code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if not all(x.isalpha() for x in string ): raise ValueError('String must only contain alphabetic characters.' ) __lowerCamelCase : Union[str, Any] = sorted(string.lower() ) return len(SCREAMING_SNAKE_CASE__ ) == len(set(SCREAMING_SNAKE_CASE__ ) ) if __name__ == "__main__": lowercase_ = input('Enter a string ').strip() lowercase_ = is_isogram(input_str) print(F"""{input_str} is {'an' if isogram else 'not an'} isogram.""")
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if density <= 0: raise ValueError('Impossible fluid density' ) if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
669
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase_ = {'configuration_yolos': ['YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'YolosConfig', 'YolosOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['YolosFeatureExtractor'] lowercase_ = ['YolosImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ '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 lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = 1 __lowerCamelCase : str = 2 while i * i <= n: __lowerCamelCase : int = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def UpperCamelCase__ ( ): __lowerCamelCase : str = 1 __lowerCamelCase : List[str] = 1 while True: i += 1 t_num += i if count_divisors(SCREAMING_SNAKE_CASE__ ) > 500: break return t_num if __name__ == "__main__": print(solution())
669
1
from __future__ import annotations from typing import Any def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): create_state_space_tree(SCREAMING_SNAKE_CASE__ , [] , 0 ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if index == len(SCREAMING_SNAKE_CASE__ ): print(SCREAMING_SNAKE_CASE__ ) return create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 ) current_subsequence.pop() if __name__ == "__main__": lowercase_ = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(['A', 'B', 'C']) generate_all_subsequences(seq)
669
import numpy as np class A_ : '''simple docstring''' def __init__( self: Optional[int] ): __lowerCamelCase : int = (0, 0) __lowerCamelCase : List[str] = None __lowerCamelCase : int = 0 __lowerCamelCase : int = 0 __lowerCamelCase : Union[str, Any] = 0 def __eq__( self: Optional[int] , a: List[Any] ): return self.position == cell.position def _snake_case ( self: Any ): print(self.position ) class A_ : '''simple docstring''' def __init__( self: str , a: List[str]=(5, 5) ): __lowerCamelCase : Optional[Any] = np.zeros(a ) __lowerCamelCase : List[str] = world_size[0] __lowerCamelCase : Optional[int] = world_size[1] def _snake_case ( self: List[Any] ): print(self.w ) def _snake_case ( self: Optional[int] , a: str ): __lowerCamelCase : Tuple = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __lowerCamelCase : Optional[int] = cell.position[0] __lowerCamelCase : List[str] = cell.position[1] __lowerCamelCase : Dict = [] for n in neughbour_cord: __lowerCamelCase : Dict = current_x + n[0] __lowerCamelCase : Optional[Any] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __lowerCamelCase : Optional[Any] = Cell() __lowerCamelCase : Any = (x, y) __lowerCamelCase : Dict = cell neighbours.append(a ) return neighbours def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = [] __lowerCamelCase : int = [] _open.append(SCREAMING_SNAKE_CASE__ ) while _open: __lowerCamelCase : Union[str, Any] = np.argmin([n.f for n in _open] ) __lowerCamelCase : int = _open[min_f] _closed.append(_open.pop(SCREAMING_SNAKE_CASE__ ) ) if current == goal: break for n in world.get_neigbours(SCREAMING_SNAKE_CASE__ ): for c in _closed: if c == n: continue __lowerCamelCase : Optional[int] = current.g + 1 __lowerCamelCase , __lowerCamelCase : int = n.position __lowerCamelCase , __lowerCamelCase : Tuple = goal.position __lowerCamelCase : Dict = (ya - ya) ** 2 + (xa - xa) ** 2 __lowerCamelCase : str = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [] while current.parent is not None: path.append(current.position ) __lowerCamelCase : int = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowercase_ = Gridworld() # Start position and goal lowercase_ = Cell() lowercase_ = (0, 0) lowercase_ = Cell() lowercase_ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowercase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowercase_ = 1 print(world.w)
669
1
from unittest import TestCase from datasets import Dataset from minhash_deduplication import deduplicate_dataset, make_duplicate_clusters def UpperCamelCase__ ( ): __lowerCamelCase : Optional[Any] = { 'repo_name': ['test_repo1', 'test_repo2', 'test_repo3'], 'path': ['test_1.py', 'test_2.py', 'unit_test.py'], 'content': ['a ' * 20, 'a ' * 30, 'b ' * 7], } __lowerCamelCase : Any = Dataset.from_dict(SCREAMING_SNAKE_CASE__ ) return dataset class A_ ( __UpperCamelCase ): '''simple docstring''' def _snake_case ( self: Optional[Any] ): __lowerCamelCase : str = get_dataset() __lowerCamelCase : int = make_duplicate_clusters(a , 0.8_5 ) self.assertEqual(len(duplicate_clusters[0] ) , 2 ) def _snake_case ( self: str ): __lowerCamelCase : int = get_dataset() __lowerCamelCase , __lowerCamelCase : Optional[int] = deduplicate_dataset(a ) self.assertEqual(len(a ) , 2 ) print(a ) self.assertEqual(duplicate_clusters[0][0]['copies'] , 2 ) self.assertEqual(duplicate_clusters[0][0]['is_extreme'] , a )
669
import math from datetime import datetime, timedelta def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = year % 19 __lowerCamelCase : int = year % 4 __lowerCamelCase : Any = year % 7 __lowerCamelCase : Dict = math.floor(year / 100 ) __lowerCamelCase : str = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCamelCase : Optional[int] = leap_day_inhibits / 4 __lowerCamelCase : str = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCamelCase : Optional[Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCamelCase : Optional[int] = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __lowerCamelCase : Tuple = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 18 ) else: return datetime(SCREAMING_SNAKE_CASE__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): lowercase_ = 'will be' if year > datetime.now().year else 'was' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
669
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from .tokenization_lxmert import LxmertTokenizer lowercase_ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} lowercase_ = { 'vocab_file': { 'unc-nlp/lxmert-base-uncased': 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/vocab.txt', }, 'tokenizer_file': { 'unc-nlp/lxmert-base-uncased': ( 'https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/tokenizer.json' ), }, } lowercase_ = { 'unc-nlp/lxmert-base-uncased': 5_1_2, } lowercase_ = { 'unc-nlp/lxmert-base-uncased': {'do_lower_case': True}, } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = LxmertTokenizer def __init__( self: int , a: Union[str, Any]=None , a: Any=None , a: Any=True , a: Optional[int]="[UNK]" , a: str="[SEP]" , a: Any="[PAD]" , a: Optional[Any]="[CLS]" , a: Union[str, Any]="[MASK]" , a: Optional[int]=True , a: str=None , **a: Optional[Any] , ): super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) __lowerCamelCase : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , a ) != do_lower_case or normalizer_state.get('strip_accents' , a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , a ) != tokenize_chinese_chars ): __lowerCamelCase : Union[str, Any] = getattr(a , normalizer_state.pop('type' ) ) __lowerCamelCase : str = do_lower_case __lowerCamelCase : str = strip_accents __lowerCamelCase : Any = tokenize_chinese_chars __lowerCamelCase : Dict = normalizer_class(**a ) __lowerCamelCase : List[str] = do_lower_case def _snake_case ( self: List[str] , a: Union[str, Any] , a: Dict=None ): __lowerCamelCase : Any = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _snake_case ( self: Union[str, Any] , a: List[int] , a: Optional[List[int]] = None ): __lowerCamelCase : Optional[int] = [self.sep_token_id] __lowerCamelCase : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case ( self: Any , a: str , a: Optional[str] = None ): __lowerCamelCase : Any = self._tokenizer.model.save(a , name=a ) return tuple(a )
669
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch 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_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' __snake_case = 1 @register_to_config def __init__( self: str , a: str=2000 , a: List[str]=0.1 , a: Any=20 , a: Dict=1e-3 ): __lowerCamelCase : Dict = None __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = None def _snake_case ( self: int , a: str , a: Union[str, torch.device] = None ): __lowerCamelCase : int = torch.linspace(1 , self.config.sampling_eps , a , device=a ) def _snake_case ( self: List[Any] , a: Union[str, Any] , a: Tuple , a: Optional[Any] , a: Dict=None ): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __lowerCamelCase : Tuple = ( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __lowerCamelCase : Optional[int] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __lowerCamelCase : Optional[Any] = std.flatten() while len(std.shape ) < len(score.shape ): __lowerCamelCase : List[str] = std.unsqueeze(-1 ) __lowerCamelCase : Any = -score / std # compute __lowerCamelCase : List[Any] = -1.0 / len(self.timesteps ) __lowerCamelCase : Any = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __lowerCamelCase : Dict = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __lowerCamelCase : int = beta_t.unsqueeze(-1 ) __lowerCamelCase : Any = -0.5 * beta_t * x __lowerCamelCase : List[Any] = torch.sqrt(a ) __lowerCamelCase : Tuple = drift - diffusion**2 * score __lowerCamelCase : str = x + drift * dt # add noise __lowerCamelCase : Any = randn_tensor(x.shape , layout=x.layout , generator=a , device=x.device , dtype=x.dtype ) __lowerCamelCase : Any = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self: Optional[int] ): return self.config.num_train_timesteps
669
1
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup lowercase_ = 'https://www.indeed.co.in/jobs?q=mobile+app+development&l=' def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ = "mumbai" ): __lowerCamelCase : List[str] = BeautifulSoup(requests.get(url + location ).content , 'html.parser' ) # This attribute finds out all the specifics listed in a job for job in soup.find_all('div' , attrs={'data-tn-component': 'organicJob'} ): __lowerCamelCase : str = job.find('a' , attrs={'data-tn-element': 'jobTitle'} ).text.strip() __lowerCamelCase : Optional[int] = job.find('span' , {'class': 'company'} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('Bangalore'), 1): print(F"""Job {i:>2} is {job[0]} at {job[1]}""")
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__ ) if n_element < 1: __lowerCamelCase : str = ValueError('a should be a positive number' ) raise my_error __lowerCamelCase : Tuple = [1] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = (0, 0, 0) __lowerCamelCase : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowercase_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') lowercase_ = hamming(int(n)) print('-----------------------------------------------------') print(F"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
669
1
import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import datasets import evaluate import numpy as np from datasets import load_dataset import transformers from transformers import ( AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, default_data_collator, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/text-classification/requirements.txt') lowercase_ = logging.getLogger(__name__) @dataclass class A_ : '''simple docstring''' __snake_case = field( default=128 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""} ) __snake_case = field( default=__UpperCamelCase , metadata={ """help""": ( """Whether to pad all samples to `max_seq_length`. """ """If False, will pad the samples dynamically when batching to the maximum length in the batch.""" ) } , ) __snake_case = field( default=__UpperCamelCase , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of training examples to this """ """value if set.""" ) } , ) __snake_case = field( default=__UpperCamelCase , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of evaluation examples to this """ """value if set.""" ) } , ) __snake_case = field( default=__UpperCamelCase , metadata={ """help""": ( """For debugging purposes or quicker training, truncate the number of prediction examples to this """ """value if set.""" ) } , ) @dataclass class A_ : '''simple docstring''' __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Evaluation language. Also train language if `train_language` is set to None."""} ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Train language if it is different from the evaluation language."""} ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"""} , ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , ) __snake_case = field( default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , ) __snake_case = field( default=__UpperCamelCase , metadata={ """help""": ( """Will use the token generated when running `huggingface-cli login` (necessary to use this script """ """with private models).""" ) } , ) __snake_case = field( default=__UpperCamelCase , metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""} , ) def UpperCamelCase__ ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __lowerCamelCase : List[str] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[int] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('run_xnli' , SCREAMING_SNAKE_CASE__ ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() __lowerCamelCase : str = training_args.get_process_log_level() logger.setLevel(SCREAMING_SNAKE_CASE__ ) datasets.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE__ ) transformers.utils.logging.set_verbosity(SCREAMING_SNAKE_CASE__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + f'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(f'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. __lowerCamelCase : List[str] = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: __lowerCamelCase : Dict = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( f'Output directory ({training_args.output_dir}) already exists and is not empty. ' 'Use --overwrite_output_dir to overcome.' ) elif last_checkpoint is not None: logger.info( f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' 'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' ) # Set seed before initializing model. set_seed(training_args.seed ) # In distributed training, the load_dataset function guarantees that only one local process can concurrently # download the dataset. # Downloading and loading xnli dataset from the hub. if training_args.do_train: if model_args.train_language is None: __lowerCamelCase : str = load_dataset( 'xnli' , model_args.language , split='train' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) else: __lowerCamelCase : Optional[int] = load_dataset( 'xnli' , model_args.train_language , split='train' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) __lowerCamelCase : str = train_dataset.features['label'].names if training_args.do_eval: __lowerCamelCase : int = load_dataset( 'xnli' , model_args.language , split='validation' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) __lowerCamelCase : Union[str, Any] = eval_dataset.features['label'].names if training_args.do_predict: __lowerCamelCase : List[Any] = load_dataset( 'xnli' , model_args.language , split='test' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) __lowerCamelCase : str = predict_dataset.features['label'].names # Labels __lowerCamelCase : Union[str, Any] = len(SCREAMING_SNAKE_CASE__ ) # Load pretrained model and tokenizer # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __lowerCamelCase : Optional[int] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=SCREAMING_SNAKE_CASE__ , idalabel={str(SCREAMING_SNAKE_CASE__ ): label for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} , labelaid={label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} , finetuning_task='xnli' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __lowerCamelCase : Dict = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) __lowerCamelCase : str = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=SCREAMING_SNAKE_CASE__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) # Preprocessing the datasets # Padding strategy if data_args.pad_to_max_length: __lowerCamelCase : Tuple = 'max_length' else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch __lowerCamelCase : Any = False def preprocess_function(SCREAMING_SNAKE_CASE__ ): # Tokenize the texts return tokenizer( examples['premise'] , examples['hypothesis'] , padding=SCREAMING_SNAKE_CASE__ , max_length=data_args.max_seq_length , truncation=SCREAMING_SNAKE_CASE__ , ) if training_args.do_train: if data_args.max_train_samples is not None: __lowerCamelCase : Any = min(len(SCREAMING_SNAKE_CASE__ ) , data_args.max_train_samples ) __lowerCamelCase : int = train_dataset.select(range(SCREAMING_SNAKE_CASE__ ) ) with training_args.main_process_first(desc='train dataset map pre-processing' ): __lowerCamelCase : Union[str, Any] = train_dataset.map( SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on train dataset' , ) # Log a few random samples from the training set: for index in random.sample(range(len(SCREAMING_SNAKE_CASE__ ) ) , 3 ): logger.info(f'Sample {index} of the training set: {train_dataset[index]}.' ) if training_args.do_eval: if data_args.max_eval_samples is not None: __lowerCamelCase : List[Any] = min(len(SCREAMING_SNAKE_CASE__ ) , data_args.max_eval_samples ) __lowerCamelCase : List[str] = eval_dataset.select(range(SCREAMING_SNAKE_CASE__ ) ) with training_args.main_process_first(desc='validation dataset map pre-processing' ): __lowerCamelCase : Any = eval_dataset.map( SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on validation dataset' , ) if training_args.do_predict: if data_args.max_predict_samples is not None: __lowerCamelCase : Optional[int] = min(len(SCREAMING_SNAKE_CASE__ ) , data_args.max_predict_samples ) __lowerCamelCase : Optional[int] = predict_dataset.select(range(SCREAMING_SNAKE_CASE__ ) ) with training_args.main_process_first(desc='prediction dataset map pre-processing' ): __lowerCamelCase : int = predict_dataset.map( SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on prediction dataset' , ) # Get the metric function __lowerCamelCase : Optional[int] = evaluate.load('xnli' ) # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[str] = p.predictions[0] if isinstance(p.predictions , SCREAMING_SNAKE_CASE__ ) else p.predictions __lowerCamelCase : Union[str, Any] = np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) return metric.compute(predictions=SCREAMING_SNAKE_CASE__ , references=p.label_ids ) # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: __lowerCamelCase : Tuple = default_data_collator elif training_args.fpaa: __lowerCamelCase : int = DataCollatorWithPadding(SCREAMING_SNAKE_CASE__ , pad_to_multiple_of=8 ) else: __lowerCamelCase : str = None # Initialize our Trainer __lowerCamelCase : Tuple = Trainer( model=SCREAMING_SNAKE_CASE__ , args=SCREAMING_SNAKE_CASE__ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ , data_collator=SCREAMING_SNAKE_CASE__ , ) # Training if training_args.do_train: __lowerCamelCase : Union[str, Any] = None if training_args.resume_from_checkpoint is not None: __lowerCamelCase : Union[str, Any] = training_args.resume_from_checkpoint elif last_checkpoint is not None: __lowerCamelCase : Tuple = last_checkpoint __lowerCamelCase : List[str] = trainer.train(resume_from_checkpoint=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = train_result.metrics __lowerCamelCase : str = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : Optional[Any] = min(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics('train' , SCREAMING_SNAKE_CASE__ ) trainer.save_metrics('train' , SCREAMING_SNAKE_CASE__ ) trainer.save_state() # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) __lowerCamelCase : Dict = trainer.evaluate(eval_dataset=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = min(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) trainer.log_metrics('eval' , SCREAMING_SNAKE_CASE__ ) trainer.save_metrics('eval' , SCREAMING_SNAKE_CASE__ ) # Prediction if training_args.do_predict: logger.info('*** Predict ***' ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Dict = trainer.predict(SCREAMING_SNAKE_CASE__ , metric_key_prefix='predict' ) __lowerCamelCase : Optional[int] = ( data_args.max_predict_samples if data_args.max_predict_samples is not None else len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : List[Any] = min(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) trainer.log_metrics('predict' , SCREAMING_SNAKE_CASE__ ) trainer.save_metrics('predict' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Union[str, Any] = np.argmax(SCREAMING_SNAKE_CASE__ , axis=1 ) __lowerCamelCase : List[str] = os.path.join(training_args.output_dir , 'predictions.txt' ) if trainer.is_world_process_zero(): with open(SCREAMING_SNAKE_CASE__ , 'w' ) as writer: writer.write('index\tprediction\n' ) for index, item in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = label_list[item] writer.write(f'{index}\t{item}\n' ) if __name__ == "__main__": main()
669
import unittest from knapsack import greedy_knapsack as kp class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: List[Any] ): __lowerCamelCase : str = [10, 20, 30, 40, 50, 60] __lowerCamelCase : List[str] = [2, 4, 6, 8, 10, 12] __lowerCamelCase : Tuple = 100 self.assertEqual(kp.calc_profit(a , a , a ) , 210 ) def _snake_case ( self: str ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'Weight can not be negative.' ) def _snake_case ( self: Dict ): self.assertRaisesRegex(a , 'Profit can not be negative.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: Any ): self.assertRaisesRegex( a , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
669
1
from random import randint, random def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = 5 , ): __lowerCamelCase : Union[str, Any] = [[-1] * number_of_cells] # Create a highway without any car __lowerCamelCase : Tuple = 0 __lowerCamelCase : Optional[int] = max(SCREAMING_SNAKE_CASE__ , 0 ) while i < number_of_cells: __lowerCamelCase : List[Any] = ( randint(0 , SCREAMING_SNAKE_CASE__ ) if random_speed else initial_speed ) # Place the cars i += ( randint(1 , max_speed * 2 ) if random_frequency else frequency ) # Arbitrary number, may need tuning return highway def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = 0 __lowerCamelCase : Dict = highway_now[car_index + 1 :] for cell in range(len(SCREAMING_SNAKE_CASE__ ) ): # May need a better name for this if cells[cell] != -1: # If the cell is not empty then return distance # we have the distance we wanted distance += 1 # Here if the car is near the end of the highway return distance + get_distance(SCREAMING_SNAKE_CASE__ , -1 ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = len(SCREAMING_SNAKE_CASE__ ) # Beforce calculations, the highway is empty __lowerCamelCase : Optional[int] = [-1] * number_of_cells for car_index in range(SCREAMING_SNAKE_CASE__ ): if highway_now[car_index] != -1: # Add 1 to the current speed of the car and cap the speed __lowerCamelCase : List[Any] = min(highway_now[car_index] + 1 , SCREAMING_SNAKE_CASE__ ) # Number of empty cell before the next car __lowerCamelCase : List[Any] = get_distance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) - 1 # We can't have the car causing an accident __lowerCamelCase : List[str] = min(next_highway[car_index] , SCREAMING_SNAKE_CASE__ ) if random() < probability: # Randomly, a driver will slow down __lowerCamelCase : Optional[int] = max(next_highway[car_index] - 1 , 0 ) return next_highway def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[str] = len(highway[0] ) for i in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = update(highway[i] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [-1] * number_of_cells for car_index in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = next_speeds_calculated[car_index] if speed != -1: # Change the position based on the speed (with % to create the loop) __lowerCamelCase : Any = (car_index + speed) % number_of_cells # Commit the change of position __lowerCamelCase : Optional[int] = speed highway.append(SCREAMING_SNAKE_CASE__ ) return highway if __name__ == "__main__": import doctest doctest.testmod()
669
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any]=2 , a: str=3 , a: Any=4 , a: Union[str, Any]=2 , a: Tuple=7 , a: int=True , a: Tuple=True , a: List[str]=True , a: Union[str, Any]=True , a: str=99 , a: Tuple=36 , a: int=2 , a: Dict=4 , a: Union[str, Any]=37 , a: List[str]="gelu" , a: List[Any]=0.1 , a: Optional[int]=0.1 , a: Dict=512 , a: Union[str, Any]=16 , a: str=2 , a: int=0.0_2 , a: Optional[Any]=6 , a: Optional[int]=6 , a: Dict=3 , a: Optional[Any]=4 , a: Optional[Any]=None , a: Dict=1000 , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Optional[int] = num_channels __lowerCamelCase : str = image_size __lowerCamelCase : int = patch_size __lowerCamelCase : List[str] = is_training __lowerCamelCase : Dict = use_input_mask __lowerCamelCase : Any = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : str = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : List[Any] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : int = type_sequence_label_size __lowerCamelCase : List[str] = initializer_range __lowerCamelCase : List[str] = coordinate_size __lowerCamelCase : int = shape_size __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : int = num_choices __lowerCamelCase : int = scope __lowerCamelCase : Any = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __lowerCamelCase : Any = text_seq_length __lowerCamelCase : Optional[Any] = (image_size // patch_size) ** 2 + 1 __lowerCamelCase : Any = self.text_seq_length + self.image_seq_length def _snake_case ( self: List[str] ): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __lowerCamelCase : int = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __lowerCamelCase : List[str] = bbox[i, j, 3] __lowerCamelCase : str = bbox[i, j, 1] __lowerCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __lowerCamelCase : Tuple = bbox[i, j, 2] __lowerCamelCase : Any = bbox[i, j, 0] __lowerCamelCase : List[str] = tmp_coordinate __lowerCamelCase : str = tf.constant(a ) __lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.text_seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __lowerCamelCase : Dict = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self: Tuple , a: List[Any] , a: Any , a: List[str] , a: Dict , a: Optional[Any] , a: Dict ): __lowerCamelCase : Optional[Any] = TFLayoutLMvaModel(config=a ) # text + image __lowerCamelCase : Optional[Any] = model(a , pixel_values=a , training=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , training=a , ) __lowerCamelCase : List[Any] = model(a , bbox=a , pixel_values=a , training=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __lowerCamelCase : List[Any] = model(a , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __lowerCamelCase : Optional[Any] = model({'pixel_values': pixel_values} , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self: Dict , a: Dict , a: Optional[Any] , a: int , a: Optional[int] , a: List[str] , a: List[str] , a: List[str] ): __lowerCamelCase : List[str] = self.num_labels __lowerCamelCase : str = TFLayoutLMvaForSequenceClassification(config=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any] , a: Dict , a: Optional[Any] , a: Tuple , a: Optional[Any] , a: List[Any] ): __lowerCamelCase : Union[str, Any] = self.num_labels __lowerCamelCase : Any = TFLayoutLMvaForTokenClassification(config=a ) __lowerCamelCase : Optional[Any] = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self: Dict , a: Optional[Any] , a: str , a: Dict , a: Union[str, Any] , a: List[Any] , a: Optional[int] , a: List[str] ): __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Any = TFLayoutLMvaForQuestionAnswering(config=a ) __lowerCamelCase : Any = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , training=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] ): __lowerCamelCase : str = self.prepare_config_and_inputs() ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : List[Any] = config_and_inputs __lowerCamelCase : Tuple = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: int , a: List[str] , a: Any , a: Optional[Any] , a: Tuple , a: Tuple ): return True def _snake_case ( self: str , a: Any , a: Any , a: Optional[int]=False ): __lowerCamelCase : List[str] = copy.deepcopy(a ) if model_class in get_values(a ): __lowerCamelCase : Tuple = { k: tf.tile(tf.expand_dims(a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a ): __lowerCamelCase : Any = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Dict = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def _snake_case ( self: Tuple ): __lowerCamelCase : int = TFLayoutLMvaModelTester(self ) __lowerCamelCase : str = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self: Union[str, Any] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : int = model_class(a ) if getattr(a , 'hf_compute_loss' , a ): # The number of elements in the loss should be the same as the number of elements in the label __lowerCamelCase : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : int = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=a )[0] ] __lowerCamelCase : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __lowerCamelCase : Optional[int] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : Dict = prepared_for_class.pop('input_ids' ) __lowerCamelCase : str = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __lowerCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : List[str] = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __lowerCamelCase : int = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __lowerCamelCase : Tuple = -100 __lowerCamelCase : Tuple = tf.convert_to_tensor(a ) __lowerCamelCase : Tuple = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __lowerCamelCase : int = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : str = model(a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __lowerCamelCase : str = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) # Get keys that were added with the _prepare_for_class function __lowerCamelCase : Optional[Any] = prepared_for_class.keys() - inputs_dict.keys() __lowerCamelCase : List[Any] = inspect.signature(model.call ).parameters __lowerCamelCase : List[str] = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __lowerCamelCase : Optional[int] = {0: 'input_ids'} for label_key in label_keys: __lowerCamelCase : Dict = signature_names.index(a ) __lowerCamelCase : str = label_key __lowerCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __lowerCamelCase : Optional[int] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __lowerCamelCase : Optional[int] = prepared_for_class[value] __lowerCamelCase : Any = tuple(a ) # Send to model __lowerCamelCase : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def _snake_case ( self: List[str] ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: int ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: Dict ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( a , a , a , a , a , a , a ) @slow def _snake_case ( self: int ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Dict = TFLayoutLMvaModel.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self: Optional[int] ): return LayoutLMvaImageProcessor(apply_ocr=a ) if is_vision_available() else None @slow def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Tuple = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __lowerCamelCase : Union[str, Any] = self.default_image_processor __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : str = image_processor(images=a , return_tensors='tf' ).pixel_values __lowerCamelCase : Union[str, Any] = tf.constant([[1, 2]] ) __lowerCamelCase : str = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __lowerCamelCase : int = model(input_ids=a , bbox=a , pixel_values=a , training=a ) # verify the logits __lowerCamelCase : Optional[int] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , a ) __lowerCamelCase : Any = tf.constant( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-4 ) )
669
1
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device lowercase_ = False class A_ ( unittest.TestCase ): '''simple docstring''' pass @nightly @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: int ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Tuple ): __lowerCamelCase : Any = VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion' , torch_dtype=torch.floataa ) pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : List[str] = pipe.dual_guided( prompt='first prompt' , image=a , text_to_image_strength=0.7_5 , generator=a , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(a ) __lowerCamelCase : List[Any] = VersatileDiffusionPipeline.from_pretrained(a , torch_dtype=torch.floataa ) pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = generator.manual_seed(0 ) __lowerCamelCase : Dict = pipe.dual_guided( prompt='first prompt' , image=a , text_to_image_strength=0.7_5 , generator=a , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' , ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion' , torch_dtype=torch.floataa ) pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = 'cyberpunk 2077' __lowerCamelCase : Any = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' ) __lowerCamelCase : str = torch.manual_seed(0 ) __lowerCamelCase : Optional[Any] = pipe.dual_guided( prompt=a , image=a , text_to_image_strength=0.7_5 , generator=a , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' , ).images __lowerCamelCase : Any = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __lowerCamelCase : int = np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 __lowerCamelCase : Optional[Any] = 'A painting of a squirrel eating a burger ' __lowerCamelCase : Union[str, Any] = torch.manual_seed(0 ) __lowerCamelCase : Dict = pipe.text_to_image( prompt=a , generator=a , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' ).images __lowerCamelCase : str = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __lowerCamelCase : List[str] = np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 __lowerCamelCase : List[str] = pipe.image_variation(a , generator=a , output_type='numpy' ).images __lowerCamelCase : List[Any] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __lowerCamelCase : str = np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
669
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = CLIPTokenizer __snake_case = CLIPTokenizerFast __snake_case = True __snake_case = {} __snake_case = False def _snake_case ( self: Union[str, Any] ): super().setUp() # fmt: off __lowerCamelCase : Any = ['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 __lowerCamelCase : Tuple = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : List[Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>'] __lowerCamelCase : Tuple = {'unk_token': '<unk>'} __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : 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(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: Tuple , **a: Union[str, Any] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Union[str, Any] , **a: List[str] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : Tuple = 'lower newer' __lowerCamelCase : Tuple = 'lower newer' return input_text, output_text def _snake_case ( self: List[str] ): __lowerCamelCase : List[Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase : Optional[Any] = 'lower newer' __lowerCamelCase : int = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>'] __lowerCamelCase : Optional[int] = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : int = tokens + [tokenizer.unk_token] __lowerCamelCase : int = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def _snake_case ( self: Union[str, Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[Any] = self.tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : int = self.rust_tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : str = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.' __lowerCamelCase : Optional[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[Any] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __lowerCamelCase : List[Any] = 'xa\u0303y' + ' ' + 'x\xe3y' __lowerCamelCase : Tuple = tokenizer_s.tokenize(a ) __lowerCamelCase : Any = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type __lowerCamelCase : List[Any] = [ '\u0009', # (horizontal tab, '\t') '\u000B', # (vertical tab) '\u000C', # (form feed) '\u0020', # (space, ' ') '\u200E', # (left-to-right mark):w '\u200F', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __lowerCamelCase : List[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[int] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type __lowerCamelCase : str = [ '\u000A', # (line feed, '\n') '\r\n', # (carriage return and line feed, '\r\n') '\u000D', # (carriage return, '\r') '\r', # (carriage return, '\r') '\u000D', # (carriage return, '\r') '\u2028', # (line separator) '\u2029', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __lowerCamelCase : Dict = tokenizer_s.tokenize(a ) __lowerCamelCase : List[str] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def _snake_case ( self: List[Any] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : Optional[int] = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` __lowerCamelCase : Optional[int] = F'{text_of_1_token} {text_of_1_token}' __lowerCamelCase : Dict = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) __lowerCamelCase : List[Any] = F' {text}' __lowerCamelCase : str = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def _snake_case ( self: str ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def _snake_case ( self: Tuple ): super().test_tokenization_python_rust_equals() def _snake_case ( self: Tuple ): # CLIP always lower cases letters pass
669
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'MIT/ast-finetuned-audioset-10-10-0.4593': ( 'https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """audio-spectrogram-transformer""" def __init__( self: Dict , a: Any=768 , a: Optional[int]=12 , a: Any=12 , a: int=3072 , a: Dict="gelu" , a: Optional[Any]=0.0 , a: Optional[int]=0.0 , a: Tuple=0.0_2 , a: int=1e-12 , a: str=16 , a: Optional[Any]=True , a: str=10 , a: Optional[Any]=10 , a: Any=1024 , a: Tuple=128 , **a: Optional[Any] , ): super().__init__(**a ) __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : List[str] = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : Union[str, Any] = hidden_act __lowerCamelCase : Dict = hidden_dropout_prob __lowerCamelCase : Optional[Any] = attention_probs_dropout_prob __lowerCamelCase : str = initializer_range __lowerCamelCase : Any = layer_norm_eps __lowerCamelCase : str = patch_size __lowerCamelCase : int = qkv_bias __lowerCamelCase : Any = frequency_stride __lowerCamelCase : Union[str, Any] = time_stride __lowerCamelCase : Union[str, Any] = max_length __lowerCamelCase : List[Any] = num_mel_bins
669
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowercase_ = False try: lowercase_ = _is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class A_ : '''simple docstring''' def __init__( self: int , a: str = None , a: list = [] ): __lowerCamelCase : Dict = 0 __lowerCamelCase : Dict = choices __lowerCamelCase : Tuple = prompt if sys.platform == "win32": __lowerCamelCase : Union[str, Any] = '*' else: __lowerCamelCase : Any = '➔ ' def _snake_case ( self: Any , a: Tuple , a: str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def _snake_case ( self: Tuple , a: int ): if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def _snake_case ( self: Optional[int] , a: Direction , a: int = 1 ): __lowerCamelCase : str = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['up'] ) def _snake_case ( self: Tuple ): self.move_direction(Direction.UP ) @input.mark(KEYMAP['down'] ) def _snake_case ( self: Optional[int] ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['newline'] ) def _snake_case ( self: str ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) return self.position @input.mark(KEYMAP['interrupt'] ) def _snake_case ( self: Union[str, Any] ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def _snake_case ( self: str ): __lowerCamelCase : List[Any] = int(chr(self.current_selection ) ) __lowerCamelCase : Any = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def _snake_case ( self: str , a: int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , '\n' ) if in_colab: forceWrite('Please input a choice index (starting from 0), and press enter' , '\n' ) else: forceWrite('Please select a choice using the arrow or number keys, and selecting with enter' , '\n' ) __lowerCamelCase : Dict = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('\n' ) move_cursor(len(self.choices ) - self.position , 'UP' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase : Any = int(builtins.input() ) except ValueError: __lowerCamelCase : str = default_choice else: __lowerCamelCase : Optional[int] = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , 'UP' ) clear_line() self.write_choice(a , '\n' ) return choice
669
1
import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification lowercase_ = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co lowercase_ = 'main' # Default branch name lowercase_ = 'f2c752cfc5c0ab6f4bdec59acea69eefbee381c2' # One particular commit (not the top of `main`) lowercase_ = 'aaaaaaa' # This commit does not exist, so we should 404. lowercase_ = 'd9e9f15bc825e4b2c9249e9578f884bbcb5e3684' # Sha-1 of config.json on the top of `main`, for checking purposes lowercase_ = '4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3' @contextlib.contextmanager def UpperCamelCase__ ( ): print('Welcome!' ) yield print('Bye!' ) @contextlib.contextmanager def UpperCamelCase__ ( ): print('Bonjour!' ) yield print('Au revoir!' ) class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: List[str] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('transformers' ) is not None class A_ ( unittest.TestCase ): '''simple docstring''' @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO ) def _snake_case ( self: Optional[Any] , a: Optional[Any] ): with ContextManagers([] ): print('Transformers are awesome!' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , 'Transformers are awesome!\n' ) @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO ) def _snake_case ( self: Tuple , a: int ): with ContextManagers([context_en()] ): print('Transformers are awesome!' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Welcome!\nTransformers are awesome!\nBye!\n' ) @unittest.mock.patch('sys.stdout' , new_callable=io.StringIO ) def _snake_case ( self: List[str] , a: str ): with ContextManagers([context_fr(), context_en()] ): print('Transformers are awesome!' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , 'Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n' ) @require_torch def _snake_case ( self: List[Any] ): self.assertEqual(find_labels(a ) , ['labels'] ) self.assertEqual(find_labels(a ) , ['labels', 'next_sentence_label'] ) self.assertEqual(find_labels(a ) , ['start_positions', 'end_positions'] ) class A_ ( __UpperCamelCase ): '''simple docstring''' pass self.assertEqual(find_labels(a ) , ['labels'] ) @require_tf def _snake_case ( self: Optional[int] ): self.assertEqual(find_labels(a ) , ['labels'] ) self.assertEqual(find_labels(a ) , ['labels', 'next_sentence_label'] ) self.assertEqual(find_labels(a ) , ['start_positions', 'end_positions'] ) class A_ ( __UpperCamelCase ): '''simple docstring''' pass self.assertEqual(find_labels(a ) , ['labels'] ) @require_flax def _snake_case ( self: Union[str, Any] ): # Flax models don't have labels self.assertEqual(find_labels(a ) , [] ) self.assertEqual(find_labels(a ) , [] ) self.assertEqual(find_labels(a ) , [] ) class A_ ( __UpperCamelCase ): '''simple docstring''' pass self.assertEqual(find_labels(a ) , [] )
669
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = (CMStochasticIterativeScheduler,) __snake_case = 10 def _snake_case ( self: Any , **a: Dict ): __lowerCamelCase : Optional[Any] = { 'num_train_timesteps': 201, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } config.update(**a ) return config def _snake_case ( self: List[Any] ): __lowerCamelCase : Any = 10 __lowerCamelCase : Any = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = self.scheduler_classes[0](**a ) scheduler.set_timesteps(a ) __lowerCamelCase : Any = scheduler.timesteps[0] __lowerCamelCase : List[str] = scheduler.timesteps[1] __lowerCamelCase : Union[str, Any] = self.dummy_sample __lowerCamelCase : int = 0.1 * sample __lowerCamelCase : Optional[Any] = scheduler.step(a , a , a ).prev_sample __lowerCamelCase : List[str] = scheduler.step(a , a , a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self: Optional[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a ) def _snake_case ( self: List[str] ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=a ) def _snake_case ( self: Tuple ): __lowerCamelCase : Tuple = self.scheduler_classes[0] __lowerCamelCase : Tuple = self.get_scheduler_config() __lowerCamelCase : Tuple = scheduler_class(**a ) __lowerCamelCase : int = 1 scheduler.set_timesteps(a ) __lowerCamelCase : Optional[int] = scheduler.timesteps __lowerCamelCase : List[str] = torch.manual_seed(0 ) __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(a ): # 1. scale model input __lowerCamelCase : List[str] = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Optional[int] = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : str = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : str = pred_prev_sample __lowerCamelCase : List[str] = torch.sum(torch.abs(a ) ) __lowerCamelCase : str = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**a ) __lowerCamelCase : List[Any] = [106, 0] scheduler.set_timesteps(timesteps=a ) __lowerCamelCase : Dict = scheduler.timesteps __lowerCamelCase : int = torch.manual_seed(0 ) __lowerCamelCase : Any = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __lowerCamelCase : Tuple = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Tuple = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : Any = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : Any = pred_prev_sample __lowerCamelCase : Dict = torch.sum(torch.abs(a ) ) __lowerCamelCase : Optional[Any] = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : int = self.get_scheduler_config() __lowerCamelCase : List[Any] = scheduler_class(**a ) __lowerCamelCase : Optional[Any] = [39, 30, 12, 15, 0] with self.assertRaises(a , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=a ) def _snake_case ( self: int ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Union[str, Any] = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [39, 30, 12, 1, 0] __lowerCamelCase : List[Any] = len(a ) with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=a , timesteps=a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Dict = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=a )
669
1
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets lowercase_ = '\n@inproceedings{xu-etal-2016-optimizing,\n title = {Optimizing Statistical Machine Translation for Text Simplification},\n authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},\n journal = {Transactions of the Association for Computational Linguistics},\n volume = {4},\n year={2016},\n url = {https://www.aclweb.org/anthology/Q16-1029},\n pages = {401--415\n},\n@inproceedings{post-2018-call,\n title = "A Call for Clarity in Reporting {BLEU} Scores",\n author = "Post, Matt",\n booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",\n month = oct,\n year = "2018",\n address = "Belgium, Brussels",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W18-6319",\n pages = "186--191",\n}\n' lowercase_ = '\\nWIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU\nIt can be used to evaluate the quality of machine-generated texts.\n' lowercase_ = '\nCalculates sari score (between 0 and 100) given a list of source and predicted\nsentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.\nArgs:\n sources: list of source sentences where each sentence should be a string.\n predictions: list of predicted sentences where each sentence should be a string.\n references: list of lists of reference sentences where each sentence should be a string.\nReturns:\n sari: sari score\n sacrebleu: sacrebleu score\n exact: exact score\n\nExamples:\n >>> sources=["About 95 species are currently accepted ."]\n >>> predictions=["About 95 you now get in ."]\n >>> references=[["About 95 species are currently known ."]]\n >>> wiki_split = datasets.load_metric("wiki_split")\n >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)\n >>> print(results)\n {\'sari\': 21.805555555555557, \'sacrebleu\': 14.535768424205482, \'exact\': 0.0}\n' def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): def remove_articles(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = re.compile(r'\b(a|an|the)\b' , re.UNICODE ) return re.sub(SCREAMING_SNAKE_CASE__ , ' ' , SCREAMING_SNAKE_CASE__ ) def white_space_fix(SCREAMING_SNAKE_CASE__ ): return " ".join(text.split() ) def remove_punc(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[str] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(SCREAMING_SNAKE_CASE__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(SCREAMING_SNAKE_CASE__ ) ) ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return int(normalize_answer(SCREAMING_SNAKE_CASE__ ) == normalize_answer(SCREAMING_SNAKE_CASE__ ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = [any(compute_exact(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for ref in refs ) for pred, refs in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )] return (sum(SCREAMING_SNAKE_CASE__ ) / len(SCREAMING_SNAKE_CASE__ )) * 100 def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = [rgram for rgrams in rgramslist for rgram in rgrams] __lowerCamelCase : str = Counter(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = Counter(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = Counter() for sgram, scount in sgramcounter.items(): __lowerCamelCase : List[Any] = scount * numref __lowerCamelCase : List[Any] = Counter(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = Counter() for cgram, ccount in cgramcounter.items(): __lowerCamelCase : Optional[int] = ccount * numref # KEEP __lowerCamelCase : Any = sgramcounter_rep & cgramcounter_rep __lowerCamelCase : Optional[int] = keepgramcounter_rep & rgramcounter __lowerCamelCase : List[Any] = sgramcounter_rep & rgramcounter __lowerCamelCase : Any = 0 __lowerCamelCase : Optional[int] = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __lowerCamelCase : Tuple = 1 __lowerCamelCase : Tuple = 1 if len(SCREAMING_SNAKE_CASE__ ) > 0: __lowerCamelCase : Any = keeptmpscorea / len(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) __lowerCamelCase : Dict = keeptmpscorea / sum(keepgramcounterall_rep.values() ) __lowerCamelCase : Any = 0 if keepscore_precision > 0 or keepscore_recall > 0: __lowerCamelCase : Tuple = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION __lowerCamelCase : Tuple = sgramcounter_rep - cgramcounter_rep __lowerCamelCase : Tuple = delgramcounter_rep - rgramcounter __lowerCamelCase : Union[str, Any] = sgramcounter_rep - rgramcounter __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[int] = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __lowerCamelCase : Optional[int] = 1 if len(SCREAMING_SNAKE_CASE__ ) > 0: __lowerCamelCase : str = deltmpscorea / len(SCREAMING_SNAKE_CASE__ ) # ADDITION __lowerCamelCase : Union[str, Any] = set(SCREAMING_SNAKE_CASE__ ) - set(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Dict = set(SCREAMING_SNAKE_CASE__ ) & set(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = set(SCREAMING_SNAKE_CASE__ ) - set(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. __lowerCamelCase : int = 1 __lowerCamelCase : Dict = 1 if len(SCREAMING_SNAKE_CASE__ ) > 0: __lowerCamelCase : Optional[int] = addtmpscore / len(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: __lowerCamelCase : Tuple = addtmpscore / len(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = 0 if addscore_precision > 0 or addscore_recall > 0: __lowerCamelCase : int = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = len(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = ssent.split(' ' ) __lowerCamelCase : List[str] = csent.split(' ' ) __lowerCamelCase : Dict = [] __lowerCamelCase : Any = [] __lowerCamelCase : Union[str, Any] = [] __lowerCamelCase : List[str] = [] __lowerCamelCase : int = [] __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : Optional[int] = [] __lowerCamelCase : Any = [] __lowerCamelCase : Optional[Any] = [] __lowerCamelCase : int = [] for rsent in rsents: __lowerCamelCase : Optional[Any] = rsent.split(' ' ) __lowerCamelCase : Any = [] __lowerCamelCase : Dict = [] __lowerCamelCase : int = [] ragramslist.append(SCREAMING_SNAKE_CASE__ ) for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ): if i < len(SCREAMING_SNAKE_CASE__ ) - 1: __lowerCamelCase : str = ragrams[i] + ' ' + ragrams[i + 1] ragrams.append(SCREAMING_SNAKE_CASE__ ) if i < len(SCREAMING_SNAKE_CASE__ ) - 2: __lowerCamelCase : Optional[int] = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] ragrams.append(SCREAMING_SNAKE_CASE__ ) if i < len(SCREAMING_SNAKE_CASE__ ) - 3: __lowerCamelCase : Optional[int] = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] + ' ' + ragrams[i + 3] ragrams.append(SCREAMING_SNAKE_CASE__ ) ragramslist.append(SCREAMING_SNAKE_CASE__ ) ragramslist.append(SCREAMING_SNAKE_CASE__ ) ragramslist.append(SCREAMING_SNAKE_CASE__ ) for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ): if i < len(SCREAMING_SNAKE_CASE__ ) - 1: __lowerCamelCase : Optional[int] = sagrams[i] + ' ' + sagrams[i + 1] sagrams.append(SCREAMING_SNAKE_CASE__ ) if i < len(SCREAMING_SNAKE_CASE__ ) - 2: __lowerCamelCase : int = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] sagrams.append(SCREAMING_SNAKE_CASE__ ) if i < len(SCREAMING_SNAKE_CASE__ ) - 3: __lowerCamelCase : List[Any] = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] + ' ' + sagrams[i + 3] sagrams.append(SCREAMING_SNAKE_CASE__ ) for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ): if i < len(SCREAMING_SNAKE_CASE__ ) - 1: __lowerCamelCase : Any = cagrams[i] + ' ' + cagrams[i + 1] cagrams.append(SCREAMING_SNAKE_CASE__ ) if i < len(SCREAMING_SNAKE_CASE__ ) - 2: __lowerCamelCase : Dict = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] cagrams.append(SCREAMING_SNAKE_CASE__ ) if i < len(SCREAMING_SNAKE_CASE__ ) - 3: __lowerCamelCase : Optional[int] = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] + ' ' + cagrams[i + 3] cagrams.append(SCREAMING_SNAKE_CASE__ ) ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : Union[str, Any] = SARIngram(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : Union[str, Any] = SARIngram(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : Tuple = SARIngram(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : Optional[int] = SARIngram(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 __lowerCamelCase : Optional[int] = sum([delascore, delascore, delascore, delascore] ) / 4 __lowerCamelCase : str = sum([addascore, addascore, addascore, addascore] ) / 4 __lowerCamelCase : Optional[Any] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = "13a" , SCREAMING_SNAKE_CASE__ = True ): # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: __lowerCamelCase : Optional[int] = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: __lowerCamelCase : Union[str, Any] = sacrebleu.metrics.bleu._get_tokenizer(SCREAMING_SNAKE_CASE__ )()(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase : Union[str, Any] = sacrebleu.TOKENIZERS[tokenizer]()(SCREAMING_SNAKE_CASE__ ) elif tokenizer == "moses": __lowerCamelCase : List[str] = sacremoses.MosesTokenizer().tokenize(SCREAMING_SNAKE_CASE__ , return_str=SCREAMING_SNAKE_CASE__ , escape=SCREAMING_SNAKE_CASE__ ) elif tokenizer == "penn": __lowerCamelCase : str = sacremoses.MosesTokenizer().penn_tokenize(SCREAMING_SNAKE_CASE__ , return_str=SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase : Tuple = sentence if not return_str: __lowerCamelCase : Tuple = normalized_sent.split() return normalized_sent def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if not (len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ )): raise ValueError('Sources length must match predictions and references lengths.' ) __lowerCamelCase : List[str] = 0 for src, pred, refs in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): sari_score += SARIsent(normalize(SCREAMING_SNAKE_CASE__ ) , normalize(SCREAMING_SNAKE_CASE__ ) , [normalize(SCREAMING_SNAKE_CASE__ ) for sent in refs] ) __lowerCamelCase : int = sari_score / len(SCREAMING_SNAKE_CASE__ ) return 100 * sari_score def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="exp" , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False , ): __lowerCamelCase : Optional[int] = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('Sacrebleu requires the same number of references for each prediction' ) __lowerCamelCase : Tuple = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase : Union[str, Any] = sacrebleu.corpus_bleu( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , smooth_method=SCREAMING_SNAKE_CASE__ , smooth_value=SCREAMING_SNAKE_CASE__ , force=SCREAMING_SNAKE_CASE__ , lowercase=SCREAMING_SNAKE_CASE__ , use_effective_order=SCREAMING_SNAKE_CASE__ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): '''simple docstring''' def _snake_case ( self: List[Any] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , 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/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py', 'https://github.com/cocoxu/simplification/blob/master/SARI.py', 'https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py', 'https://github.com/mjpost/sacreBLEU', ] , reference_urls=[ 'https://www.aclweb.org/anthology/Q16-1029.pdf', 'https://github.com/mjpost/sacreBLEU', 'https://en.wikipedia.org/wiki/BLEU', 'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213', ] , ) def _snake_case ( self: Union[str, Any] , a: Optional[int] , a: Any , a: int ): __lowerCamelCase : Any = {} result.update({'sari': compute_sari(sources=a , predictions=a , references=a )} ) result.update({'sacrebleu': compute_sacrebleu(predictions=a , references=a )} ) result.update({'exact': compute_em(predictions=a , references=a )} ) return result
669
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") lowercase_ = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find('meta', {'property': 'og:image'})['content'] lowercase_ = requests.get(image_url).content lowercase_ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
669
1
import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class A_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' @register_to_config def __init__( self: Union[str, Any] , *, a: int = 4 , a: int = 768 , a: int , a: str , ): super().__init__() __lowerCamelCase : Any = nn.Parameter(torch.zeros(a ) ) # parameters for additional clip time embeddings __lowerCamelCase : str = nn.Linear(a , a ) __lowerCamelCase : Dict = nn.Linear(a , a ) # parameters for encoder hidden states __lowerCamelCase : Tuple = clip_extra_context_tokens __lowerCamelCase : Optional[Any] = nn.Linear( a , self.clip_extra_context_tokens * cross_attention_dim ) __lowerCamelCase : Optional[int] = nn.Linear(a , a ) __lowerCamelCase : Tuple = nn.LayerNorm(a ) def _snake_case ( self: Any , *, a: Union[str, Any] , a: List[str] , a: List[Any] , a: Dict ): if do_classifier_free_guidance: # Add the classifier free guidance embeddings to the image embeddings __lowerCamelCase : List[Any] = image_embeddings.shape[0] __lowerCamelCase : Any = self.learned_classifier_free_guidance_embeddings.unsqueeze(0 ) __lowerCamelCase : List[str] = classifier_free_guidance_embeddings.expand( a , -1 ) __lowerCamelCase : Optional[int] = torch.cat([classifier_free_guidance_embeddings, image_embeddings] , dim=0 ) # The image embeddings batch size and the text embeddings batch size are equal assert image_embeddings.shape[0] == prompt_embeds.shape[0] __lowerCamelCase : int = prompt_embeds.shape[0] # "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and # adding CLIP embeddings to the existing timestep embedding, ... __lowerCamelCase : List[str] = self.embedding_proj(a ) __lowerCamelCase : List[str] = self.clip_image_embeddings_project_to_time_embeddings(a ) __lowerCamelCase : List[str] = time_projected_image_embeddings + time_projected_prompt_embeds # ... and by projecting CLIP embeddings into four # extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder" __lowerCamelCase : Tuple = self.clip_extra_context_tokens_proj(a ) __lowerCamelCase : Optional[int] = clip_extra_context_tokens.reshape(a , -1 , self.clip_extra_context_tokens ) __lowerCamelCase : Tuple = clip_extra_context_tokens.permute(0 , 2 , 1 ) __lowerCamelCase : Any = self.encoder_hidden_states_proj(a ) __lowerCamelCase : Tuple = self.text_encoder_hidden_states_norm(a ) __lowerCamelCase : Union[str, Any] = torch.cat([clip_extra_context_tokens, text_encoder_hidden_states] , dim=1 ) return text_encoder_hidden_states, additive_clip_time_embeddings
669
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore lowercase_ = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" lowercase_ = [file for file in filepaths if file != file.lower()] if upper_files: print(F"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') lowercase_ = [file for file in filepaths if ' ' in file] if space_files: print(F"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') lowercase_ = [file for file in filepaths if '-' in file] if hyphen_files: print(F"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') lowercase_ = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') lowercase_ = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
669
1
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """tokenizer"""] __snake_case = """BridgeTowerImageProcessor""" __snake_case = ("""RobertaTokenizer""", """RobertaTokenizerFast""") def __init__( self: Optional[int] , a: int , a: Tuple ): super().__init__(a , a ) def __call__( self: Union[str, Any] , a: Any , a: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , a: bool = True , a: Union[bool, str, PaddingStrategy] = False , a: Union[bool, str, TruncationStrategy] = None , a: Optional[int] = None , a: int = 0 , a: Optional[int] = None , a: Optional[bool] = None , a: Optional[bool] = None , a: bool = False , a: bool = False , a: bool = False , a: bool = False , a: bool = True , a: Optional[Union[str, TensorType]] = None , **a: Tuple , ): __lowerCamelCase : Tuple = self.tokenizer( text=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_token_type_ids=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_length=a , verbose=a , return_tensors=a , **a , ) # add pixel_values + pixel_mask __lowerCamelCase : Dict = self.image_processor( a , return_tensors=a , do_normalize=a , do_center_crop=a , **a ) encoding.update(a ) return encoding def _snake_case ( self: Any , *a: Dict , **a: str ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: str , *a: Tuple , **a: Optional[int] ): return self.tokenizer.decode(*a , **a ) @property def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : str = self.tokenizer.model_input_names __lowerCamelCase : int = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
669
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_ = { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """xlm-roberta""" def __init__( self: Optional[Any] , a: int=3_0522 , a: List[Any]=768 , a: Tuple=12 , a: List[str]=12 , a: Dict=3072 , a: List[str]="gelu" , a: Any=0.1 , a: Optional[Any]=0.1 , a: str=512 , a: Optional[int]=2 , a: int=0.0_2 , a: str=1e-12 , a: str=1 , a: List[Any]=0 , a: Dict=2 , a: Dict="absolute" , a: List[Any]=True , a: str=None , **a: List[Any] , ): super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : str = hidden_act __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : int = max_position_embeddings __lowerCamelCase : Any = type_vocab_size __lowerCamelCase : int = initializer_range __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : List[Any] = position_embedding_type __lowerCamelCase : List[str] = use_cache __lowerCamelCase : Optional[int] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
669
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { 'configuration_timesformer': ['TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'TimesformerConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TimesformerModel', 'TimesformerForVideoClassification', 'TimesformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
669
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ConsistencyModelPipeline __snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __snake_case = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def _snake_case ( self: str ): __lowerCamelCase : Tuple = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _snake_case ( self: Tuple ): __lowerCamelCase : List[str] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _snake_case ( self: int , a: str=False ): if class_cond: __lowerCamelCase : str = self.dummy_cond_unet else: __lowerCamelCase : str = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCamelCase : Tuple = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def _snake_case ( self: int , a: List[str] , a: Any=0 ): if str(a ).startswith('mps' ): __lowerCamelCase : List[Any] = torch.manual_seed(a ) else: __lowerCamelCase : Tuple = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : Optional[Any] = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : str = ConsistencyModelPipeline(**a ) __lowerCamelCase : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Any = self.get_dummy_inputs(a ) __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[int] = ConsistencyModelPipeline(**a ) __lowerCamelCase : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(a ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : List[str] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Optional[int] = self.get_dummy_components() __lowerCamelCase : Tuple = ConsistencyModelPipeline(**a ) __lowerCamelCase : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = self.get_dummy_inputs(a ) __lowerCamelCase : str = 1 __lowerCamelCase : Optional[int] = None __lowerCamelCase : Any = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[int] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: List[str] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : List[Any] = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[Any] = ConsistencyModelPipeline(**a ) __lowerCamelCase : List[Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_dummy_inputs(a ) __lowerCamelCase : List[str] = 1 __lowerCamelCase : List[str] = None __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Optional[int] , a: str=0 , a: Tuple=False , a: Tuple="cpu" , a: List[str]=torch.floataa , a: Optional[Any]=(1, 3, 64, 64) ): __lowerCamelCase : Optional[Any] = torch.manual_seed(a ) __lowerCamelCase : Optional[int] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __lowerCamelCase : Dict = self.get_fixed_latents(seed=a , device=a , dtype=a , shape=a ) __lowerCamelCase : Optional[Any] = latents return inputs def _snake_case ( self: Any , a: Any=0 , a: List[str]="cpu" , a: Optional[Any]=torch.floataa , a: int=(1, 3, 64, 64) ): if type(a ) == str: __lowerCamelCase : Dict = torch.device(a ) __lowerCamelCase : Union[str, Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : str = randn_tensor(a , generator=a , device=a , dtype=a ) return latents def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs() __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Dict = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_inputs() __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Tuple = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : List[Any] = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs(get_fixed_latents=a , device=a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : int = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[Any] = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def _snake_case ( self: Dict ): __lowerCamelCase : Dict = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = self.get_inputs(get_fixed_latents=a , device=a ) __lowerCamelCase : str = 1 __lowerCamelCase : Union[str, Any] = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : str = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
669
1
import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer lowercase_ = ['gpt2'] lowercase_ = 'gpt2' if is_tf_available(): class A_ ( tf.Module ): '''simple docstring''' def __init__( self: str , a: Union[str, Any] ): super().__init__() __lowerCamelCase : Optional[Any] = tokenizer __lowerCamelCase : List[Any] = AutoConfig.from_pretrained(a ) __lowerCamelCase : Any = TFGPTaLMHeadModel.from_config(a ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name='text' ),) ) def _snake_case ( self: Dict , a: List[Any] ): __lowerCamelCase : Any = self.tokenizer(a ) __lowerCamelCase : Tuple = tokenized['input_ids'].to_tensor() __lowerCamelCase : Any = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) __lowerCamelCase : List[Any] = self.model(input_ids=a , attention_mask=a )['logits'] return outputs @require_tf @require_keras_nlp class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Tuple ): super().setUp() __lowerCamelCase : str = [GPTaTokenizer.from_pretrained(a ) for checkpoint in (TOKENIZER_CHECKPOINTS)] __lowerCamelCase : Tuple = [TFGPTaTokenizer.from_pretrained(a ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __lowerCamelCase : int = [ 'This is a straightforward English test sentence.', 'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.', 'Now we\'re going to add some Chinese: 一 二 三 一二三', 'And some much more rare Chinese: 齉 堃 齉堃', 'Je vais aussi écrire en français pour tester les accents', 'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ', ] __lowerCamelCase : Dict = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def _snake_case ( self: int ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: __lowerCamelCase : List[Any] = tokenizer([test_inputs] , return_tensors='tf' ) __lowerCamelCase : Dict = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors __lowerCamelCase : Any = python_outputs[key].numpy() __lowerCamelCase : int = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(a , tf.intaa ) == tf_outputs_values ) ) @slow def _snake_case ( self: Dict ): for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase : List[str] = tf.function(a ) for test_inputs in self.test_sentences: __lowerCamelCase : Tuple = tf.constant(a ) __lowerCamelCase : List[Any] = compiled_tokenizer(a ) __lowerCamelCase : Tuple = tf_tokenizer(a ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def _snake_case ( self: Dict ): for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase : Optional[Any] = ModelToSave(tokenizer=a ) __lowerCamelCase : Any = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase : Union[str, Any] = model.serving(a ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __lowerCamelCase : Dict = Path(a ) / 'saved.model' tf.saved_model.save(a , a , signatures={'serving_default': model.serving} ) __lowerCamelCase : Optional[int] = tf.saved_model.load(a ) __lowerCamelCase : Optional[int] = loaded_model.signatures['serving_default'](a )['output_0'] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def _snake_case ( self: Dict ): for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase : List[Any] = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase : List[Any] = tf_tokenizer(a ) # Build model with some sample inputs __lowerCamelCase : List[str] = tf_tokenizer.get_config() __lowerCamelCase : int = TFGPTaTokenizer.from_config(a ) __lowerCamelCase : Tuple = model_from_config(a ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def _snake_case ( self: Union[str, Any] ): for tf_tokenizer in self.tf_tokenizers: # for the test to run __lowerCamelCase : Dict = 12_3123 for max_length in [3, 5, 1024]: __lowerCamelCase : int = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase : List[str] = tf_tokenizer(a , max_length=a ) __lowerCamelCase : Any = out['input_ids'].numpy().shape[1] assert out_length == max_length
669
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """trocr""" __snake_case = ["""past_key_values"""] __snake_case = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Dict , a: List[str]=5_0265 , a: Optional[Any]=1024 , a: Tuple=12 , a: Dict=16 , a: Optional[Any]=4096 , a: Optional[Any]="gelu" , a: Optional[int]=512 , a: int=0.1 , a: str=0.0 , a: Union[str, Any]=0.0 , a: Any=2 , a: Optional[int]=0.0_2 , a: Optional[Any]=0.0 , a: List[Any]=True , a: Any=False , a: int=True , a: Optional[Any]=True , a: Tuple=1 , a: Union[str, Any]=0 , a: Any=2 , **a: List[Any] , ): __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : List[str] = decoder_layers __lowerCamelCase : Optional[Any] = decoder_attention_heads __lowerCamelCase : List[str] = decoder_ffn_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : Optional[Any] = max_position_embeddings __lowerCamelCase : Dict = dropout __lowerCamelCase : int = attention_dropout __lowerCamelCase : List[str] = activation_dropout __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Tuple = decoder_layerdrop __lowerCamelCase : str = use_cache __lowerCamelCase : List[Any] = scale_embedding __lowerCamelCase : Any = use_learned_position_embeddings __lowerCamelCase : List[Any] = layernorm_embedding super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , decoder_start_token_id=a , **a , )
669
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ = 50 ): __lowerCamelCase : Optional[Any] = [[0] * 3 for _ in range(length + 1 )] for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): different_colour_ways_number[row_length][tile_length - 2] += ( different_colour_ways_number[row_length - tile_start - tile_length][ tile_length - 2 ] + 1 ) return sum(different_colour_ways_number[length] ) if __name__ == "__main__": print(F"""{solution() = }""")
669
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """tokenizer"""] __snake_case = """CLIPImageProcessor""" __snake_case = ("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self: Union[str, Any] , a: int=None , a: List[str]=None , **a: str ): __lowerCamelCase : int = 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 , ) __lowerCamelCase : str = kwargs.pop('feature_extractor' ) __lowerCamelCase : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: List[Any]=None , a: List[str]=None , a: int=None , **a: List[Any] ): if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __lowerCamelCase : Dict = self.tokenizer(a , return_tensors=a , **a ) if images is not None: __lowerCamelCase : Tuple = self.image_processor(a , return_tensors=a , **a ) if text is not None and images is not None: __lowerCamelCase : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a ) , tensor_type=a ) def _snake_case ( self: List[Any] , *a: Optional[Any] , **a: int ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: Any , *a: Union[str, Any] , **a: Optional[Any] ): return self.tokenizer.decode(*a , **a ) @property def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = self.tokenizer.model_input_names __lowerCamelCase : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
669
1
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_realm import RealmTokenizer lowercase_ = logging.get_logger(__name__) lowercase_ = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} lowercase_ = { 'vocab_file': { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt' ), 'google/realm-orqa-nq-openqa': 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt', 'google/realm-orqa-nq-reader': 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt', 'google/realm-orqa-wq-openqa': 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt', 'google/realm-orqa-wq-reader': 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt', }, 'tokenizer_file': { 'google/realm-cc-news-pretrained-embedder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont' ), 'google/realm-cc-news-pretrained-encoder': ( 'https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json' ), 'google/realm-cc-news-pretrained-scorer': ( 'https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json' ), 'google/realm-cc-news-pretrained-openqa': ( 'https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json' ), 'google/realm-orqa-nq-openqa': ( 'https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json' ), 'google/realm-orqa-nq-reader': ( 'https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json' ), 'google/realm-orqa-wq-openqa': ( 'https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json' ), 'google/realm-orqa-wq-reader': ( 'https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json' ), }, } lowercase_ = { 'google/realm-cc-news-pretrained-embedder': 5_1_2, 'google/realm-cc-news-pretrained-encoder': 5_1_2, 'google/realm-cc-news-pretrained-scorer': 5_1_2, 'google/realm-cc-news-pretrained-openqa': 5_1_2, 'google/realm-orqa-nq-openqa': 5_1_2, 'google/realm-orqa-nq-reader': 5_1_2, 'google/realm-orqa-wq-openqa': 5_1_2, 'google/realm-orqa-wq-reader': 5_1_2, } lowercase_ = { 'google/realm-cc-news-pretrained-embedder': {'do_lower_case': True}, 'google/realm-cc-news-pretrained-encoder': {'do_lower_case': True}, 'google/realm-cc-news-pretrained-scorer': {'do_lower_case': True}, 'google/realm-cc-news-pretrained-openqa': {'do_lower_case': True}, 'google/realm-orqa-nq-openqa': {'do_lower_case': True}, 'google/realm-orqa-nq-reader': {'do_lower_case': True}, 'google/realm-orqa-wq-openqa': {'do_lower_case': True}, 'google/realm-orqa-wq-reader': {'do_lower_case': True}, } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_INIT_CONFIGURATION __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = RealmTokenizer def __init__( self: Tuple , a: Union[str, Any]=None , a: List[Any]=None , a: str=True , a: Optional[int]="[UNK]" , a: List[Any]="[SEP]" , a: List[Any]="[PAD]" , a: Union[str, Any]="[CLS]" , a: List[str]="[MASK]" , a: Optional[int]=True , a: str=None , **a: Any , ): super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) __lowerCamelCase : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('lowercase' , a ) != do_lower_case or normalizer_state.get('strip_accents' , a ) != strip_accents or normalizer_state.get('handle_chinese_chars' , a ) != tokenize_chinese_chars ): __lowerCamelCase : Any = getattr(a , normalizer_state.pop('type' ) ) __lowerCamelCase : Optional[Any] = do_lower_case __lowerCamelCase : Optional[Any] = strip_accents __lowerCamelCase : Union[str, Any] = tokenize_chinese_chars __lowerCamelCase : str = normalizer_class(**a ) __lowerCamelCase : int = do_lower_case def _snake_case ( self: Tuple , a: Any , **a: Any ): __lowerCamelCase : List[str] = PaddingStrategy.MAX_LENGTH __lowerCamelCase : Tuple = text __lowerCamelCase : int = kwargs.pop('text_pair' , a ) __lowerCamelCase : str = kwargs.pop('return_tensors' , a ) __lowerCamelCase : Optional[int] = { 'input_ids': [], 'attention_mask': [], 'token_type_ids': [], } for idx, candidate_text in enumerate(a ): if batch_text_pair is not None: __lowerCamelCase : Optional[Any] = batch_text_pair[idx] else: __lowerCamelCase : Optional[int] = None __lowerCamelCase : Optional[int] = super().__call__(a , a , return_tensors=a , **a ) __lowerCamelCase : List[Any] = encoded_candidates.get('input_ids' ) __lowerCamelCase : Optional[int] = encoded_candidates.get('attention_mask' ) __lowerCamelCase : List[Any] = encoded_candidates.get('token_type_ids' ) if encoded_input_ids is not None: output_data["input_ids"].append(a ) if encoded_attention_mask is not None: output_data["attention_mask"].append(a ) if encoded_token_type_ids is not None: output_data["token_type_ids"].append(a ) __lowerCamelCase : int = {key: item for key, item in output_data.items() if len(a ) != 0} return BatchEncoding(a , tensor_type=a ) def _snake_case ( self: Any , a: Optional[int] , a: Union[str, Any]=None ): __lowerCamelCase : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def _snake_case ( self: Dict , a: List[int] , a: Optional[List[int]] = None ): __lowerCamelCase : List[str] = [self.sep_token_id] __lowerCamelCase : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case ( self: Dict , a: str , a: Optional[str] = None ): __lowerCamelCase : Optional[Any] = self._tokenizer.model.save(a , name=a ) return tuple(a )
669
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self: int ): torch.manual_seed(0 ) __lowerCamelCase : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Any = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _snake_case ( self: Dict ): torch.manual_seed(0 ) __lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.dummy_uncond_unet __lowerCamelCase : List[str] = DDIMScheduler() __lowerCamelCase : str = self.dummy_vq_model __lowerCamelCase : Optional[int] = LDMPipeline(unet=a , vqvae=a , scheduler=a ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[int] = torch.manual_seed(0 ) __lowerCamelCase : Any = ldm(generator=a , num_inference_steps=2 , output_type='numpy' ).images __lowerCamelCase : Tuple = torch.manual_seed(0 ) __lowerCamelCase : Dict = ldm(generator=a , num_inference_steps=2 , output_type='numpy' , return_dict=a )[0] __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[int] = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) __lowerCamelCase : str = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : int = ldm(generator=a , num_inference_steps=5 , output_type='numpy' ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __lowerCamelCase : List[Any] = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) __lowerCamelCase : Union[str, Any] = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
669
1
import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem lowercase_ = importlib.util.find_spec('s3fs') is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 lowercase_ = [ 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 UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if "://" in dataset_path: __lowerCamelCase : List[str] = dataset_path.split('://' )[1] return dataset_path def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if fs is not None and fs.protocol != "file": return True else: return False def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = not is_remote_filesystem(SCREAMING_SNAKE_CASE__ ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(SCREAMING_SNAKE_CASE__ ) , fs._strip_protocol(SCREAMING_SNAKE_CASE__ ) ) else: fs.mv(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , recursive=SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( ): if hasattr(fsspec.asyn , 'reset_lock' ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: __lowerCamelCase : Any = None __lowerCamelCase : List[Any] = None __lowerCamelCase : Tuple = threading.Lock()
669
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = 'Usage of script: script_name <size_of_canvas:int>' lowercase_ = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = [[False for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] return canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): for j, _ in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = bool(random.getrandbits(1 ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = np.array(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(SCREAMING_SNAKE_CASE__ ): for c, pt in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = __judge_point( SCREAMING_SNAKE_CASE__ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __lowerCamelCase : Any = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __lowerCamelCase : list[list[bool]] = current_canvas.tolist() return return_canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __lowerCamelCase : Tuple = pt if pt: if alive < 2: __lowerCamelCase : Optional[Any] = False elif alive == 2 or alive == 3: __lowerCamelCase : Any = True elif alive > 3: __lowerCamelCase : Dict = False else: if alive == 3: __lowerCamelCase : Tuple = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ ,lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(['w', 'k']) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
669
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
669
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 A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """char""" __snake_case = """bpe""" __snake_case = """wp""" lowercase_ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """char_tokenizer"""] __snake_case = """ViTImageProcessor""" __snake_case = """MgpstrTokenizer""" def __init__( self: int , a: Dict=None , a: Optional[int]=None , **a: List[str] ): __lowerCamelCase : Optional[int] = 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 , ) __lowerCamelCase : Optional[Any] = kwargs.pop('feature_extractor' ) __lowerCamelCase : 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`.' ) __lowerCamelCase : Any = tokenizer __lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('gpt2' ) __lowerCamelCase : int = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: Optional[int]=None , a: List[Any]=None , a: int=None , **a: str ): 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: __lowerCamelCase : Dict = self.image_processor(a , return_tensors=a , **a ) if text is not None: __lowerCamelCase : Dict = self.char_tokenizer(a , return_tensors=a , **a ) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : List[str] = encodings['input_ids'] return inputs def _snake_case ( self: List[str] , a: List[Any] ): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = sequences __lowerCamelCase : List[str] = char_preds.size(0 ) __lowerCamelCase , __lowerCamelCase : str = self._decode_helper(a , 'char' ) __lowerCamelCase , __lowerCamelCase : Optional[int] = self._decode_helper(a , 'bpe' ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = self._decode_helper(a , 'wp' ) __lowerCamelCase : Tuple = [] __lowerCamelCase : List[Any] = [] for i in range(a ): __lowerCamelCase : List[Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowerCamelCase : Optional[int] = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowerCamelCase : Any = scores.index(max(a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowerCamelCase : List[str] = {} __lowerCamelCase : Optional[int] = final_strs __lowerCamelCase : Dict = final_scores __lowerCamelCase : Dict = char_strs __lowerCamelCase : List[Any] = bpe_strs __lowerCamelCase : Tuple = wp_strs return out def _snake_case ( self: int , a: Optional[int] , a: Optional[Any] ): if format == DecodeType.CHARACTER: __lowerCamelCase : Optional[Any] = self.char_decode __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : List[str] = '[s]' elif format == DecodeType.BPE: __lowerCamelCase : Dict = self.bpe_decode __lowerCamelCase : List[str] = 2 __lowerCamelCase : Any = '#' elif format == DecodeType.WORDPIECE: __lowerCamelCase : List[str] = self.wp_decode __lowerCamelCase : int = 102 __lowerCamelCase : Dict = '[SEP]' else: raise ValueError(F'Format {format} is not supported.' ) __lowerCamelCase , __lowerCamelCase : int = [], [] __lowerCamelCase : Tuple = pred_logits.size(0 ) __lowerCamelCase : List[Any] = pred_logits.size(1 ) __lowerCamelCase , __lowerCamelCase : Dict = pred_logits.topk(1 , dim=-1 , largest=a , sorted=a ) __lowerCamelCase : List[str] = preds_index.view(-1 , a )[:, 1:] __lowerCamelCase : Dict = decoder(a ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = torch.nn.functional.softmax(a , dim=2 ).max(dim=2 ) __lowerCamelCase : List[str] = preds_max_prob[:, 1:] for index in range(a ): __lowerCamelCase : str = preds_str[index].find(a ) __lowerCamelCase : Tuple = preds_str[index][:pred_eos] __lowerCamelCase : Any = preds_index[index].cpu().tolist() __lowerCamelCase : Any = pred_index.index(a ) if eos_token in pred_index else -1 __lowerCamelCase : str = preds_max_prob[index][: pred_eos_index + 1] __lowerCamelCase : Union[str, Any] = 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 _snake_case ( self: Tuple , a: Optional[int] ): __lowerCamelCase : Dict = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(a )] return decode_strs def _snake_case ( self: Optional[int] , a: Tuple ): return self.bpe_tokenizer.batch_decode(a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : int = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(a )] return decode_strs
669
1
import argparse import math import os from copy import deepcopy import torch from audio_diffusion.models import DiffusionAttnUnetaD from diffusion import sampling from torch import nn from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel lowercase_ = { 'gwf-440k': { 'url': 'https://model-server.zqevans2.workers.dev/gwf-440k.ckpt', 'sample_rate': 4_8_0_0_0, 'sample_size': 6_5_5_3_6, }, 'jmann-small-190k': { 'url': 'https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt', 'sample_rate': 4_8_0_0_0, 'sample_size': 6_5_5_3_6, }, 'jmann-large-580k': { 'url': 'https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt', 'sample_rate': 4_8_0_0_0, 'sample_size': 1_3_1_0_7_2, }, 'maestro-uncond-150k': { 'url': 'https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt', 'sample_rate': 1_6_0_0_0, 'sample_size': 6_5_5_3_6, }, 'unlocked-uncond-250k': { 'url': 'https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt', 'sample_rate': 1_6_0_0_0, 'sample_size': 6_5_5_3_6, }, 'honk-140k': { 'url': 'https://model-server.zqevans2.workers.dev/honk-140k.ckpt', 'sample_rate': 1_6_0_0_0, 'sample_size': 6_5_5_3_6, }, } def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return torch.atana(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) / math.pi * 2 def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = torch.sin(t * math.pi / 2 ) ** 2 __lowerCamelCase : Dict = (1 - sigma**2) ** 0.5 return alpha_sigma_to_t(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) class A_ ( __UpperCamelCase ): '''simple docstring''' pass class A_ ( nn.Module ): '''simple docstring''' def __init__( self: Union[str, Any] , a: str ): super().__init__() __lowerCamelCase : Tuple = DiffusionAttnUnetaD(a , n_attn_layers=4 ) __lowerCamelCase : Tuple = deepcopy(self.diffusion ) __lowerCamelCase : Dict = torch.quasirandom.SobolEngine(1 , scramble=a ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = MODELS_MAP[model_name]['url'] os.system(f'wget {url} ./' ) return f'./{model_name}.ckpt' lowercase_ = { '1': 'resnets.0', '2': 'attentions.0', '3': 'resnets.1', '4': 'attentions.1', '5': 'resnets.2', '6': 'attentions.2', } lowercase_ = { '8': 'resnets.0', '9': 'attentions.0', '10': 'resnets.1', '11': 'attentions.1', '12': 'resnets.2', '13': 'attentions.2', } lowercase_ = { '1': 'resnets.0', '2': 'attentions.0', '3': 'resnets.1', '4': 'attentions.1', '5': 'resnets.2', '6': 'attentions.2', '8': 'resnets.3', '9': 'attentions.3', '10': 'resnets.4', '11': 'attentions.4', '12': 'resnets.5', '13': 'attentions.5', } lowercase_ = { '0': 'resnets.0', '1': 'resnets.1', '2': 'resnets.2', '4': 'resnets.0', '5': 'resnets.1', '6': 'resnets.2', } lowercase_ = { 'skip': 'conv_skip', 'main.0': 'conv_1', 'main.1': 'group_norm_1', 'main.3': 'conv_2', 'main.4': 'group_norm_2', } lowercase_ = { 'norm': 'group_norm', 'qkv_proj': ['query', 'key', 'value'], 'out_proj': ['proj_attn'], } def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if name.startswith('skip' ): return name.replace('skip' , RES_CONV_MAP['skip'] ) # name has to be of format main.{digit} if not name.startswith('main.' ): raise ValueError(f'ResConvBlock error with {name}' ) return name.replace(name[:6] , RES_CONV_MAP[name[:6]] ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for key, value in ATTN_MAP.items(): if name.startswith(SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return name.replace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif name.startswith(SCREAMING_SNAKE_CASE__ ): return [name.replace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for v in value] raise ValueError(f'Attn error with {name}' ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=13 ): __lowerCamelCase : Optional[int] = input_string if string.split('.' )[0] == "timestep_embed": return string.replace('timestep_embed' , 'time_proj' ) __lowerCamelCase : Optional[int] = 0 if string.startswith('net.3.' ): depth += 1 __lowerCamelCase : Tuple = string[6:] elif string.startswith('net.' ): __lowerCamelCase : Optional[int] = string[4:] while string.startswith('main.7.' ): depth += 1 __lowerCamelCase : List[str] = string[7:] if string.startswith('main.' ): __lowerCamelCase : List[Any] = string[5:] # mid block if string[:2].isdigit(): __lowerCamelCase : Optional[int] = string[:2] __lowerCamelCase : Union[str, Any] = string[2:] else: __lowerCamelCase : List[Any] = string[0] __lowerCamelCase : Any = string[1:] if depth == max_depth: __lowerCamelCase : Optional[int] = MID_NUM_TO_LAYER[layer_num] __lowerCamelCase : Tuple = 'mid_block' elif depth > 0 and int(SCREAMING_SNAKE_CASE__ ) < 7: __lowerCamelCase : int = DOWN_NUM_TO_LAYER[layer_num] __lowerCamelCase : Union[str, Any] = f'down_blocks.{depth}' elif depth > 0 and int(SCREAMING_SNAKE_CASE__ ) > 7: __lowerCamelCase : List[str] = UP_NUM_TO_LAYER[layer_num] __lowerCamelCase : Union[str, Any] = f'up_blocks.{max_depth - depth - 1}' elif depth == 0: __lowerCamelCase : str = DEPTH_0_TO_LAYER[layer_num] __lowerCamelCase : Tuple = f'up_blocks.{max_depth - 1}' if int(SCREAMING_SNAKE_CASE__ ) > 3 else 'down_blocks.0' if not string_left.startswith('.' ): raise ValueError(f'Naming error with {input_string} and string_left: {string_left}.' ) __lowerCamelCase : Tuple = string_left[1:] if "resnets" in new_layer: __lowerCamelCase : int = convert_resconv_naming(SCREAMING_SNAKE_CASE__ ) elif "attentions" in new_layer: __lowerCamelCase : Optional[int] = convert_attn_naming(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = new_string_left if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = prefix + '.' + new_layer + '.' + string_left else: __lowerCamelCase : List[str] = [prefix + '.' + new_layer + '.' + s for s in string_left] return new_string def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = {} for k, v in state_dict.items(): if k.endswith('kernel' ): # up- and downsample layers, don't have trainable weights continue __lowerCamelCase : Any = rename(SCREAMING_SNAKE_CASE__ ) # check if we need to transform from Conv => Linear for attention if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = transform_conv_attns(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase : Optional[Any] = v return new_state_dict def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if len(SCREAMING_SNAKE_CASE__ ) == 1: if len(v.shape ) == 3: # weight __lowerCamelCase : Dict = v[:, :, 0] else: # bias __lowerCamelCase : List[str] = v else: # qkv matrices __lowerCamelCase : Union[str, Any] = v.shape[0] __lowerCamelCase : Optional[int] = trippled_shape // 3 for i in range(3 ): if len(v.shape ) == 3: __lowerCamelCase : Optional[int] = v[i * single_shape : (i + 1) * single_shape, :, 0] else: __lowerCamelCase : List[str] = v[i * single_shape : (i + 1) * single_shape] return new_state_dict def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = torch.device('cuda' if torch.cuda.is_available() else 'cpu' ) __lowerCamelCase : Union[str, Any] = args.model_path.split('/' )[-1].split('.' )[0] if not os.path.isfile(args.model_path ): assert ( model_name == args.model_path ), f'Make sure to provide one of the official model names {MODELS_MAP.keys()}' __lowerCamelCase : Union[str, Any] = download(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = MODELS_MAP[model_name]['sample_rate'] __lowerCamelCase : Any = MODELS_MAP[model_name]['sample_size'] __lowerCamelCase : Optional[int] = Object() __lowerCamelCase : Tuple = sample_size __lowerCamelCase : Dict = sample_rate __lowerCamelCase : Union[str, Any] = 0 __lowerCamelCase : Optional[int] = UNetaDModel(sample_size=SCREAMING_SNAKE_CASE__ , sample_rate=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = diffusers_model.state_dict() __lowerCamelCase : Union[str, Any] = DiffusionUncond(SCREAMING_SNAKE_CASE__ ) orig_model.load_state_dict(torch.load(args.model_path , map_location=SCREAMING_SNAKE_CASE__ )['state_dict'] ) __lowerCamelCase : List[str] = orig_model.diffusion_ema.eval() __lowerCamelCase : int = orig_model.state_dict() __lowerCamelCase : Optional[int] = rename_orig_weights(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() ) __lowerCamelCase : Tuple = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() ) assert len(SCREAMING_SNAKE_CASE__ ) == 0, f'Problem with {renamed_minus_diffusers}' assert all(k.endswith('kernel' ) for k in list(SCREAMING_SNAKE_CASE__ ) ), f'Problem with {diffusers_minus_renamed}' for key, value in renamed_state_dict.items(): assert ( diffusers_state_dict[key].squeeze().shape == value.squeeze().shape ), f'Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}' if key == "time_proj.weight": __lowerCamelCase : Tuple = value.squeeze() __lowerCamelCase : int = value diffusers_model.load_state_dict(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = 100 __lowerCamelCase : int = 33 __lowerCamelCase : int = IPNDMScheduler(num_train_timesteps=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = torch.randn([1, 2, config.sample_size] , generator=SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = torch.linspace(1 , 0 , steps + 1 , device=SCREAMING_SNAKE_CASE__ )[:-1] __lowerCamelCase : List[Any] = get_crash_schedule(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = DanceDiffusionPipeline(unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = torch.manual_seed(33 ) __lowerCamelCase : Optional[Any] = pipe(num_inference_steps=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ ).audios __lowerCamelCase : Union[str, Any] = sampling.iplms_sample(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , {} ) __lowerCamelCase : Any = generated.clamp(-1 , 1 ) __lowerCamelCase : Dict = (generated - audio).abs().sum() __lowerCamelCase : List[Any] = (generated - audio).abs().max() if args.save: pipe.save_pretrained(args.checkpoint_path ) print('Diff sum' , SCREAMING_SNAKE_CASE__ ) print('Diff max' , SCREAMING_SNAKE_CASE__ ) assert diff_max < 1e-3, f'Diff max: {diff_max} is too much :-/' print(f'Conversion for {model_name} successful!' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument( '--save', default=True, type=bool, required=False, help='Whether to save the converted model or not.' ) parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') lowercase_ = parser.parse_args() main(args)
669
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : Optional[int] = TOKENIZER_CLASSES else: __lowerCamelCase : Union[str, Any] = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE__ , tokenizer_name + 'Fast' )} logger.info(f'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : int = TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Optional[int] = True if checkpoint_name is None: __lowerCamelCase : List[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : Optional[Any] = [checkpoint_name] logger.info(f'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(f'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ ) # Save fast tokenizer logger.info(f'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Tuple = checkpoint.split('/' ) __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif add_prefix: __lowerCamelCase : Any = checkpoint __lowerCamelCase : Dict = dump_path else: __lowerCamelCase : List[str] = None __lowerCamelCase : Optional[int] = dump_path logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : List[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : int = file_path.split(SCREAMING_SNAKE_CASE__ )[-1][0] if next_char == "/": __lowerCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = None logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Dict = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ , filename_prefix=SCREAMING_SNAKE_CASE__ ) logger.info(f'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('tokenizer.json' ): os.remove(SCREAMING_SNAKE_CASE__ ) logger.info(f'=> removing {file_name}' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) lowercase_ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
669
1
from torch import nn class A_ ( nn.Module ): '''simple docstring''' def __init__( self: Dict , a: Optional[Any] , a: Optional[Any] ): super().__init__() __lowerCamelCase : int = class_size __lowerCamelCase : List[str] = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) __lowerCamelCase : Optional[int] = nn.Linear(a , a ) def _snake_case ( self: Dict , a: List[str] ): # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) __lowerCamelCase : int = self.mlp(a ) return logits
669
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: List[str] ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : List[str] = PegasusTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[Any] ): return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def _snake_case ( self: Tuple , **a: List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[Any] , a: int ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Dict = '</s>' __lowerCamelCase : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a ) , 1103 ) def _snake_case ( self: Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) __lowerCamelCase : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: int ): __lowerCamelCase : Union[str, Any] = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowerCamelCase : Tuple = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' __lowerCamelCase : Optional[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : Optional[Any] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 __lowerCamelCase : int = 'To ensure a smooth flow of bank resolutions.' __lowerCamelCase : Union[str, Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : List[str] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _snake_case ( self: str ): __lowerCamelCase : List[str] = ['This is going to be way too long.' * 150, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : Union[str, Any] = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : List[str] = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. @slow def _snake_case ( self: List[str] ): # fmt: off __lowerCamelCase : Tuple = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: str ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : str = PegasusTokenizer(a , offset=0 , mask_token_sent=a , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[str] ): return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def _snake_case ( self: Union[str, Any] , **a: Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[str] , a: Any ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) __lowerCamelCase : int = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) @require_torch def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = ['This is going to be way too long.' * 1000, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : str = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : Any = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. def _snake_case ( self: Any ): __lowerCamelCase : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) __lowerCamelCase : Dict = self._large_tokenizer(a ).input_ids self.assertListEqual( a , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
669
1
import inspect import re from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowercase_ = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. lowercase_ = direct_transformers_import(PATH_TO_TRANSFORMERS) lowercase_ = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` lowercase_ = re.compile(R'\[(.+?)\]\((https://huggingface\.co/.+?)\)') lowercase_ = { 'DecisionTransformerConfig', 'EncoderDecoderConfig', 'MusicgenConfig', 'RagConfig', 'SpeechEncoderDecoderConfig', 'TimmBackboneConfig', 'VisionEncoderDecoderConfig', 'VisionTextDualEncoderConfig', 'LlamaConfig', } def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[str] = None # source code of `config_class` __lowerCamelCase : Dict = inspect.getsource(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = _re_checkpoint.findall(SCREAMING_SNAKE_CASE__ ) # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` for ckpt_name, ckpt_link in checkpoints: # allow the link to end with `/` if ckpt_link.endswith('/' ): __lowerCamelCase : List[str] = ckpt_link[:-1] # verify the checkpoint name corresponds to the checkpoint link __lowerCamelCase : Optional[Any] = f'https://huggingface.co/{ckpt_name}' if ckpt_link == ckpt_link_from_name: __lowerCamelCase : List[str] = ckpt_name break return checkpoint def UpperCamelCase__ ( ): __lowerCamelCase : int = [] for config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in config_class.__module__: continue __lowerCamelCase : Optional[int] = get_checkpoint_from_config_class(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = config_class.__name__ if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: __lowerCamelCase : Optional[Any] = '\n'.join(sorted(SCREAMING_SNAKE_CASE__ ) ) raise ValueError(f'The following configurations don\'t contain any valid checkpoint:\n{message}' ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if density <= 0: raise ValueError('Impossible fluid density' ) if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
669
1
from __future__ import annotations lowercase_ = [-1_0, -5, 0, 5, 5.1, 1_1, 1_3, 2_1, 3, 4, -2_1, -1_0, -5, -1, 0] lowercase_ = [-5, 0, 5, 5.1, 1_1, 1_3, 2_1, -1, 4, -1, -1_0, -5, -1, 0, -1] def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = [] __lowerCamelCase : Dict = len(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : float = -1 for j in range(i + 1 , SCREAMING_SNAKE_CASE__ ): if arr[i] < arr[j]: __lowerCamelCase : Dict = arr[j] break result.append(SCREAMING_SNAKE_CASE__ ) return result def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = [] for i, outer in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : float = -1 for inner in arr[i + 1 :]: if outer < inner: __lowerCamelCase : List[Any] = inner break result.append(SCREAMING_SNAKE_CASE__ ) return result def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[Any] = len(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : list[float] = [] __lowerCamelCase : list[float] = [-1] * arr_size for index in reversed(range(SCREAMING_SNAKE_CASE__ ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: __lowerCamelCase : Tuple = stack[-1] stack.append(arr[index] ) return result if __name__ == "__main__": from doctest import testmod from timeit import timeit testmod() print(next_greatest_element_slow(arr)) print(next_greatest_element_fast(arr)) print(next_greatest_element(arr)) lowercase_ = ( 'from __main__ import arr, next_greatest_element_slow, ' 'next_greatest_element_fast, next_greatest_element' ) print( 'next_greatest_element_slow():', timeit('next_greatest_element_slow(arr)', setup=setup), ) print( 'next_greatest_element_fast():', timeit('next_greatest_element_fast(arr)', setup=setup), ) print( ' next_greatest_element():', timeit('next_greatest_element(arr)', setup=setup), )
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = 1 __lowerCamelCase : str = 2 while i * i <= n: __lowerCamelCase : int = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def UpperCamelCase__ ( ): __lowerCamelCase : str = 1 __lowerCamelCase : List[str] = 1 while True: i += 1 t_num += i if count_divisors(SCREAMING_SNAKE_CASE__ ) > 500: break return t_num if __name__ == "__main__": print(solution())
669
1
import unittest from knapsack import greedy_knapsack as kp class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: List[Any] ): __lowerCamelCase : str = [10, 20, 30, 40, 50, 60] __lowerCamelCase : List[str] = [2, 4, 6, 8, 10, 12] __lowerCamelCase : Tuple = 100 self.assertEqual(kp.calc_profit(a , a , a ) , 210 ) def _snake_case ( self: str ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'Weight can not be negative.' ) def _snake_case ( self: Dict ): self.assertRaisesRegex(a , 'Profit can not be negative.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: Any ): self.assertRaisesRegex( a , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
669
import numpy as np class A_ : '''simple docstring''' def __init__( self: Optional[int] ): __lowerCamelCase : int = (0, 0) __lowerCamelCase : List[str] = None __lowerCamelCase : int = 0 __lowerCamelCase : int = 0 __lowerCamelCase : Union[str, Any] = 0 def __eq__( self: Optional[int] , a: List[Any] ): return self.position == cell.position def _snake_case ( self: Any ): print(self.position ) class A_ : '''simple docstring''' def __init__( self: str , a: List[str]=(5, 5) ): __lowerCamelCase : Optional[Any] = np.zeros(a ) __lowerCamelCase : List[str] = world_size[0] __lowerCamelCase : Optional[int] = world_size[1] def _snake_case ( self: List[Any] ): print(self.w ) def _snake_case ( self: Optional[int] , a: str ): __lowerCamelCase : Tuple = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __lowerCamelCase : Optional[int] = cell.position[0] __lowerCamelCase : List[str] = cell.position[1] __lowerCamelCase : Dict = [] for n in neughbour_cord: __lowerCamelCase : Dict = current_x + n[0] __lowerCamelCase : Optional[Any] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __lowerCamelCase : Optional[Any] = Cell() __lowerCamelCase : Any = (x, y) __lowerCamelCase : Dict = cell neighbours.append(a ) return neighbours def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = [] __lowerCamelCase : int = [] _open.append(SCREAMING_SNAKE_CASE__ ) while _open: __lowerCamelCase : Union[str, Any] = np.argmin([n.f for n in _open] ) __lowerCamelCase : int = _open[min_f] _closed.append(_open.pop(SCREAMING_SNAKE_CASE__ ) ) if current == goal: break for n in world.get_neigbours(SCREAMING_SNAKE_CASE__ ): for c in _closed: if c == n: continue __lowerCamelCase : Optional[int] = current.g + 1 __lowerCamelCase , __lowerCamelCase : int = n.position __lowerCamelCase , __lowerCamelCase : Tuple = goal.position __lowerCamelCase : Dict = (ya - ya) ** 2 + (xa - xa) ** 2 __lowerCamelCase : str = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [] while current.parent is not None: path.append(current.position ) __lowerCamelCase : int = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowercase_ = Gridworld() # Start position and goal lowercase_ = Cell() lowercase_ = (0, 0) lowercase_ = Cell() lowercase_ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowercase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowercase_ = 1 print(world.w)
669
1
import numpy as np from PIL import Image def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = np.array(SCREAMING_SNAKE_CASE__ ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __lowerCamelCase : Optional[Any] = 0 __lowerCamelCase : Optional[int] = 0 __lowerCamelCase : List[Any] = 0 __lowerCamelCase : List[str] = 0 # compute the shape of the output matrix __lowerCamelCase : Any = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape __lowerCamelCase : Any = np.zeros((maxpool_shape, maxpool_shape) ) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix __lowerCamelCase : Dict = np.max(arr[i : i + size, j : j + size] ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __lowerCamelCase : Dict = 0 __lowerCamelCase : List[str] = 0 return updated_arr def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = np.array(SCREAMING_SNAKE_CASE__ ) if arr.shape[0] != arr.shape[1]: raise ValueError('The input array is not a square matrix' ) __lowerCamelCase : str = 0 __lowerCamelCase : Dict = 0 __lowerCamelCase : Tuple = 0 __lowerCamelCase : List[str] = 0 # compute the shape of the output matrix __lowerCamelCase : Optional[Any] = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape __lowerCamelCase : Dict = np.zeros((avgpool_shape, avgpool_shape) ) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix __lowerCamelCase : Union[str, Any] = int(np.average(arr[i : i + size, j : j + size] ) ) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 __lowerCamelCase : Dict = 0 __lowerCamelCase : int = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='avgpooling', verbose=True) # Loading the image lowercase_ = Image.open('path_to_image') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
669
import math from datetime import datetime, timedelta def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = year % 19 __lowerCamelCase : int = year % 4 __lowerCamelCase : Any = year % 7 __lowerCamelCase : Dict = math.floor(year / 100 ) __lowerCamelCase : str = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCamelCase : Optional[int] = leap_day_inhibits / 4 __lowerCamelCase : str = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCamelCase : Optional[Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCamelCase : Optional[int] = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __lowerCamelCase : Tuple = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 18 ) else: return datetime(SCREAMING_SNAKE_CASE__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): lowercase_ = 'will be' if year > datetime.now().year else 'was' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
669
1
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any]=2 , a: str=3 , a: Any=4 , a: Union[str, Any]=2 , a: Tuple=7 , a: int=True , a: Tuple=True , a: List[str]=True , a: Union[str, Any]=True , a: str=99 , a: Tuple=36 , a: int=2 , a: Dict=4 , a: Union[str, Any]=37 , a: List[str]="gelu" , a: List[Any]=0.1 , a: Optional[int]=0.1 , a: Dict=512 , a: Union[str, Any]=16 , a: str=2 , a: int=0.0_2 , a: Optional[Any]=6 , a: Optional[int]=6 , a: Dict=3 , a: Optional[Any]=4 , a: Optional[Any]=None , a: Dict=1000 , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Optional[int] = num_channels __lowerCamelCase : str = image_size __lowerCamelCase : int = patch_size __lowerCamelCase : List[str] = is_training __lowerCamelCase : Dict = use_input_mask __lowerCamelCase : Any = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : str = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : List[Any] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : int = type_sequence_label_size __lowerCamelCase : List[str] = initializer_range __lowerCamelCase : List[str] = coordinate_size __lowerCamelCase : int = shape_size __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : int = num_choices __lowerCamelCase : int = scope __lowerCamelCase : Any = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __lowerCamelCase : Any = text_seq_length __lowerCamelCase : Optional[Any] = (image_size // patch_size) ** 2 + 1 __lowerCamelCase : Any = self.text_seq_length + self.image_seq_length def _snake_case ( self: List[str] ): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __lowerCamelCase : int = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __lowerCamelCase : List[str] = bbox[i, j, 3] __lowerCamelCase : str = bbox[i, j, 1] __lowerCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __lowerCamelCase : Tuple = bbox[i, j, 2] __lowerCamelCase : Any = bbox[i, j, 0] __lowerCamelCase : List[str] = tmp_coordinate __lowerCamelCase : str = tf.constant(a ) __lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.text_seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __lowerCamelCase : Dict = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self: Tuple , a: List[Any] , a: Any , a: List[str] , a: Dict , a: Optional[Any] , a: Dict ): __lowerCamelCase : Optional[Any] = TFLayoutLMvaModel(config=a ) # text + image __lowerCamelCase : Optional[Any] = model(a , pixel_values=a , training=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , training=a , ) __lowerCamelCase : List[Any] = model(a , bbox=a , pixel_values=a , training=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __lowerCamelCase : List[Any] = model(a , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __lowerCamelCase : Optional[Any] = model({'pixel_values': pixel_values} , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self: Dict , a: Dict , a: Optional[Any] , a: int , a: Optional[int] , a: List[str] , a: List[str] , a: List[str] ): __lowerCamelCase : List[str] = self.num_labels __lowerCamelCase : str = TFLayoutLMvaForSequenceClassification(config=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any] , a: Dict , a: Optional[Any] , a: Tuple , a: Optional[Any] , a: List[Any] ): __lowerCamelCase : Union[str, Any] = self.num_labels __lowerCamelCase : Any = TFLayoutLMvaForTokenClassification(config=a ) __lowerCamelCase : Optional[Any] = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self: Dict , a: Optional[Any] , a: str , a: Dict , a: Union[str, Any] , a: List[Any] , a: Optional[int] , a: List[str] ): __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Any = TFLayoutLMvaForQuestionAnswering(config=a ) __lowerCamelCase : Any = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , training=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] ): __lowerCamelCase : str = self.prepare_config_and_inputs() ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : List[Any] = config_and_inputs __lowerCamelCase : Tuple = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: int , a: List[str] , a: Any , a: Optional[Any] , a: Tuple , a: Tuple ): return True def _snake_case ( self: str , a: Any , a: Any , a: Optional[int]=False ): __lowerCamelCase : List[str] = copy.deepcopy(a ) if model_class in get_values(a ): __lowerCamelCase : Tuple = { k: tf.tile(tf.expand_dims(a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a ): __lowerCamelCase : Any = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Dict = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def _snake_case ( self: Tuple ): __lowerCamelCase : int = TFLayoutLMvaModelTester(self ) __lowerCamelCase : str = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self: Union[str, Any] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : int = model_class(a ) if getattr(a , 'hf_compute_loss' , a ): # The number of elements in the loss should be the same as the number of elements in the label __lowerCamelCase : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : int = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=a )[0] ] __lowerCamelCase : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __lowerCamelCase : Optional[int] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : Dict = prepared_for_class.pop('input_ids' ) __lowerCamelCase : str = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __lowerCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : List[str] = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __lowerCamelCase : int = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __lowerCamelCase : Tuple = -100 __lowerCamelCase : Tuple = tf.convert_to_tensor(a ) __lowerCamelCase : Tuple = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __lowerCamelCase : int = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : str = model(a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __lowerCamelCase : str = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) # Get keys that were added with the _prepare_for_class function __lowerCamelCase : Optional[Any] = prepared_for_class.keys() - inputs_dict.keys() __lowerCamelCase : List[Any] = inspect.signature(model.call ).parameters __lowerCamelCase : List[str] = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __lowerCamelCase : Optional[int] = {0: 'input_ids'} for label_key in label_keys: __lowerCamelCase : Dict = signature_names.index(a ) __lowerCamelCase : str = label_key __lowerCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __lowerCamelCase : Optional[int] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __lowerCamelCase : Optional[int] = prepared_for_class[value] __lowerCamelCase : Any = tuple(a ) # Send to model __lowerCamelCase : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def _snake_case ( self: List[str] ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: int ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: Dict ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( a , a , a , a , a , a , a ) @slow def _snake_case ( self: int ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Dict = TFLayoutLMvaModel.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self: Optional[int] ): return LayoutLMvaImageProcessor(apply_ocr=a ) if is_vision_available() else None @slow def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Tuple = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __lowerCamelCase : Union[str, Any] = self.default_image_processor __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : str = image_processor(images=a , return_tensors='tf' ).pixel_values __lowerCamelCase : Union[str, Any] = tf.constant([[1, 2]] ) __lowerCamelCase : str = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __lowerCamelCase : int = model(input_ids=a , bbox=a , pixel_values=a , training=a ) # verify the logits __lowerCamelCase : Optional[int] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , a ) __lowerCamelCase : Any = tf.constant( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-4 ) )
669
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch 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_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' __snake_case = 1 @register_to_config def __init__( self: str , a: str=2000 , a: List[str]=0.1 , a: Any=20 , a: Dict=1e-3 ): __lowerCamelCase : Dict = None __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = None def _snake_case ( self: int , a: str , a: Union[str, torch.device] = None ): __lowerCamelCase : int = torch.linspace(1 , self.config.sampling_eps , a , device=a ) def _snake_case ( self: List[Any] , a: Union[str, Any] , a: Tuple , a: Optional[Any] , a: Dict=None ): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __lowerCamelCase : Tuple = ( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __lowerCamelCase : Optional[int] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __lowerCamelCase : Optional[Any] = std.flatten() while len(std.shape ) < len(score.shape ): __lowerCamelCase : List[str] = std.unsqueeze(-1 ) __lowerCamelCase : Any = -score / std # compute __lowerCamelCase : List[Any] = -1.0 / len(self.timesteps ) __lowerCamelCase : Any = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __lowerCamelCase : Dict = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __lowerCamelCase : int = beta_t.unsqueeze(-1 ) __lowerCamelCase : Any = -0.5 * beta_t * x __lowerCamelCase : List[Any] = torch.sqrt(a ) __lowerCamelCase : Tuple = drift - diffusion**2 * score __lowerCamelCase : str = x + drift * dt # add noise __lowerCamelCase : Any = randn_tensor(x.shape , layout=x.layout , generator=a , device=x.device , dtype=x.dtype ) __lowerCamelCase : Any = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self: Optional[int] ): return self.config.num_train_timesteps
669
1
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class A_ ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = StableUnCLIPImgaImgPipeline __snake_case = TEXT_GUIDED_IMAGE_VARIATION_PARAMS __snake_case = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __snake_case = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess __snake_case = frozenset([] ) def _snake_case ( self: Dict ): __lowerCamelCase : int = 32 __lowerCamelCase : Any = embedder_hidden_size # image encoding components __lowerCamelCase : List[str] = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) __lowerCamelCase : Dict = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=a , projection_dim=a , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) __lowerCamelCase : Tuple = StableUnCLIPImageNormalizer(embedding_dim=a ) __lowerCamelCase : Dict = DDPMScheduler(beta_schedule='squaredcos_cap_v2' ) torch.manual_seed(0 ) __lowerCamelCase : Union[str, Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) __lowerCamelCase : Dict = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=a , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) __lowerCamelCase : Dict = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=a , layers_per_block=1 , upcast_attention=a , use_linear_projection=a , ) torch.manual_seed(0 ) __lowerCamelCase : str = DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , prediction_type='v_prediction' , set_alpha_to_one=a , steps_offset=1 , ) torch.manual_seed(0 ) __lowerCamelCase : int = AutoencoderKL() __lowerCamelCase : List[str] = { # image encoding components 'feature_extractor': feature_extractor, 'image_encoder': image_encoder.eval(), # image noising components 'image_normalizer': image_normalizer.eval(), 'image_noising_scheduler': image_noising_scheduler, # regular denoising components 'tokenizer': tokenizer, 'text_encoder': text_encoder.eval(), 'unet': unet.eval(), 'scheduler': scheduler, 'vae': vae.eval(), } return components def _snake_case ( self: List[str] , a: Optional[Any] , a: List[Any]=0 , a: int=True ): if str(a ).startswith('mps' ): __lowerCamelCase : Any = torch.manual_seed(a ) else: __lowerCamelCase : List[Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : List[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a ) ).to(a ) if pil_image: __lowerCamelCase : int = input_image * 0.5 + 0.5 __lowerCamelCase : Tuple = input_image.clamp(0 , 1 ) __lowerCamelCase : Dict = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __lowerCamelCase : List[str] = DiffusionPipeline.numpy_to_pil(a )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def _snake_case ( self: Optional[int] ): __lowerCamelCase : List[str] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Union[str, Any] = self.get_dummy_components() __lowerCamelCase : Any = StableUnCLIPImgaImgPipeline(**a ) __lowerCamelCase : Optional[int] = sd_pipe.to(a ) sd_pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[Any] = self.get_dummy_inputs(a ) inputs.update({'image_embeds': None} ) __lowerCamelCase : Tuple = sd_pipe(**a ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCamelCase : List[str] = np.array([0.3_8_7_2, 0.7_2_2_4, 0.5_6_0_1, 0.4_7_4_1, 0.6_8_7_2, 0.5_8_1_4, 0.4_6_3_6, 0.3_8_6_7, 0.5_0_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: List[str] ): __lowerCamelCase : str = torch_device in ['cpu', 'mps'] self._test_attention_slicing_forward_pass(test_max_difference=a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = torch_device in ['cpu', 'mps'] self._test_inference_batch_single_identical(test_max_difference=a ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def _snake_case ( self: List[str] ): self._test_xformers_attention_forwardGenerator_pass(test_max_difference=a ) @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Optional[Any] ): __lowerCamelCase : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) __lowerCamelCase : Dict = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy' ) __lowerCamelCase : List[str] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-l-img2img' , torch_dtype=torch.floataa ) pipe.to(a ) pipe.set_progress_bar_config(disable=a ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCamelCase : List[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) __lowerCamelCase : Optional[int] = pipe(a , 'anime turle' , generator=a , output_type='np' ) __lowerCamelCase : List[Any] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a , a ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) __lowerCamelCase : Union[str, Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy' ) __lowerCamelCase : Dict = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) pipe.to(a ) pipe.set_progress_bar_config(disable=a ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCamelCase : Optional[int] = torch.Generator(device='cpu' ).manual_seed(0 ) __lowerCamelCase : Optional[Any] = pipe(a , 'anime turle' , generator=a , output_type='np' ) __lowerCamelCase : Dict = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a , a ) def _snake_case ( self: Optional[int] ): __lowerCamelCase : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __lowerCamelCase : int = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) __lowerCamelCase : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __lowerCamelCase : Dict = pipe( a , 'anime turtle' , num_inference_steps=2 , output_type='np' , ) __lowerCamelCase : Optional[Any] = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__ ) if n_element < 1: __lowerCamelCase : str = ValueError('a should be a positive number' ) raise my_error __lowerCamelCase : Tuple = [1] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = (0, 0, 0) __lowerCamelCase : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowercase_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') lowercase_ = hamming(int(n)) print('-----------------------------------------------------') print(F"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
669
1
from queue import PriorityQueue from typing import Any import numpy as np def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ): for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCamelCase : Tuple = cst_fwd.get(SCREAMING_SNAKE_CASE__ , np.inf ) __lowerCamelCase : Union[str, Any] = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCamelCase : Any = new_cost_f __lowerCamelCase : Tuple = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCamelCase : List[Any] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = -1 __lowerCamelCase : Any = set() __lowerCamelCase : Tuple = set() __lowerCamelCase : List[str] = {source: 0} __lowerCamelCase : Dict = {destination: 0} __lowerCamelCase : List[str] = {source: None} __lowerCamelCase : Union[str, Any] = {destination: None} __lowerCamelCase : PriorityQueue[Any] = PriorityQueue() __lowerCamelCase : PriorityQueue[Any] = PriorityQueue() __lowerCamelCase : Union[str, Any] = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCamelCase , __lowerCamelCase : Dict = queue_forward.get() visited_forward.add(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase : Any = queue_backward.get() visited_backward.add(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = pass_and_relaxation( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase : List[Any] = pass_and_relaxation( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCamelCase : int = shortest_distance return shortest_path_distance lowercase_ = { 'B': [['C', 1]], 'C': [['D', 1]], 'D': [['F', 1]], 'E': [['B', 1], ['G', 2]], 'F': [], 'G': [['F', 1]], } lowercase_ = { 'B': [['E', 1]], 'C': [['B', 1]], 'D': [['C', 1]], 'F': [['D', 1], ['G', 1]], 'E': [[None, np.inf]], 'G': [['E', 2]], } if __name__ == "__main__": import doctest doctest.testmod()
669
import unittest from knapsack import greedy_knapsack as kp class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: List[Any] ): __lowerCamelCase : str = [10, 20, 30, 40, 50, 60] __lowerCamelCase : List[str] = [2, 4, 6, 8, 10, 12] __lowerCamelCase : Tuple = 100 self.assertEqual(kp.calc_profit(a , a , a ) , 210 ) def _snake_case ( self: str ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'Weight can not be negative.' ) def _snake_case ( self: Dict ): self.assertRaisesRegex(a , 'Profit can not be negative.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: Any ): self.assertRaisesRegex( a , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
669
1
from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class A_ ( nn.Module ): '''simple docstring''' def __init__( self: Dict , a: int = 16 , a: int = 88 , a: Optional[int] = None , a: int = 1 , a: float = 0.0 , a: int = 32 , a: Optional[int] = None , a: bool = False , a: Optional[int] = None , a: Optional[int] = None , a: str = "geglu" , a: Optional[int] = None , ): super().__init__() __lowerCamelCase : Any = nn.ModuleList( [ TransformeraDModel( num_attention_heads=a , attention_head_dim=a , in_channels=a , num_layers=a , dropout=a , norm_num_groups=a , cross_attention_dim=a , attention_bias=a , sample_size=a , num_vector_embeds=a , activation_fn=a , num_embeds_ada_norm=a , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference __lowerCamelCase : List[Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` __lowerCamelCase : int = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` __lowerCamelCase : str = [1, 0] def _snake_case ( self: List[Any] , a: Tuple , a: Any , a: Any=None , a: str=None , a: Optional[Any]=None , a: bool = True , ): __lowerCamelCase : List[str] = hidden_states __lowerCamelCase : Union[str, Any] = [] __lowerCamelCase : List[Any] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens __lowerCamelCase : List[str] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] __lowerCamelCase : List[Any] = self.transformer_index_for_condition[i] __lowerCamelCase : Optional[Any] = self.transformers[transformer_index]( a , encoder_hidden_states=a , timestep=a , cross_attention_kwargs=a , return_dict=a , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] __lowerCamelCase : Union[str, Any] = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) __lowerCamelCase : int = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=a )
669
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any]=2 , a: str=3 , a: Any=4 , a: Union[str, Any]=2 , a: Tuple=7 , a: int=True , a: Tuple=True , a: List[str]=True , a: Union[str, Any]=True , a: str=99 , a: Tuple=36 , a: int=2 , a: Dict=4 , a: Union[str, Any]=37 , a: List[str]="gelu" , a: List[Any]=0.1 , a: Optional[int]=0.1 , a: Dict=512 , a: Union[str, Any]=16 , a: str=2 , a: int=0.0_2 , a: Optional[Any]=6 , a: Optional[int]=6 , a: Dict=3 , a: Optional[Any]=4 , a: Optional[Any]=None , a: Dict=1000 , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Optional[int] = num_channels __lowerCamelCase : str = image_size __lowerCamelCase : int = patch_size __lowerCamelCase : List[str] = is_training __lowerCamelCase : Dict = use_input_mask __lowerCamelCase : Any = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : str = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : List[Any] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : int = type_sequence_label_size __lowerCamelCase : List[str] = initializer_range __lowerCamelCase : List[str] = coordinate_size __lowerCamelCase : int = shape_size __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : int = num_choices __lowerCamelCase : int = scope __lowerCamelCase : Any = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __lowerCamelCase : Any = text_seq_length __lowerCamelCase : Optional[Any] = (image_size // patch_size) ** 2 + 1 __lowerCamelCase : Any = self.text_seq_length + self.image_seq_length def _snake_case ( self: List[str] ): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __lowerCamelCase : int = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __lowerCamelCase : List[str] = bbox[i, j, 3] __lowerCamelCase : str = bbox[i, j, 1] __lowerCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __lowerCamelCase : Tuple = bbox[i, j, 2] __lowerCamelCase : Any = bbox[i, j, 0] __lowerCamelCase : List[str] = tmp_coordinate __lowerCamelCase : str = tf.constant(a ) __lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.text_seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __lowerCamelCase : Dict = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self: Tuple , a: List[Any] , a: Any , a: List[str] , a: Dict , a: Optional[Any] , a: Dict ): __lowerCamelCase : Optional[Any] = TFLayoutLMvaModel(config=a ) # text + image __lowerCamelCase : Optional[Any] = model(a , pixel_values=a , training=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , training=a , ) __lowerCamelCase : List[Any] = model(a , bbox=a , pixel_values=a , training=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __lowerCamelCase : List[Any] = model(a , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __lowerCamelCase : Optional[Any] = model({'pixel_values': pixel_values} , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self: Dict , a: Dict , a: Optional[Any] , a: int , a: Optional[int] , a: List[str] , a: List[str] , a: List[str] ): __lowerCamelCase : List[str] = self.num_labels __lowerCamelCase : str = TFLayoutLMvaForSequenceClassification(config=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any] , a: Dict , a: Optional[Any] , a: Tuple , a: Optional[Any] , a: List[Any] ): __lowerCamelCase : Union[str, Any] = self.num_labels __lowerCamelCase : Any = TFLayoutLMvaForTokenClassification(config=a ) __lowerCamelCase : Optional[Any] = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self: Dict , a: Optional[Any] , a: str , a: Dict , a: Union[str, Any] , a: List[Any] , a: Optional[int] , a: List[str] ): __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Any = TFLayoutLMvaForQuestionAnswering(config=a ) __lowerCamelCase : Any = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , training=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] ): __lowerCamelCase : str = self.prepare_config_and_inputs() ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : List[Any] = config_and_inputs __lowerCamelCase : Tuple = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: int , a: List[str] , a: Any , a: Optional[Any] , a: Tuple , a: Tuple ): return True def _snake_case ( self: str , a: Any , a: Any , a: Optional[int]=False ): __lowerCamelCase : List[str] = copy.deepcopy(a ) if model_class in get_values(a ): __lowerCamelCase : Tuple = { k: tf.tile(tf.expand_dims(a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a ): __lowerCamelCase : Any = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Dict = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def _snake_case ( self: Tuple ): __lowerCamelCase : int = TFLayoutLMvaModelTester(self ) __lowerCamelCase : str = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self: Union[str, Any] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : int = model_class(a ) if getattr(a , 'hf_compute_loss' , a ): # The number of elements in the loss should be the same as the number of elements in the label __lowerCamelCase : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : int = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=a )[0] ] __lowerCamelCase : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __lowerCamelCase : Optional[int] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : Dict = prepared_for_class.pop('input_ids' ) __lowerCamelCase : str = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __lowerCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : List[str] = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __lowerCamelCase : int = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __lowerCamelCase : Tuple = -100 __lowerCamelCase : Tuple = tf.convert_to_tensor(a ) __lowerCamelCase : Tuple = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __lowerCamelCase : int = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : str = model(a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __lowerCamelCase : str = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) # Get keys that were added with the _prepare_for_class function __lowerCamelCase : Optional[Any] = prepared_for_class.keys() - inputs_dict.keys() __lowerCamelCase : List[Any] = inspect.signature(model.call ).parameters __lowerCamelCase : List[str] = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __lowerCamelCase : Optional[int] = {0: 'input_ids'} for label_key in label_keys: __lowerCamelCase : Dict = signature_names.index(a ) __lowerCamelCase : str = label_key __lowerCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __lowerCamelCase : Optional[int] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __lowerCamelCase : Optional[int] = prepared_for_class[value] __lowerCamelCase : Any = tuple(a ) # Send to model __lowerCamelCase : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def _snake_case ( self: List[str] ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: int ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: Dict ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( a , a , a , a , a , a , a ) @slow def _snake_case ( self: int ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Dict = TFLayoutLMvaModel.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self: Optional[int] ): return LayoutLMvaImageProcessor(apply_ocr=a ) if is_vision_available() else None @slow def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Tuple = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __lowerCamelCase : Union[str, Any] = self.default_image_processor __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : str = image_processor(images=a , return_tensors='tf' ).pixel_values __lowerCamelCase : Union[str, Any] = tf.constant([[1, 2]] ) __lowerCamelCase : str = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __lowerCamelCase : int = model(input_ids=a , bbox=a , pixel_values=a , training=a ) # verify the logits __lowerCamelCase : Optional[int] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , a ) __lowerCamelCase : Any = tf.constant( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-4 ) )
669
1
import math import random from typing import Any from .hill_climbing import SearchProblem def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = math.inf , SCREAMING_SNAKE_CASE__ = -math.inf , SCREAMING_SNAKE_CASE__ = math.inf , SCREAMING_SNAKE_CASE__ = -math.inf , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = 100 , SCREAMING_SNAKE_CASE__ = 0.01 , SCREAMING_SNAKE_CASE__ = 1 , ): __lowerCamelCase : List[Any] = False __lowerCamelCase : List[str] = search_prob __lowerCamelCase : Tuple = start_temperate __lowerCamelCase : Tuple = [] __lowerCamelCase : Tuple = 0 __lowerCamelCase : int = None while not search_end: __lowerCamelCase : str = current_state.score() if best_state is None or current_score > best_state.score(): __lowerCamelCase : List[str] = current_state scores.append(SCREAMING_SNAKE_CASE__ ) iterations += 1 __lowerCamelCase : List[Any] = None __lowerCamelCase : Union[str, Any] = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to __lowerCamelCase : int = random.randint(0 , len(SCREAMING_SNAKE_CASE__ ) - 1 ) # picking a random neighbor __lowerCamelCase : str = neighbors.pop(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: __lowerCamelCase : str = change * -1 # in case we are finding minimum if change > 0: # improves the solution __lowerCamelCase : List[str] = picked_neighbor else: __lowerCamelCase : List[Any] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability __lowerCamelCase : Union[str, Any] = picked_neighbor __lowerCamelCase : Optional[int] = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor __lowerCamelCase : Optional[Any] = True else: __lowerCamelCase : List[Any] = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) plt.xlabel('Iterations' ) plt.ylabel('Function values' ) plt.show() return best_state if __name__ == "__main__": def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) lowercase_ = SearchProblem(x=1_2, y=4_7, step_size=1, function_to_optimize=test_fa) lowercase_ = simulated_annealing( prob, find_max=False, max_x=1_0_0, min_x=5, max_y=5_0, min_y=-5, visualization=True ) print( 'The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) # starting the problem with initial coordinates (12, 47) lowercase_ = SearchProblem(x=1_2, y=4_7, step_size=1, function_to_optimize=test_fa) lowercase_ = simulated_annealing( prob, find_max=True, max_x=1_0_0, min_x=5, max_y=5_0, min_y=-5, visualization=True ) print( 'The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 ' F"""and 50 > y > - 5 found via hill climbing: {local_min.score()}""" ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return (3 * x**2) - (6 * y) lowercase_ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowercase_ = simulated_annealing(prob, find_max=False, visualization=True) print( 'The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" ) lowercase_ = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) lowercase_ = simulated_annealing(prob, find_max=True, visualization=True) print( 'The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: ' F"""{local_min.score()}""" )
669
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = CLIPTokenizer __snake_case = CLIPTokenizerFast __snake_case = True __snake_case = {} __snake_case = False def _snake_case ( self: Union[str, Any] ): super().setUp() # fmt: off __lowerCamelCase : Any = ['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 __lowerCamelCase : Tuple = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : List[Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>'] __lowerCamelCase : Tuple = {'unk_token': '<unk>'} __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : 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(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: Tuple , **a: Union[str, Any] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Union[str, Any] , **a: List[str] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : Tuple = 'lower newer' __lowerCamelCase : Tuple = 'lower newer' return input_text, output_text def _snake_case ( self: List[str] ): __lowerCamelCase : List[Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase : Optional[Any] = 'lower newer' __lowerCamelCase : int = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>'] __lowerCamelCase : Optional[int] = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : int = tokens + [tokenizer.unk_token] __lowerCamelCase : int = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def _snake_case ( self: Union[str, Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[Any] = self.tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : int = self.rust_tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : str = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.' __lowerCamelCase : Optional[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[Any] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __lowerCamelCase : List[Any] = 'xa\u0303y' + ' ' + 'x\xe3y' __lowerCamelCase : Tuple = tokenizer_s.tokenize(a ) __lowerCamelCase : Any = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type __lowerCamelCase : List[Any] = [ '\u0009', # (horizontal tab, '\t') '\u000B', # (vertical tab) '\u000C', # (form feed) '\u0020', # (space, ' ') '\u200E', # (left-to-right mark):w '\u200F', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __lowerCamelCase : List[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[int] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type __lowerCamelCase : str = [ '\u000A', # (line feed, '\n') '\r\n', # (carriage return and line feed, '\r\n') '\u000D', # (carriage return, '\r') '\r', # (carriage return, '\r') '\u000D', # (carriage return, '\r') '\u2028', # (line separator) '\u2029', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __lowerCamelCase : Dict = tokenizer_s.tokenize(a ) __lowerCamelCase : List[str] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def _snake_case ( self: List[Any] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : Optional[int] = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` __lowerCamelCase : Optional[int] = F'{text_of_1_token} {text_of_1_token}' __lowerCamelCase : Dict = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) __lowerCamelCase : List[Any] = F' {text}' __lowerCamelCase : str = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def _snake_case ( self: str ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def _snake_case ( self: Tuple ): super().test_tokenization_python_rust_equals() def _snake_case ( self: Tuple ): # CLIP always lower cases letters pass
669
1
lowercase_ = 'Input must be a string of 8 numbers plus letter' lowercase_ = 'TRWAGMYFPDXBNJZSQVHLCKE' def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = f'Expected string as input, found {type(SCREAMING_SNAKE_CASE__ ).__name__}' raise TypeError(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = spanish_id.replace('-' , '' ).upper() if len(SCREAMING_SNAKE_CASE__ ) != 9: raise ValueError(SCREAMING_SNAKE_CASE__ ) try: __lowerCamelCase : Dict = int(spanish_id_clean[0:8] ) __lowerCamelCase : List[str] = spanish_id_clean[8] except ValueError as ex: raise ValueError(SCREAMING_SNAKE_CASE__ ) from ex if letter.isdigit(): raise ValueError(SCREAMING_SNAKE_CASE__ ) return letter == LOOKUP_LETTERS[number % 23] if __name__ == "__main__": import doctest doctest.testmod()
669
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowercase_ = False try: lowercase_ = _is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class A_ : '''simple docstring''' def __init__( self: int , a: str = None , a: list = [] ): __lowerCamelCase : Dict = 0 __lowerCamelCase : Dict = choices __lowerCamelCase : Tuple = prompt if sys.platform == "win32": __lowerCamelCase : Union[str, Any] = '*' else: __lowerCamelCase : Any = '➔ ' def _snake_case ( self: Any , a: Tuple , a: str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def _snake_case ( self: Tuple , a: int ): if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def _snake_case ( self: Optional[int] , a: Direction , a: int = 1 ): __lowerCamelCase : str = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['up'] ) def _snake_case ( self: Tuple ): self.move_direction(Direction.UP ) @input.mark(KEYMAP['down'] ) def _snake_case ( self: Optional[int] ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['newline'] ) def _snake_case ( self: str ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) return self.position @input.mark(KEYMAP['interrupt'] ) def _snake_case ( self: Union[str, Any] ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def _snake_case ( self: str ): __lowerCamelCase : List[Any] = int(chr(self.current_selection ) ) __lowerCamelCase : Any = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def _snake_case ( self: str , a: int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , '\n' ) if in_colab: forceWrite('Please input a choice index (starting from 0), and press enter' , '\n' ) else: forceWrite('Please select a choice using the arrow or number keys, and selecting with enter' , '\n' ) __lowerCamelCase : Dict = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('\n' ) move_cursor(len(self.choices ) - self.position , 'UP' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase : Any = int(builtins.input() ) except ValueError: __lowerCamelCase : str = default_choice else: __lowerCamelCase : Optional[int] = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , 'UP' ) clear_line() self.write_choice(a , '\n' ) return choice
669
1
import argparse import os import re import torch from flax.traverse_util import flatten_dict from tax import checkpoints from transformers import ( AutoTokenizer, PixaStructConfig, PixaStructForConditionalGeneration, PixaStructImageProcessor, PixaStructProcessor, PixaStructTextConfig, PixaStructVisionConfig, ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = checkpoints.load_tax_checkpoint(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Dict = flatten_dict(SCREAMING_SNAKE_CASE__ ) return flax_params def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[Any] = {} __lowerCamelCase : Tuple = { 'token_embedder': 'embeddings', 'encoder_norm': 'layernorm', 'kernel': 'weight', '.out': '.output', 'scale': 'weight', 'embedders_0.pos_embedding': 'row_embedder.weight', 'embedders_1.pos_embedding': 'column_embedder.weight', } __lowerCamelCase : Any = { 'query': 'attention.query', 'key': 'attention.key', 'value': 'attention.value', 'output.dense': 'output', 'encoder_decoder_attention.o': 'encoder_decoder_attention.attention.o', 'pre_self_attention_layer_norm': 'self_attention.layer_norm', 'pre_cross_attention_layer_norm': 'encoder_decoder_attention.layer_norm', 'mlp.': 'mlp.DenseReluDense.', 'pre_mlp_layer_norm': 'mlp.layer_norm', 'self_attention.o': 'self_attention.attention.o', 'decoder.embeddings.embedding': 'decoder.embed_tokens.weight', 'decoder.relpos_bias.rel_embedding': 'decoder.layer.0.self_attention.attention.relative_attention_bias.weight', 'decoder.decoder_norm.weight': 'decoder.final_layer_norm.weight', 'decoder.logits_dense.weight': 'decoder.lm_head.weight', } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key __lowerCamelCase : int = '.'.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): __lowerCamelCase : Optional[int] = new_key.replace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): __lowerCamelCase : List[Any] = new_key.replace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number __lowerCamelCase : Optional[int] = re.sub(r'layers_(\d+)' , r'layer.\1' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = new_key.replace('encoder' , 'encoder.encoder' ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number __lowerCamelCase : str = re.sub(r'layers_(\d+)' , r'layer.\1' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = flax_dict[key] __lowerCamelCase : Dict = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): __lowerCamelCase : str = torch.from_numpy(converted_dict[key].T ) else: __lowerCamelCase : Union[str, Any] = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=False ): __lowerCamelCase : Optional[Any] = get_flax_param(SCREAMING_SNAKE_CASE__ ) if not use_large: __lowerCamelCase : int = PixaStructVisionConfig() __lowerCamelCase : Dict = PixaStructTextConfig() else: __lowerCamelCase : int = PixaStructVisionConfig( hidden_size=1_536 , d_ff=3_968 , num_attention_heads=24 , num_hidden_layers=18 ) __lowerCamelCase : Dict = PixaStructTextConfig(hidden_size=1_536 , d_ff=3_968 , num_heads=24 , num_layers=18 ) __lowerCamelCase : List[Any] = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = PixaStructForConditionalGeneration(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = rename_and_convert_flax_params(SCREAMING_SNAKE_CASE__ ) model.load_state_dict(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = AutoTokenizer.from_pretrained('ybelkada/test-pix2struct-tokenizer' ) __lowerCamelCase : str = PixaStructImageProcessor() __lowerCamelCase : int = PixaStructProcessor(image_processor=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ ) if use_large: __lowerCamelCase : List[Any] = 4_096 __lowerCamelCase : Dict = True # mkdir if needed os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) print('Model saved in {}'.format(SCREAMING_SNAKE_CASE__ ) ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument('--t5x_checkpoint_path', default=None, type=str, help='Path to the original T5x checkpoint.') parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--use_large', action='store_true', help='Use large model.') parser.add_argument('--is_vqa', action='store_true', help='Use large model.') lowercase_ = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
669
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = (CMStochasticIterativeScheduler,) __snake_case = 10 def _snake_case ( self: Any , **a: Dict ): __lowerCamelCase : Optional[Any] = { 'num_train_timesteps': 201, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } config.update(**a ) return config def _snake_case ( self: List[Any] ): __lowerCamelCase : Any = 10 __lowerCamelCase : Any = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = self.scheduler_classes[0](**a ) scheduler.set_timesteps(a ) __lowerCamelCase : Any = scheduler.timesteps[0] __lowerCamelCase : List[str] = scheduler.timesteps[1] __lowerCamelCase : Union[str, Any] = self.dummy_sample __lowerCamelCase : int = 0.1 * sample __lowerCamelCase : Optional[Any] = scheduler.step(a , a , a ).prev_sample __lowerCamelCase : List[str] = scheduler.step(a , a , a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self: Optional[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a ) def _snake_case ( self: List[str] ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=a ) def _snake_case ( self: Tuple ): __lowerCamelCase : Tuple = self.scheduler_classes[0] __lowerCamelCase : Tuple = self.get_scheduler_config() __lowerCamelCase : Tuple = scheduler_class(**a ) __lowerCamelCase : int = 1 scheduler.set_timesteps(a ) __lowerCamelCase : Optional[int] = scheduler.timesteps __lowerCamelCase : List[str] = torch.manual_seed(0 ) __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(a ): # 1. scale model input __lowerCamelCase : List[str] = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Optional[int] = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : str = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : str = pred_prev_sample __lowerCamelCase : List[str] = torch.sum(torch.abs(a ) ) __lowerCamelCase : str = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**a ) __lowerCamelCase : List[Any] = [106, 0] scheduler.set_timesteps(timesteps=a ) __lowerCamelCase : Dict = scheduler.timesteps __lowerCamelCase : int = torch.manual_seed(0 ) __lowerCamelCase : Any = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __lowerCamelCase : Tuple = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Tuple = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : Any = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : Any = pred_prev_sample __lowerCamelCase : Dict = torch.sum(torch.abs(a ) ) __lowerCamelCase : Optional[Any] = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : int = self.get_scheduler_config() __lowerCamelCase : List[Any] = scheduler_class(**a ) __lowerCamelCase : Optional[Any] = [39, 30, 12, 15, 0] with self.assertRaises(a , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=a ) def _snake_case ( self: int ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Union[str, Any] = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [39, 30, 12, 1, 0] __lowerCamelCase : List[Any] = len(a ) with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=a , timesteps=a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Dict = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=a )
669
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {'configuration_xglm': ['XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XGLMConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['XGLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['XGLMTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'XGLMForCausalLM', 'XGLMModel', 'XGLMPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'FlaxXGLMForCausalLM', 'FlaxXGLMModel', 'FlaxXGLMPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXGLMForCausalLM', 'TFXGLMModel', 'TFXGLMPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure)
669
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") lowercase_ = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find('meta', {'property': 'og:image'})['content'] lowercase_ = requests.get(image_url).content lowercase_ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
669
1
from __future__ import annotations def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , ): __lowerCamelCase : Dict = cipher_alphabet or [chr(SCREAMING_SNAKE_CASE__ ) for i in range(97 , 123 )] # If the argument is None or the user provided an empty dictionary if not frequencies_dict: # Frequencies of letters in the english language (how much they show up) __lowerCamelCase : Dict = { 'a': 0.08_497, 'b': 0.01_492, 'c': 0.02_202, 'd': 0.04_253, 'e': 0.11_162, 'f': 0.02_228, 'g': 0.02_015, 'h': 0.06_094, 'i': 0.07_546, 'j': 0.00_153, 'k': 0.01_292, 'l': 0.04_025, 'm': 0.02_406, 'n': 0.06_749, 'o': 0.07_507, 'p': 0.01_929, 'q': 0.00_095, 'r': 0.07_587, 's': 0.06_327, 't': 0.09_356, 'u': 0.02_758, 'v': 0.00_978, 'w': 0.02_560, 'x': 0.00_150, 'y': 0.01_994, 'z': 0.00_077, } else: # Custom frequencies dictionary __lowerCamelCase : str = frequencies_dict if not case_sensitive: __lowerCamelCase : Optional[Any] = ciphertext.lower() # Chi squared statistic values __lowerCamelCase : dict[int, tuple[float, str]] = {} # cycle through all of the shifts for shift in range(len(SCREAMING_SNAKE_CASE__ ) ): __lowerCamelCase : Optional[int] = '' # decrypt the message with the shift for letter in ciphertext: try: # Try to index the letter in the alphabet __lowerCamelCase : List[Any] = (alphabet_letters.index(letter.lower() ) - shift) % len( SCREAMING_SNAKE_CASE__ ) decrypted_with_shift += ( alphabet_letters[new_key].upper() if case_sensitive and letter.isupper() else alphabet_letters[new_key] ) except ValueError: # Append the character if it isn't in the alphabet decrypted_with_shift += letter __lowerCamelCase : Optional[Any] = 0.0 # Loop through each letter in the decoded message with the shift for letter in decrypted_with_shift: if case_sensitive: __lowerCamelCase : List[str] = letter.lower() if letter in frequencies: # Get the amount of times the letter occurs in the message __lowerCamelCase : List[str] = decrypted_with_shift.lower().count(SCREAMING_SNAKE_CASE__ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies __lowerCamelCase : Any = frequencies[letter] * occurrences # Complete the chi squared statistic formula __lowerCamelCase : List[Any] = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value else: if letter.lower() in frequencies: # Get the amount of times the letter occurs in the message __lowerCamelCase : List[str] = decrypted_with_shift.count(SCREAMING_SNAKE_CASE__ ) # Get the excepcted amount of times the letter should appear based # on letter frequencies __lowerCamelCase : Tuple = frequencies[letter] * occurrences # Complete the chi squared statistic formula __lowerCamelCase : int = ((occurrences - expected) ** 2) / expected # Add the margin of error to the total chi squared statistic chi_squared_statistic += chi_letter_value # Add the data to the chi_squared_statistic_values dictionary __lowerCamelCase : str = ( chi_squared_statistic, decrypted_with_shift, ) # Get the most likely cipher by finding the cipher with the smallest chi squared # statistic def chi_squared_statistic_values_sorting_key(SCREAMING_SNAKE_CASE__ ) -> tuple[float, str]: return chi_squared_statistic_values[key] __lowerCamelCase : int = min( SCREAMING_SNAKE_CASE__ , key=SCREAMING_SNAKE_CASE__ , ) # Get all the data from the most likely cipher (key, decoded message) ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : int = chi_squared_statistic_values[most_likely_cipher] # Return the data on the most likely shift return ( most_likely_cipher, most_likely_cipher_chi_squared_value, decoded_most_likely_cipher, )
669
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore lowercase_ = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" lowercase_ = [file for file in filepaths if file != file.lower()] if upper_files: print(F"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') lowercase_ = [file for file in filepaths if ' ' in file] if space_files: print(F"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') lowercase_ = [file for file in filepaths if '-' in file] if hyphen_files: print(F"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') lowercase_ = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') lowercase_ = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
669
1
from __future__ import annotations import unittest from transformers import EsmConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers.models.esm.modeling_tf_esm import ( TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, TFEsmModel, ) class A_ : '''simple docstring''' def __init__( self: Any , a: str , ): __lowerCamelCase : List[Any] = parent __lowerCamelCase : Optional[Any] = 13 __lowerCamelCase : str = 7 __lowerCamelCase : List[str] = True __lowerCamelCase : Optional[int] = True __lowerCamelCase : Dict = True __lowerCamelCase : Tuple = 99 __lowerCamelCase : List[str] = 32 __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Any = 4 __lowerCamelCase : Dict = 37 __lowerCamelCase : List[Any] = 'gelu' __lowerCamelCase : List[Any] = 0.1 __lowerCamelCase : Optional[Any] = 0.1 __lowerCamelCase : Dict = 512 __lowerCamelCase : Dict = 16 __lowerCamelCase : Dict = 2 __lowerCamelCase : List[Any] = 0.0_2 __lowerCamelCase : List[str] = 3 __lowerCamelCase : List[Any] = 4 __lowerCamelCase : int = None def _snake_case ( self: Dict ): __lowerCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCamelCase : str = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCamelCase : Dict = None __lowerCamelCase : Optional[int] = None __lowerCamelCase : Any = None if self.use_labels: __lowerCamelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCamelCase : Any = ids_tensor([self.batch_size] , self.num_choices ) __lowerCamelCase : int = EsmConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , pad_token_id=1 , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self: Tuple ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : int = self.prepare_config_and_inputs() __lowerCamelCase : Optional[Any] = True __lowerCamelCase : Any = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __lowerCamelCase : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _snake_case ( self: Any , a: Tuple , a: Optional[int] , a: int , a: Union[str, Any] , a: int , a: List[Any] ): __lowerCamelCase : Dict = TFEsmModel(config=a ) __lowerCamelCase : int = {'input_ids': input_ids, 'attention_mask': input_mask} __lowerCamelCase : int = model(a ) __lowerCamelCase : int = [input_ids, input_mask] __lowerCamelCase : int = model(a ) __lowerCamelCase : Optional[Any] = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self: Optional[int] , a: int , a: Union[str, Any] , a: str , a: Dict , a: Union[str, Any] , a: Dict , a: Optional[int] , a: Any , ): __lowerCamelCase : Optional[Any] = True __lowerCamelCase : int = TFEsmModel(config=a ) __lowerCamelCase : Tuple = { 'input_ids': input_ids, 'attention_mask': input_mask, 'encoder_hidden_states': encoder_hidden_states, 'encoder_attention_mask': encoder_attention_mask, } __lowerCamelCase : List[str] = model(a ) __lowerCamelCase : Optional[int] = [input_ids, input_mask] __lowerCamelCase : int = model(a , encoder_hidden_states=a ) # Also check the case where encoder outputs are not passed __lowerCamelCase : Any = model(a , attention_mask=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self: Union[str, Any] , a: Optional[int] , a: Optional[int] , a: Dict , a: Tuple , a: str , a: str ): __lowerCamelCase : List[str] = TFEsmForMaskedLM(config=a ) __lowerCamelCase : List[str] = model([input_ids, input_mask] ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self: List[str] , a: str , a: List[str] , a: Any , a: Optional[Any] , a: Union[str, Any] , a: Optional[Any] ): __lowerCamelCase : int = self.num_labels __lowerCamelCase : Optional[int] = TFEsmForTokenClassification(config=a ) __lowerCamelCase : Dict = {'input_ids': input_ids, 'attention_mask': input_mask} __lowerCamelCase : Any = model(a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Union[str, Any] = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Any = config_and_inputs __lowerCamelCase : int = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFEsmModel, TFEsmForMaskedLM, TFEsmForSequenceClassification, TFEsmForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( { """feature-extraction""": TFEsmModel, """fill-mask""": TFEsmForMaskedLM, """text-classification""": TFEsmForSequenceClassification, """token-classification""": TFEsmForTokenClassification, """zero-shot""": TFEsmForSequenceClassification, } if is_tf_available() else {} ) __snake_case = False __snake_case = False def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : List[str] = TFEsmModelTester(self ) __lowerCamelCase : Optional[Any] = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self: List[Any] ): __lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : int = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a ) def _snake_case ( self: List[Any] ): __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a ) @slow def _snake_case ( self: List[str] ): for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Dict = TFEsmModel.from_pretrained(a ) self.assertIsNotNone(a ) @unittest.skip('Protein models do not support embedding resizing.' ) def _snake_case ( self: int ): pass @unittest.skip('Protein models do not support embedding resizing.' ) def _snake_case ( self: Optional[Any] ): pass def _snake_case ( self: Optional[int] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : Dict = model_class(a ) assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer ) if model_class is TFEsmForMaskedLM: # Output embedding test differs from the main test because they're a matrix, not a layer __lowerCamelCase : Optional[Any] = model.get_bias() assert isinstance(a , a ) for k, v in name.items(): assert isinstance(a , tf.Variable ) else: __lowerCamelCase : List[str] = model.get_output_embeddings() assert x is None __lowerCamelCase : Union[str, Any] = model.get_bias() assert name is None @require_tf class A_ ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[Any] = TFEsmForMaskedLM.from_pretrained('facebook/esm2_t6_8M_UR50D' ) __lowerCamelCase : Optional[int] = tf.constant([[0, 1, 2, 3, 4, 5]] ) __lowerCamelCase : Tuple = model(a )[0] __lowerCamelCase : Optional[Any] = [1, 6, 33] self.assertEqual(list(output.numpy().shape ) , a ) # compare the actual values for a slice. __lowerCamelCase : Optional[int] = tf.constant( [ [ [8.9_2_1_5_1_8, -1_0.5_8_9_8_1_4, -6.4_6_7_1_3_0_7], [-6.3_9_6_7_1_5_6, -1_3.9_1_1_3_7_7, -1.1_2_1_1_9_1_5], [-7.7_8_1_2_4_7, -1_3.9_5_1_5_5_7, -3.7_4_0_5_9_2], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-2 ) ) @slow def _snake_case ( self: Dict ): __lowerCamelCase : Optional[int] = TFEsmModel.from_pretrained('facebook/esm2_t6_8M_UR50D' ) __lowerCamelCase : Dict = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) __lowerCamelCase : Any = model(a )[0] # compare the actual values for a slice. __lowerCamelCase : List[Any] = tf.constant( [ [ [0.1_4_4_4_3_0_9_2, 0.5_4_1_2_5_3_2_7, 0.3_2_4_7_7_3_9], [0.3_0_3_4_0_4_8_4, 0.0_0_5_2_6_6_7_6, 0.3_1_0_7_7_7_2_2], [0.3_2_2_7_8_0_4_3, -0.2_4_9_8_7_0_9_6, 0.3_4_1_4_6_2_8], ] ] ) self.assertTrue(numpy.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1e-4 ) )
669
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_ = { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """xlm-roberta""" def __init__( self: Optional[Any] , a: int=3_0522 , a: List[Any]=768 , a: Tuple=12 , a: List[str]=12 , a: Dict=3072 , a: List[str]="gelu" , a: Any=0.1 , a: Optional[Any]=0.1 , a: str=512 , a: Optional[int]=2 , a: int=0.0_2 , a: str=1e-12 , a: str=1 , a: List[Any]=0 , a: Dict=2 , a: Dict="absolute" , a: List[Any]=True , a: str=None , **a: List[Any] , ): super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : str = hidden_act __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : int = max_position_embeddings __lowerCamelCase : Any = type_vocab_size __lowerCamelCase : int = initializer_range __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : List[Any] = position_embedding_type __lowerCamelCase : List[str] = use_cache __lowerCamelCase : Optional[int] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
669
1
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowercase_ = { 'configuration_informer': [ 'INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'InformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'InformerForPrediction', 'InformerModel', 'InformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_informer import ( INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, InformerForPrediction, InformerModel, InformerPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
669
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ConsistencyModelPipeline __snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __snake_case = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def _snake_case ( self: str ): __lowerCamelCase : Tuple = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _snake_case ( self: Tuple ): __lowerCamelCase : List[str] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _snake_case ( self: int , a: str=False ): if class_cond: __lowerCamelCase : str = self.dummy_cond_unet else: __lowerCamelCase : str = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCamelCase : Tuple = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def _snake_case ( self: int , a: List[str] , a: Any=0 ): if str(a ).startswith('mps' ): __lowerCamelCase : List[Any] = torch.manual_seed(a ) else: __lowerCamelCase : Tuple = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : Optional[Any] = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : str = ConsistencyModelPipeline(**a ) __lowerCamelCase : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Any = self.get_dummy_inputs(a ) __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[int] = ConsistencyModelPipeline(**a ) __lowerCamelCase : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(a ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : List[str] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Optional[int] = self.get_dummy_components() __lowerCamelCase : Tuple = ConsistencyModelPipeline(**a ) __lowerCamelCase : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = self.get_dummy_inputs(a ) __lowerCamelCase : str = 1 __lowerCamelCase : Optional[int] = None __lowerCamelCase : Any = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[int] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: List[str] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : List[Any] = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[Any] = ConsistencyModelPipeline(**a ) __lowerCamelCase : List[Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_dummy_inputs(a ) __lowerCamelCase : List[str] = 1 __lowerCamelCase : List[str] = None __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Optional[int] , a: str=0 , a: Tuple=False , a: Tuple="cpu" , a: List[str]=torch.floataa , a: Optional[Any]=(1, 3, 64, 64) ): __lowerCamelCase : Optional[Any] = torch.manual_seed(a ) __lowerCamelCase : Optional[int] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __lowerCamelCase : Dict = self.get_fixed_latents(seed=a , device=a , dtype=a , shape=a ) __lowerCamelCase : Optional[Any] = latents return inputs def _snake_case ( self: Any , a: Any=0 , a: List[str]="cpu" , a: Optional[Any]=torch.floataa , a: int=(1, 3, 64, 64) ): if type(a ) == str: __lowerCamelCase : Dict = torch.device(a ) __lowerCamelCase : Union[str, Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : str = randn_tensor(a , generator=a , device=a , dtype=a ) return latents def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs() __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Dict = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_inputs() __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Tuple = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : List[Any] = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs(get_fixed_latents=a , device=a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : int = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[Any] = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def _snake_case ( self: Dict ): __lowerCamelCase : Dict = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = self.get_inputs(get_fixed_latents=a , device=a ) __lowerCamelCase : str = 1 __lowerCamelCase : Union[str, Any] = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : str = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
669
1
from functools import reduce lowercase_ = ( '73167176531330624919225119674426574742355349194934' '96983520312774506326239578318016984801869478851843' '85861560789112949495459501737958331952853208805511' '12540698747158523863050715693290963295227443043557' '66896648950445244523161731856403098711121722383113' '62229893423380308135336276614282806444486645238749' '30358907296290491560440772390713810515859307960866' '70172427121883998797908792274921901699720888093776' '65727333001053367881220235421809751254540594752243' '52584907711670556013604839586446706324415722155397' '53697817977846174064955149290862569321978468622482' '83972241375657056057490261407972968652414535100474' '82166370484403199890008895243450658541227588666881' '16427171479924442928230863465674813919123162824586' '17866458359124566529476545682848912883142607690042' '24219022671055626321111109370544217506941658960408' '07198403850962455444362981230987879927244284909188' '84580156166097919133875499200524063689912560717606' '05886116467109405077541002256983155200055935729725' '71636269561882670428252483600823257530420752963450' ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ = N ): return max( # mypy cannot properly interpret reduce int(reduce(lambda SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str(int(SCREAMING_SNAKE_CASE__ ) * int(SCREAMING_SNAKE_CASE__ ) ) , n[i : i + 13] ) ) for i in range(len(SCREAMING_SNAKE_CASE__ ) - 12 ) ) if __name__ == "__main__": print(F"""{solution() = }""")
669
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """trocr""" __snake_case = ["""past_key_values"""] __snake_case = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Dict , a: List[str]=5_0265 , a: Optional[Any]=1024 , a: Tuple=12 , a: Dict=16 , a: Optional[Any]=4096 , a: Optional[Any]="gelu" , a: Optional[int]=512 , a: int=0.1 , a: str=0.0 , a: Union[str, Any]=0.0 , a: Any=2 , a: Optional[int]=0.0_2 , a: Optional[Any]=0.0 , a: List[Any]=True , a: Any=False , a: int=True , a: Optional[Any]=True , a: Tuple=1 , a: Union[str, Any]=0 , a: Any=2 , **a: List[Any] , ): __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : List[str] = decoder_layers __lowerCamelCase : Optional[Any] = decoder_attention_heads __lowerCamelCase : List[str] = decoder_ffn_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : Optional[Any] = max_position_embeddings __lowerCamelCase : Dict = dropout __lowerCamelCase : int = attention_dropout __lowerCamelCase : List[str] = activation_dropout __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Tuple = decoder_layerdrop __lowerCamelCase : str = use_cache __lowerCamelCase : List[Any] = scale_embedding __lowerCamelCase : Any = use_learned_position_embeddings __lowerCamelCase : List[Any] = layernorm_embedding super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , decoder_start_token_id=a , **a , )
669
1
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = KandinskyVaaImgaImgPipeline __snake_case = ["""image_embeds""", """negative_image_embeds""", """image"""] __snake_case = [ """image_embeds""", """negative_image_embeds""", """image""", ] __snake_case = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __snake_case = False @property def _snake_case ( self: Optional[int] ): return 32 @property def _snake_case ( self: Tuple ): return 32 @property def _snake_case ( self: List[str] ): return self.time_input_dim @property def _snake_case ( self: int ): return self.time_input_dim * 4 @property def _snake_case ( self: Dict ): return 100 @property def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Any = { 'in_channels': 4, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'image', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } __lowerCamelCase : Optional[int] = UNetaDConditionModel(**a ) return model @property def _snake_case ( self: Tuple ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def _snake_case ( self: Optional[int] ): torch.manual_seed(0 ) __lowerCamelCase : List[Any] = VQModel(**self.dummy_movq_kwargs ) return model def _snake_case ( self: str ): __lowerCamelCase : Any = self.dummy_unet __lowerCamelCase : Dict = self.dummy_movq __lowerCamelCase : int = { 'num_train_timesteps': 1000, 'beta_schedule': 'linear', 'beta_start': 0.0_0_0_8_5, 'beta_end': 0.0_1_2, 'clip_sample': False, 'set_alpha_to_one': False, 'steps_offset': 0, 'prediction_type': 'epsilon', 'thresholding': False, } __lowerCamelCase : str = DDIMScheduler(**a ) __lowerCamelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def _snake_case ( self: Optional[int] , a: Optional[int] , a: Dict=0 ): __lowerCamelCase : Optional[int] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(a ) ).to(a ) __lowerCamelCase : List[str] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( a ) # create init_image __lowerCamelCase : Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(a ) ).to(a ) __lowerCamelCase : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] __lowerCamelCase : Any = Image.fromarray(np.uinta(a ) ).convert('RGB' ).resize((256, 256) ) if str(a ).startswith('mps' ): __lowerCamelCase : List[str] = torch.manual_seed(a ) else: __lowerCamelCase : List[Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : List[str] = { 'image': init_image, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 64, 'width': 64, 'num_inference_steps': 10, 'guidance_scale': 7.0, 'strength': 0.2, 'output_type': 'np', } return inputs def _snake_case ( self: int ): __lowerCamelCase : Optional[Any] = 'cpu' __lowerCamelCase : int = self.get_dummy_components() __lowerCamelCase : int = self.pipeline_class(**a ) __lowerCamelCase : Optional[Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[Any] = pipe(**self.get_dummy_inputs(a ) ) __lowerCamelCase : List[str] = output.images __lowerCamelCase : int = pipe( **self.get_dummy_inputs(a ) , return_dict=a , )[0] __lowerCamelCase : Any = image[0, -3:, -3:, -1] __lowerCamelCase : Dict = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Any = np.array( [0.6_1_9_9_7_7_8, 0.6_3_9_8_4_4_0_6, 0.4_6_1_4_5_7_8_5, 0.6_2_9_4_4_9_8_4, 0.5_6_2_2_2_1_5, 0.4_7_3_0_6_1_3_2, 0.4_7_4_4_1_4_5_6, 0.4_6_0_7_6_0_6, 0.4_8_7_1_9_2_6_3] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F' expected_slice {expected_slice}, but got {image_slice.flatten()}' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}' @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: List[Any] ): __lowerCamelCase : int = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_img2img_frog.npy' ) __lowerCamelCase : Dict = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) __lowerCamelCase : List[str] = 'A red cartoon frog, 4k' __lowerCamelCase : List[Any] = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(a ) __lowerCamelCase : Tuple = KandinskyVaaImgaImgPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-decoder' , torch_dtype=torch.floataa ) __lowerCamelCase : List[Any] = pipeline.to(a ) pipeline.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = torch.Generator(device='cpu' ).manual_seed(0 ) __lowerCamelCase , __lowerCamelCase : List[Any] = pipe_prior( a , generator=a , num_inference_steps=5 , negative_prompt='' , ).to_tuple() __lowerCamelCase : List[Any] = pipeline( image=a , image_embeds=a , negative_image_embeds=a , generator=a , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='np' , ) __lowerCamelCase : List[Any] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a , a )
669
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """tokenizer"""] __snake_case = """CLIPImageProcessor""" __snake_case = ("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self: Union[str, Any] , a: int=None , a: List[str]=None , **a: str ): __lowerCamelCase : int = 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 , ) __lowerCamelCase : str = kwargs.pop('feature_extractor' ) __lowerCamelCase : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: List[Any]=None , a: List[str]=None , a: int=None , **a: List[Any] ): if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __lowerCamelCase : Dict = self.tokenizer(a , return_tensors=a , **a ) if images is not None: __lowerCamelCase : Tuple = self.image_processor(a , return_tensors=a , **a ) if text is not None and images is not None: __lowerCamelCase : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a ) , tensor_type=a ) def _snake_case ( self: List[Any] , *a: Optional[Any] , **a: int ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: Any , *a: Union[str, Any] , **a: Optional[Any] ): return self.tokenizer.decode(*a , **a ) @property def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = self.tokenizer.model_input_names __lowerCamelCase : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
669
1
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_roberta import RobertaTokenizer lowercase_ = logging.get_logger(__name__) lowercase_ = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} lowercase_ = { 'vocab_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/vocab.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/vocab.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/vocab.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json' ), }, 'merges_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/merges.txt', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/merges.txt', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/merges.txt', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt', 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt' ), }, 'tokenizer_file': { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/tokenizer.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/tokenizer.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json', 'roberta-base-openai-detector': ( 'https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json' ), 'roberta-large-openai-detector': ( 'https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json' ), }, } lowercase_ = { 'roberta-base': 5_1_2, 'roberta-large': 5_1_2, 'roberta-large-mnli': 5_1_2, 'distilroberta-base': 5_1_2, 'roberta-base-openai-detector': 5_1_2, 'roberta-large-openai-detector': 5_1_2, } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = VOCAB_FILES_NAMES __snake_case = PRETRAINED_VOCAB_FILES_MAP __snake_case = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __snake_case = ["""input_ids""", """attention_mask"""] __snake_case = RobertaTokenizer def __init__( self: Optional[Any] , a: Tuple=None , a: Union[str, Any]=None , a: Any=None , a: Dict="replace" , a: int="<s>" , a: Optional[Any]="</s>" , a: Optional[Any]="</s>" , a: List[str]="<s>" , a: int="<unk>" , a: List[str]="<pad>" , a: Any="<mask>" , a: Optional[int]=False , a: int=True , **a: Dict , ): super().__init__( a , a , tokenizer_file=a , errors=a , bos_token=a , eos_token=a , sep_token=a , cls_token=a , unk_token=a , pad_token=a , mask_token=a , add_prefix_space=a , trim_offsets=a , **a , ) __lowerCamelCase : Any = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , a ) != add_prefix_space: __lowerCamelCase : int = getattr(a , pre_tok_state.pop('type' ) ) __lowerCamelCase : int = add_prefix_space __lowerCamelCase : Union[str, Any] = pre_tok_class(**a ) __lowerCamelCase : Optional[Any] = add_prefix_space __lowerCamelCase : Optional[Any] = 'post_processor' __lowerCamelCase : Union[str, Any] = getattr(self.backend_tokenizer , a , a ) if tokenizer_component_instance: __lowerCamelCase : Any = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: __lowerCamelCase : Union[str, Any] = tuple(state['sep'] ) if "cls" in state: __lowerCamelCase : Union[str, Any] = tuple(state['cls'] ) __lowerCamelCase : List[Any] = False if state.get('add_prefix_space' , a ) != add_prefix_space: __lowerCamelCase : Optional[int] = add_prefix_space __lowerCamelCase : str = True if state.get('trim_offsets' , a ) != trim_offsets: __lowerCamelCase : Union[str, Any] = trim_offsets __lowerCamelCase : str = True if changes_to_apply: __lowerCamelCase : int = getattr(a , state.pop('type' ) ) __lowerCamelCase : Optional[Any] = component_class(**a ) setattr(self.backend_tokenizer , a , a ) @property def _snake_case ( self: List[Any] ): if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def _snake_case ( self: int , a: Optional[Any] ): __lowerCamelCase : Optional[Any] = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else value __lowerCamelCase : Any = value def _snake_case ( self: List[str] , *a: str , **a: int ): __lowerCamelCase : Dict = kwargs.get('is_split_into_words' , a ) assert self.add_prefix_space or not is_split_into_words, ( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*a , **a ) def _snake_case ( self: Dict , *a: Any , **a: int ): __lowerCamelCase : Optional[Any] = kwargs.get('is_split_into_words' , a ) assert self.add_prefix_space or not is_split_into_words, ( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' "to use it with pretokenized inputs." ) return super()._encode_plus(*a , **a ) def _snake_case ( self: List[Any] , a: str , a: Optional[str] = None ): __lowerCamelCase : Tuple = self._tokenizer.model.save(a , name=a ) return tuple(a ) def _snake_case ( self: Optional[Any] , a: Dict , a: Union[str, Any]=None ): __lowerCamelCase : Union[str, Any] = [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 _snake_case ( self: Dict , a: List[int] , a: Optional[List[int]] = None ): __lowerCamelCase : Any = [self.sep_token_id] __lowerCamelCase : str = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
669
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self: int ): torch.manual_seed(0 ) __lowerCamelCase : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Any = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _snake_case ( self: Dict ): torch.manual_seed(0 ) __lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.dummy_uncond_unet __lowerCamelCase : List[str] = DDIMScheduler() __lowerCamelCase : str = self.dummy_vq_model __lowerCamelCase : Optional[int] = LDMPipeline(unet=a , vqvae=a , scheduler=a ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[int] = torch.manual_seed(0 ) __lowerCamelCase : Any = ldm(generator=a , num_inference_steps=2 , output_type='numpy' ).images __lowerCamelCase : Tuple = torch.manual_seed(0 ) __lowerCamelCase : Dict = ldm(generator=a , num_inference_steps=2 , output_type='numpy' , return_dict=a )[0] __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[int] = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) __lowerCamelCase : str = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : int = ldm(generator=a , num_inference_steps=5 , output_type='numpy' ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __lowerCamelCase : List[Any] = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) __lowerCamelCase : Union[str, Any] = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
669
1
from dataclasses import dataclass from typing import Dict, Optional, Union import torch import torch.nn.functional as F from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .attention import BasicTransformerBlock from .attention_processor import AttentionProcessor, AttnProcessor from .embeddings import TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin @dataclass class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = 42 class A_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' @register_to_config def __init__( self: int , a: int = 32 , a: int = 64 , a: int = 20 , a: int = 768 , a: List[str]=77 , a: Optional[int]=4 , a: float = 0.0 , a: str = "silu" , a: Optional[str] = None , a: Optional[str] = None , a: Optional[str] = "linear" , a: Optional[str] = "prd" , a: Optional[int] = None , a: Optional[int] = None , a: Optional[int] = None , ): super().__init__() __lowerCamelCase : Tuple = num_attention_heads __lowerCamelCase : List[Any] = attention_head_dim __lowerCamelCase : Optional[int] = num_attention_heads * attention_head_dim __lowerCamelCase : List[Any] = additional_embeddings __lowerCamelCase : str = time_embed_dim or inner_dim __lowerCamelCase : Dict = embedding_proj_dim or embedding_dim __lowerCamelCase : Union[str, Any] = clip_embed_dim or embedding_dim __lowerCamelCase : str = Timesteps(a , a , 0 ) __lowerCamelCase : List[str] = TimestepEmbedding(a , a , out_dim=a , act_fn=a ) __lowerCamelCase : Dict = nn.Linear(a , a ) if embedding_proj_norm_type is None: __lowerCamelCase : List[str] = None elif embedding_proj_norm_type == "layer": __lowerCamelCase : Any = nn.LayerNorm(a ) else: raise ValueError(F'unsupported embedding_proj_norm_type: {embedding_proj_norm_type}' ) __lowerCamelCase : Any = nn.Linear(a , a ) if encoder_hid_proj_type is None: __lowerCamelCase : Optional[int] = None elif encoder_hid_proj_type == "linear": __lowerCamelCase : Optional[int] = nn.Linear(a , a ) else: raise ValueError(F'unsupported encoder_hid_proj_type: {encoder_hid_proj_type}' ) __lowerCamelCase : int = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , a ) ) if added_emb_type == "prd": __lowerCamelCase : Union[str, Any] = nn.Parameter(torch.zeros(1 , 1 , a ) ) elif added_emb_type is None: __lowerCamelCase : str = None else: raise ValueError( F'`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.' ) __lowerCamelCase : Optional[Any] = nn.ModuleList( [ BasicTransformerBlock( a , a , a , dropout=a , activation_fn='gelu' , attention_bias=a , ) for d in range(a ) ] ) if norm_in_type == "layer": __lowerCamelCase : int = nn.LayerNorm(a ) elif norm_in_type is None: __lowerCamelCase : List[Any] = None else: raise ValueError(F'Unsupported norm_in_type: {norm_in_type}.' ) __lowerCamelCase : Tuple = nn.LayerNorm(a ) __lowerCamelCase : Optional[int] = nn.Linear(a , a ) __lowerCamelCase : Tuple = torch.full( [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -1_0_0_0_0.0 ) causal_attention_mask.triu_(1 ) __lowerCamelCase : Optional[int] = causal_attention_mask[None, ...] self.register_buffer('causal_attention_mask' , a , persistent=a ) __lowerCamelCase : List[str] = nn.Parameter(torch.zeros(1 , a ) ) __lowerCamelCase : Union[str, Any] = nn.Parameter(torch.zeros(1 , a ) ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : int = {} def fn_recursive_add_processors(a: str , a: torch.nn.Module , a: Dict[str, AttentionProcessor] ): if hasattr(a , 'set_processor' ): __lowerCamelCase : Any = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F'{name}.{sub_name}' , a , a ) return processors for name, module in self.named_children(): fn_recursive_add_processors(a , a , a ) return processors def _snake_case ( self: Any , a: Union[AttentionProcessor, Dict[str, AttentionProcessor]] ): __lowerCamelCase : str = len(self.attn_processors.keys() ) if isinstance(a , a ) and len(a ) != count: raise ValueError( F'A dict of processors was passed, but the number of processors {len(a )} does not match the' F' number of attention layers: {count}. Please make sure to pass {count} processor classes.' ) def fn_recursive_attn_processor(a: str , a: torch.nn.Module , a: Optional[Any] ): if hasattr(a , 'set_processor' ): if not isinstance(a , a ): module.set_processor(a ) else: module.set_processor(processor.pop(F'{name}.processor' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'{name}.{sub_name}' , a , a ) for name, module in self.named_children(): fn_recursive_attn_processor(a , a , a ) def _snake_case ( self: List[str] ): self.set_attn_processor(AttnProcessor() ) def _snake_case ( self: Tuple , a: Any , a: Union[torch.Tensor, float, int] , a: torch.FloatTensor , a: Optional[torch.FloatTensor] = None , a: Optional[torch.BoolTensor] = None , a: bool = True , ): __lowerCamelCase : Tuple = hidden_states.shape[0] __lowerCamelCase : Dict = timestep if not torch.is_tensor(a ): __lowerCamelCase : Optional[int] = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device ) elif torch.is_tensor(a ) and len(timesteps.shape ) == 0: __lowerCamelCase : Any = timesteps[None].to(hidden_states.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML __lowerCamelCase : Union[str, Any] = timesteps * torch.ones(a , dtype=timesteps.dtype , device=timesteps.device ) __lowerCamelCase : Union[str, Any] = self.time_proj(a ) # timesteps does not contain any weights and will always return f32 tensors # but time_embedding might be fp16, so we need to cast here. __lowerCamelCase : Optional[int] = timesteps_projected.to(dtype=self.dtype ) __lowerCamelCase : int = self.time_embedding(a ) if self.embedding_proj_norm is not None: __lowerCamelCase : Dict = self.embedding_proj_norm(a ) __lowerCamelCase : Union[str, Any] = self.embedding_proj(a ) if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None: __lowerCamelCase : Optional[int] = self.encoder_hidden_states_proj(a ) elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None: raise ValueError('`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set' ) __lowerCamelCase : Optional[int] = self.proj_in(a ) __lowerCamelCase : Optional[int] = self.positional_embedding.to(hidden_states.dtype ) __lowerCamelCase : Dict = [] __lowerCamelCase : Dict = 0 if encoder_hidden_states is not None: additional_embeds.append(a ) additional_embeddings_len += encoder_hidden_states.shape[1] if len(proj_embeddings.shape ) == 2: __lowerCamelCase : Union[str, Any] = proj_embeddings[:, None, :] if len(hidden_states.shape ) == 2: __lowerCamelCase : List[str] = hidden_states[:, None, :] __lowerCamelCase : List[str] = additional_embeds + [ proj_embeddings, time_embeddings[:, None, :], hidden_states, ] if self.prd_embedding is not None: __lowerCamelCase : str = self.prd_embedding.to(hidden_states.dtype ).expand(a , -1 , -1 ) additional_embeds.append(a ) __lowerCamelCase : Union[str, Any] = torch.cat( a , dim=1 , ) # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens __lowerCamelCase : List[Any] = additional_embeddings_len + proj_embeddings.shape[1] + 1 if positional_embeddings.shape[1] < hidden_states.shape[1]: __lowerCamelCase : Optional[Any] = F.pad( a , ( 0, 0, additional_embeddings_len, self.prd_embedding.shape[1] if self.prd_embedding is not None else 0, ) , value=0.0 , ) __lowerCamelCase : int = hidden_states + positional_embeddings if attention_mask is not None: __lowerCamelCase : Any = (1 - attention_mask.to(hidden_states.dtype )) * -1_0_0_0_0.0 __lowerCamelCase : Dict = F.pad(a , (0, self.additional_embeddings) , value=0.0 ) __lowerCamelCase : Optional[int] = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype ) __lowerCamelCase : List[Any] = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0 ) if self.norm_in is not None: __lowerCamelCase : Union[str, Any] = self.norm_in(a ) for block in self.transformer_blocks: __lowerCamelCase : Optional[int] = block(a , attention_mask=a ) __lowerCamelCase : Any = self.norm_out(a ) if self.prd_embedding is not None: __lowerCamelCase : Optional[int] = hidden_states[:, -1] else: __lowerCamelCase : Optional[int] = hidden_states[:, additional_embeddings_len:] __lowerCamelCase : Optional[int] = self.proj_to_clip_embeddings(a ) if not return_dict: return (predicted_image_embedding,) return PriorTransformerOutput(predicted_image_embedding=a ) def _snake_case ( self: List[Any] , a: int ): __lowerCamelCase : Dict = (prior_latents * self.clip_std) + self.clip_mean return prior_latents
669
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = 'Usage of script: script_name <size_of_canvas:int>' lowercase_ = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = [[False for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] return canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): for j, _ in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = bool(random.getrandbits(1 ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = np.array(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(SCREAMING_SNAKE_CASE__ ): for c, pt in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = __judge_point( SCREAMING_SNAKE_CASE__ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __lowerCamelCase : Any = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __lowerCamelCase : list[list[bool]] = current_canvas.tolist() return return_canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __lowerCamelCase : Tuple = pt if pt: if alive < 2: __lowerCamelCase : Optional[Any] = False elif alive == 2 or alive == 3: __lowerCamelCase : Any = True elif alive > 3: __lowerCamelCase : Dict = False else: if alive == 3: __lowerCamelCase : Tuple = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ ,lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(['w', 'k']) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
669
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): return 10 - x * x def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # Bolzano theory in order to find if there is a root between a and b if equation(SCREAMING_SNAKE_CASE__ ) * equation(SCREAMING_SNAKE_CASE__ ) >= 0: raise ValueError('Wrong space!' ) __lowerCamelCase : str = a while (b - a) >= 0.01: # Find middle point __lowerCamelCase : int = (a + b) / 2 # Check if middle point is root if equation(SCREAMING_SNAKE_CASE__ ) == 0.0: break # Decide the side to repeat the steps if equation(SCREAMING_SNAKE_CASE__ ) * equation(SCREAMING_SNAKE_CASE__ ) < 0: __lowerCamelCase : str = c else: __lowerCamelCase : Optional[Any] = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
669
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 A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """char""" __snake_case = """bpe""" __snake_case = """wp""" lowercase_ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """char_tokenizer"""] __snake_case = """ViTImageProcessor""" __snake_case = """MgpstrTokenizer""" def __init__( self: int , a: Dict=None , a: Optional[int]=None , **a: List[str] ): __lowerCamelCase : Optional[int] = 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 , ) __lowerCamelCase : Optional[Any] = kwargs.pop('feature_extractor' ) __lowerCamelCase : 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`.' ) __lowerCamelCase : Any = tokenizer __lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('gpt2' ) __lowerCamelCase : int = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: Optional[int]=None , a: List[Any]=None , a: int=None , **a: str ): 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: __lowerCamelCase : Dict = self.image_processor(a , return_tensors=a , **a ) if text is not None: __lowerCamelCase : Dict = self.char_tokenizer(a , return_tensors=a , **a ) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : List[str] = encodings['input_ids'] return inputs def _snake_case ( self: List[str] , a: List[Any] ): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = sequences __lowerCamelCase : List[str] = char_preds.size(0 ) __lowerCamelCase , __lowerCamelCase : str = self._decode_helper(a , 'char' ) __lowerCamelCase , __lowerCamelCase : Optional[int] = self._decode_helper(a , 'bpe' ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = self._decode_helper(a , 'wp' ) __lowerCamelCase : Tuple = [] __lowerCamelCase : List[Any] = [] for i in range(a ): __lowerCamelCase : List[Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowerCamelCase : Optional[int] = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowerCamelCase : Any = scores.index(max(a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowerCamelCase : List[str] = {} __lowerCamelCase : Optional[int] = final_strs __lowerCamelCase : Dict = final_scores __lowerCamelCase : Dict = char_strs __lowerCamelCase : List[Any] = bpe_strs __lowerCamelCase : Tuple = wp_strs return out def _snake_case ( self: int , a: Optional[int] , a: Optional[Any] ): if format == DecodeType.CHARACTER: __lowerCamelCase : Optional[Any] = self.char_decode __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : List[str] = '[s]' elif format == DecodeType.BPE: __lowerCamelCase : Dict = self.bpe_decode __lowerCamelCase : List[str] = 2 __lowerCamelCase : Any = '#' elif format == DecodeType.WORDPIECE: __lowerCamelCase : List[str] = self.wp_decode __lowerCamelCase : int = 102 __lowerCamelCase : Dict = '[SEP]' else: raise ValueError(F'Format {format} is not supported.' ) __lowerCamelCase , __lowerCamelCase : int = [], [] __lowerCamelCase : Tuple = pred_logits.size(0 ) __lowerCamelCase : List[Any] = pred_logits.size(1 ) __lowerCamelCase , __lowerCamelCase : Dict = pred_logits.topk(1 , dim=-1 , largest=a , sorted=a ) __lowerCamelCase : List[str] = preds_index.view(-1 , a )[:, 1:] __lowerCamelCase : Dict = decoder(a ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = torch.nn.functional.softmax(a , dim=2 ).max(dim=2 ) __lowerCamelCase : List[str] = preds_max_prob[:, 1:] for index in range(a ): __lowerCamelCase : str = preds_str[index].find(a ) __lowerCamelCase : Tuple = preds_str[index][:pred_eos] __lowerCamelCase : Any = preds_index[index].cpu().tolist() __lowerCamelCase : Any = pred_index.index(a ) if eos_token in pred_index else -1 __lowerCamelCase : str = preds_max_prob[index][: pred_eos_index + 1] __lowerCamelCase : Union[str, Any] = 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 _snake_case ( self: Tuple , a: Optional[int] ): __lowerCamelCase : Dict = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(a )] return decode_strs def _snake_case ( self: Optional[int] , a: Tuple ): return self.bpe_tokenizer.batch_decode(a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : int = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(a )] return decode_strs
669
1
import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness lowercase_ = '\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n' lowercase_ = '\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n' lowercase_ = '\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric("code_eval")\n >>> test_cases = ["assert add(2,3)==5"]\n >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {\'pass@1\': 0.5, \'pass@2\': 1.0}\n' lowercase_ = '\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n' lowercase_ = 'The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A_ ( datasets.Metric ): '''simple docstring''' def _snake_case ( self: Union[str, Any] ): return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('string' ) ), 'references': datasets.Value('string' ), } ) , homepage='https://github.com/openai/human-eval' , codebase_urls=['https://github.com/openai/human-eval'] , reference_urls=['https://github.com/openai/human-eval'] , license=_LICENSE , ) def _snake_case ( self: str , a: str , a: Union[str, Any] , a: List[str]=[1, 10, 100] , a: Any=4 , a: Union[str, Any]=3.0 ): if os.getenv('HF_ALLOW_CODE_EVAL' , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError('This metric is currently not supported on Windows.' ) with ThreadPoolExecutor(max_workers=a ) as executor: __lowerCamelCase : Dict = [] __lowerCamelCase : Union[str, Any] = Counter() __lowerCamelCase : Dict = 0 __lowerCamelCase : Optional[Any] = defaultdict(a ) for task_id, (candidates, test_case) in enumerate(zip(a , a ) ): for candidate in candidates: __lowerCamelCase : Tuple = candidate + '\n' + test_case __lowerCamelCase : List[str] = (test_program, timeout, task_id, completion_id[task_id]) __lowerCamelCase : str = executor.submit(a , *a ) futures.append(a ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(a ): __lowerCamelCase : Any = future.result() results[result["task_id"]].append((result['completion_id'], result) ) __lowerCamelCase , __lowerCamelCase : Optional[int] = [], [] for result in results.values(): result.sort() __lowerCamelCase : int = [r[1]['passed'] for r in result] total.append(len(a ) ) correct.append(sum(a ) ) __lowerCamelCase : List[str] = np.array(a ) __lowerCamelCase : Optional[Any] = np.array(a ) __lowerCamelCase : Any = k __lowerCamelCase : Dict = {F'pass@{k}': estimate_pass_at_k(a , a , a ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): def estimator(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = itertools.repeat(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) else: assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = iter(SCREAMING_SNAKE_CASE__ ) return np.array([estimator(int(SCREAMING_SNAKE_CASE__ ) , int(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) for n, c in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )] )
669
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : Optional[int] = TOKENIZER_CLASSES else: __lowerCamelCase : Union[str, Any] = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE__ , tokenizer_name + 'Fast' )} logger.info(f'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : int = TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Optional[int] = True if checkpoint_name is None: __lowerCamelCase : List[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : Optional[Any] = [checkpoint_name] logger.info(f'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(f'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ ) # Save fast tokenizer logger.info(f'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Tuple = checkpoint.split('/' ) __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif add_prefix: __lowerCamelCase : Any = checkpoint __lowerCamelCase : Dict = dump_path else: __lowerCamelCase : List[str] = None __lowerCamelCase : Optional[int] = dump_path logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : List[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : int = file_path.split(SCREAMING_SNAKE_CASE__ )[-1][0] if next_char == "/": __lowerCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = None logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Dict = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ , filename_prefix=SCREAMING_SNAKE_CASE__ ) logger.info(f'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('tokenizer.json' ): os.remove(SCREAMING_SNAKE_CASE__ ) logger.info(f'=> removing {file_name}' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) lowercase_ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
669
1
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder lowercase_ = '__DUMMY_TRANSFORMERS_USER__' lowercase_ = 'Dummy User' lowercase_ = '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' lowercase_ = 'https://hub-ci.huggingface.co' lowercase_ = CI_HUB_ENDPOINT + '/datasets/{repo_id}/resolve/{revision}/{path}' lowercase_ = CI_HUB_ENDPOINT + '/{repo_id}/resolve/{revision}/{filename}' lowercase_ = Path('~/.huggingface/hub_ci_token').expanduser() @pytest.fixture def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): monkeypatch.setattr( 'huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE' , SCREAMING_SNAKE_CASE__ ) @pytest.fixture def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): monkeypatch.setattr('datasets.config.HF_ENDPOINT' , SCREAMING_SNAKE_CASE__ ) monkeypatch.setattr('datasets.config.HUB_DATASETS_URL' , SCREAMING_SNAKE_CASE__ ) @pytest.fixture def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): monkeypatch.setattr('huggingface_hub.hf_api.HfFolder.path_token' , SCREAMING_SNAKE_CASE__ ) @pytest.fixture def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) yield HfFolder.delete_token() @pytest.fixture(scope='session' ) def UpperCamelCase__ ( ): return HfApi(endpoint=SCREAMING_SNAKE_CASE__ ) @pytest.fixture(scope='session' ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = HfFolder.get_token() HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) @pytest.fixture def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): def _cleanup_repo(SCREAMING_SNAKE_CASE__ ): hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) return _cleanup_repo @pytest.fixture def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): @contextmanager def _temporary_repo(SCREAMING_SNAKE_CASE__ ): try: yield repo_id finally: cleanup_repo(SCREAMING_SNAKE_CASE__ ) return _temporary_repo @pytest.fixture(scope='session' ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = f'repo_txt_data-{int(time.time() * 10e3 )}' __lowerCamelCase : str = f'{CI_HUB_USER}/{repo_name}' hf_api.create_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='dataset' , private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__ , path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ) , path_in_repo='data/text_data.txt' , repo_id=SCREAMING_SNAKE_CASE__ , repo_type='dataset' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope='session' ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = f'repo_zipped_txt_data-{int(time.time() * 10e3 )}' __lowerCamelCase : str = f'{CI_HUB_USER}/{repo_name}' hf_api.create_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='dataset' , private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__ , path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ) , path_in_repo='data.zip' , repo_id=SCREAMING_SNAKE_CASE__ , repo_type='dataset' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope='session' ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = f'repo_zipped_img_data-{int(time.time() * 10e3 )}' __lowerCamelCase : Optional[int] = f'{CI_HUB_USER}/{repo_name}' hf_api.create_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='dataset' , private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__ , path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ) , path_in_repo='data.zip' , repo_id=SCREAMING_SNAKE_CASE__ , repo_type='dataset' , ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__ , token=SCREAMING_SNAKE_CASE__ , repo_type='dataset' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return hf_private_dataset_repo_zipped_img_data_
669
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: List[str] ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : List[str] = PegasusTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[Any] ): return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def _snake_case ( self: Tuple , **a: List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[Any] , a: int ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Dict = '</s>' __lowerCamelCase : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a ) , 1103 ) def _snake_case ( self: Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) __lowerCamelCase : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: int ): __lowerCamelCase : Union[str, Any] = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowerCamelCase : Tuple = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' __lowerCamelCase : Optional[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : Optional[Any] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 __lowerCamelCase : int = 'To ensure a smooth flow of bank resolutions.' __lowerCamelCase : Union[str, Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : List[str] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _snake_case ( self: str ): __lowerCamelCase : List[str] = ['This is going to be way too long.' * 150, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : Union[str, Any] = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : List[str] = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. @slow def _snake_case ( self: List[str] ): # fmt: off __lowerCamelCase : Tuple = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: str ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : str = PegasusTokenizer(a , offset=0 , mask_token_sent=a , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[str] ): return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def _snake_case ( self: Union[str, Any] , **a: Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[str] , a: Any ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) __lowerCamelCase : int = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) @require_torch def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = ['This is going to be way too long.' * 1000, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : str = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : Any = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. def _snake_case ( self: Any ): __lowerCamelCase : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) __lowerCamelCase : Dict = self._large_tokenizer(a ).input_ids self.assertListEqual( a , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
669
1
class A_ : '''simple docstring''' def __init__( self: Tuple ): __lowerCamelCase : List[str] = {} def _snake_case ( self: int ): print(self.vertex ) for i in self.vertex: print(a , ' -> ' , ' -> '.join([str(a ) for j in self.vertex[i]] ) ) def _snake_case ( self: Union[str, Any] , a: int , a: int ): # check if vertex is already present, if from_vertex in self.vertex: self.vertex[from_vertex].append(a ) else: # else make a new vertex __lowerCamelCase : str = [to_vertex] def _snake_case ( self: int ): # visited array for storing already visited nodes __lowerCamelCase : Optional[Any] = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(a , a ) def _snake_case ( self: str , a: int , a: list ): # mark start vertex as visited __lowerCamelCase : Optional[Any] = True print(a , end=' ' ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(a , a ) if __name__ == "__main__": lowercase_ = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print('DFS:') g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if density <= 0: raise ValueError('Impossible fluid density' ) if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
669
1
from __future__ import annotations import math import random from collections.abc import Collection from typing import overload class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Collection[float] | None = None ): if components is None: __lowerCamelCase : Optional[int] = [] __lowerCamelCase : Optional[int] = list(a ) def __len__( self: Optional[int] ): return len(self.__components ) def __str__( self: List[str] ): return "(" + ",".join(map(a , self.__components ) ) + ")" def __add__( self: Union[str, Any] , a: Vector ): __lowerCamelCase : Tuple = len(self ) if size == len(a ): __lowerCamelCase : Any = [self.__components[i] + other.component(a ) for i in range(a )] return Vector(a ) else: raise Exception('must have the same size' ) def __sub__( self: Dict , a: Vector ): __lowerCamelCase : Dict = len(self ) if size == len(a ): __lowerCamelCase : Tuple = [self.__components[i] - other.component(a ) for i in range(a )] return Vector(a ) else: # error case raise Exception('must have the same size' ) @overload def __mul__( self: Any , a: float ): ... @overload def __mul__( self: Tuple , a: Vector ): ... def __mul__( self: List[str] , a: float | Vector ): if isinstance(a , (float, int) ): __lowerCamelCase : int = [c * other for c in self.__components] return Vector(a ) elif isinstance(a , a ) and len(self ) == len(a ): __lowerCamelCase : Dict = len(self ) __lowerCamelCase : List[str] = [self.__components[i] * other.component(a ) for i in range(a )] return sum(a ) else: # error case raise Exception('invalid operand!' ) def _snake_case ( self: Optional[Any] ): return Vector(self.__components ) def _snake_case ( self: Tuple , a: int ): if isinstance(a , a ) and -len(self.__components ) <= i < len(self.__components ): return self.__components[i] else: raise Exception('index out of range' ) def _snake_case ( self: Optional[Any] , a: int , a: float ): assert -len(self.__components ) <= pos < len(self.__components ) __lowerCamelCase : int = value def _snake_case ( self: Optional[int] ): if len(self.__components ) == 0: raise Exception('Vector is empty' ) __lowerCamelCase : Optional[Any] = [c**2 for c in self.__components] return math.sqrt(sum(a ) ) def _snake_case ( self: Union[str, Any] , a: Vector , a: bool = False ): __lowerCamelCase : Tuple = self * other __lowerCamelCase : Any = self.euclidean_length() * other.euclidean_length() if deg: return math.degrees(math.acos(num / den ) ) else: return math.acos(num / den ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return Vector([0] * dimension ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )) __lowerCamelCase : Any = [0] * dimension __lowerCamelCase : Optional[int] = 1 return Vector(SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): assert ( isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) )) ) return x * scalar + y def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): random.seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] return Vector(SCREAMING_SNAKE_CASE__ ) class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: list[list[float]] , a: int , a: int ): __lowerCamelCase : List[Any] = matrix __lowerCamelCase : Optional[int] = w __lowerCamelCase : List[Any] = h def __str__( self: Optional[int] ): __lowerCamelCase : List[Any] = '' for i in range(self.__height ): ans += "|" for j in range(self.__width ): if j < self.__width - 1: ans += str(self.__matrix[i][j] ) + "," else: ans += str(self.__matrix[i][j] ) + "|\n" return ans def __add__( self: List[Any] , a: Matrix ): if self.__width == other.width() and self.__height == other.height(): __lowerCamelCase : Tuple = [] for i in range(self.__height ): __lowerCamelCase : Optional[Any] = [ self.__matrix[i][j] + other.component(a , a ) for j in range(self.__width ) ] matrix.append(a ) return Matrix(a , self.__width , self.__height ) else: raise Exception('matrix must have the same dimension!' ) def __sub__( self: Optional[int] , a: Matrix ): if self.__width == other.width() and self.__height == other.height(): __lowerCamelCase : Any = [] for i in range(self.__height ): __lowerCamelCase : Optional[Any] = [ self.__matrix[i][j] - other.component(a , a ) for j in range(self.__width ) ] matrix.append(a ) return Matrix(a , self.__width , self.__height ) else: raise Exception('matrices must have the same dimension!' ) @overload def __mul__( self: Any , a: float ): ... @overload def __mul__( self: Tuple , a: Vector ): ... def __mul__( self: int , a: float | Vector ): if isinstance(a , a ): # matrix-vector if len(a ) == self.__width: __lowerCamelCase : Optional[int] = zero_vector(self.__height ) for i in range(self.__height ): __lowerCamelCase : Dict = [ self.__matrix[i][j] * other.component(a ) for j in range(self.__width ) ] ans.change_component(a , sum(a ) ) return ans else: raise Exception( 'vector must have the same size as the ' 'number of columns of the matrix!' ) elif isinstance(a , (int, float) ): # matrix-scalar __lowerCamelCase : Any = [ [self.__matrix[i][j] * other for j in range(self.__width )] for i in range(self.__height ) ] return Matrix(a , self.__width , self.__height ) return None def _snake_case ( self: Tuple ): return self.__height def _snake_case ( self: Optional[int] ): return self.__width def _snake_case ( self: Any , a: int , a: int ): if 0 <= x < self.__height and 0 <= y < self.__width: return self.__matrix[x][y] else: raise Exception('change_component: indices out of bounds' ) def _snake_case ( self: Any , a: int , a: int , a: float ): if 0 <= x < self.__height and 0 <= y < self.__width: __lowerCamelCase : Union[str, Any] = value else: raise Exception('change_component: indices out of bounds' ) def _snake_case ( self: Tuple , a: int , a: int ): if self.__height != self.__width: raise Exception('Matrix is not square' ) __lowerCamelCase : int = self.__matrix[:x] + self.__matrix[x + 1 :] for i in range(len(a ) ): __lowerCamelCase : List[str] = minor[i][:y] + minor[i][y + 1 :] return Matrix(a , self.__width - 1 , self.__height - 1 ).determinant() def _snake_case ( self: str , a: int , a: int ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if 0 <= x < self.__height and 0 <= y < self.__width: return (-1) ** (x + y) * self.minor(a , a ) else: raise Exception('Indices out of bounds' ) def _snake_case ( self: List[str] ): if self.__height != self.__width: raise Exception('Matrix is not square' ) if self.__height < 1: raise Exception('Matrix has no element' ) elif self.__height == 1: return self.__matrix[0][0] elif self.__height == 2: return ( self.__matrix[0][0] * self.__matrix[1][1] - self.__matrix[0][1] * self.__matrix[1][0] ) else: __lowerCamelCase : int = [ self.__matrix[0][y] * self.cofactor(0 , a ) for y in range(self.__width ) ] return sum(a ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : list[list[float]] = [[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): random.seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : list[list[float]] = [ [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ ) ] return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = 1 __lowerCamelCase : str = 2 while i * i <= n: __lowerCamelCase : int = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def UpperCamelCase__ ( ): __lowerCamelCase : str = 1 __lowerCamelCase : List[str] = 1 while True: i += 1 t_num += i if count_divisors(SCREAMING_SNAKE_CASE__ ) > 500: break return t_num if __name__ == "__main__": print(solution())
669
1
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore lowercase_ = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" lowercase_ = [file for file in filepaths if file != file.lower()] if upper_files: print(F"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') lowercase_ = [file for file in filepaths if ' ' in file] if space_files: print(F"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') lowercase_ = [file for file in filepaths if '-' in file] if hyphen_files: print(F"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') lowercase_ = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') lowercase_ = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
669
import numpy as np class A_ : '''simple docstring''' def __init__( self: Optional[int] ): __lowerCamelCase : int = (0, 0) __lowerCamelCase : List[str] = None __lowerCamelCase : int = 0 __lowerCamelCase : int = 0 __lowerCamelCase : Union[str, Any] = 0 def __eq__( self: Optional[int] , a: List[Any] ): return self.position == cell.position def _snake_case ( self: Any ): print(self.position ) class A_ : '''simple docstring''' def __init__( self: str , a: List[str]=(5, 5) ): __lowerCamelCase : Optional[Any] = np.zeros(a ) __lowerCamelCase : List[str] = world_size[0] __lowerCamelCase : Optional[int] = world_size[1] def _snake_case ( self: List[Any] ): print(self.w ) def _snake_case ( self: Optional[int] , a: str ): __lowerCamelCase : Tuple = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __lowerCamelCase : Optional[int] = cell.position[0] __lowerCamelCase : List[str] = cell.position[1] __lowerCamelCase : Dict = [] for n in neughbour_cord: __lowerCamelCase : Dict = current_x + n[0] __lowerCamelCase : Optional[Any] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __lowerCamelCase : Optional[Any] = Cell() __lowerCamelCase : Any = (x, y) __lowerCamelCase : Dict = cell neighbours.append(a ) return neighbours def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = [] __lowerCamelCase : int = [] _open.append(SCREAMING_SNAKE_CASE__ ) while _open: __lowerCamelCase : Union[str, Any] = np.argmin([n.f for n in _open] ) __lowerCamelCase : int = _open[min_f] _closed.append(_open.pop(SCREAMING_SNAKE_CASE__ ) ) if current == goal: break for n in world.get_neigbours(SCREAMING_SNAKE_CASE__ ): for c in _closed: if c == n: continue __lowerCamelCase : Optional[int] = current.g + 1 __lowerCamelCase , __lowerCamelCase : int = n.position __lowerCamelCase , __lowerCamelCase : Tuple = goal.position __lowerCamelCase : Dict = (ya - ya) ** 2 + (xa - xa) ** 2 __lowerCamelCase : str = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [] while current.parent is not None: path.append(current.position ) __lowerCamelCase : int = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowercase_ = Gridworld() # Start position and goal lowercase_ = Cell() lowercase_ = (0, 0) lowercase_ = Cell() lowercase_ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowercase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowercase_ = 1 print(world.w)
669
1
import json import os import re import unittest from transformers import CodeGenTokenizer, CodeGenTokenizerFast from transformers.models.codegen.tokenization_codegen import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = CodeGenTokenizer __snake_case = CodeGenTokenizerFast __snake_case = True __snake_case = {"""add_prefix_space""": True} __snake_case = False def _snake_case ( self: str ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __lowerCamelCase : Dict = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', '<|endoftext|>', ] __lowerCamelCase : Tuple = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : Tuple = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] __lowerCamelCase : List[str] = {'unk_token': '<unk>'} __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : Optional[Any] = 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(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: Dict , **a: Tuple ): kwargs.update(self.special_tokens_map ) return CodeGenTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Dict , **a: int ): kwargs.update(self.special_tokens_map ) return CodeGenTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: int , a: Optional[int] ): __lowerCamelCase : int = 'lower newer' __lowerCamelCase : List[str] = 'lower newer' return input_text, output_text def _snake_case ( self: Tuple ): __lowerCamelCase : Union[str, Any] = CodeGenTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase : List[str] = 'lower newer' __lowerCamelCase : str = ['\u0120low', 'er', '\u0120', 'n', 'e', 'w', 'er'] __lowerCamelCase : Tuple = tokenizer.tokenize(a , add_prefix_space=a ) self.assertListEqual(a , a ) __lowerCamelCase : Tuple = tokens + [tokenizer.unk_token] __lowerCamelCase : Any = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) def _snake_case ( self: Any ): if not self.test_rust_tokenizer: return __lowerCamelCase : int = self.get_tokenizer() __lowerCamelCase : str = self.get_rust_tokenizer(add_prefix_space=a ) __lowerCamelCase : str = 'lower newer' # Testing tokenization __lowerCamelCase : Tuple = tokenizer.tokenize(a , add_prefix_space=a ) __lowerCamelCase : Any = rust_tokenizer.tokenize(a ) self.assertListEqual(a , a ) # Testing conversion to ids without special tokens __lowerCamelCase : Dict = tokenizer.encode(a , add_special_tokens=a , add_prefix_space=a ) __lowerCamelCase : List[str] = rust_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) # Testing conversion to ids with special tokens __lowerCamelCase : List[Any] = self.get_rust_tokenizer(add_prefix_space=a ) __lowerCamelCase : Optional[Any] = tokenizer.encode(a , add_prefix_space=a ) __lowerCamelCase : Optional[int] = rust_tokenizer.encode(a ) self.assertListEqual(a , a ) # Testing the unknown token __lowerCamelCase : Union[str, Any] = tokens + [rust_tokenizer.unk_token] __lowerCamelCase : List[str] = [14, 15, 10, 9, 3, 2, 15, 19] self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(a ) , a ) def _snake_case ( self: List[Any] , *a: Optional[int] , **a: int ): # It's very difficult to mix/test pretokenization with byte-level # And get both CodeGen and Roberta to work at the same time (mostly an issue of adding a space before the string) pass def _snake_case ( self: Optional[Any] , a: List[str]=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[str] = self.rust_tokenizer_class.from_pretrained(a , **a ) # Simple input __lowerCamelCase : List[Any] = 'This is a simple input' __lowerCamelCase : List[Any] = ['This is a simple input 1', 'This is a simple input 2'] __lowerCamelCase : Any = ('This is a simple input', 'This is a pair') __lowerCamelCase : Optional[Any] = [ ('This is a simple input 1', 'This is a simple input 2'), ('This is a simple pair 1', 'This is a simple pair 2'), ] # Simple input tests self.assertRaises(a , tokenizer_r.encode , a , max_length=a , padding='max_length' ) # Simple input self.assertRaises(a , tokenizer_r.encode_plus , a , max_length=a , padding='max_length' ) # Simple input self.assertRaises( a , tokenizer_r.batch_encode_plus , a , max_length=a , padding='max_length' , ) # Pair input self.assertRaises(a , tokenizer_r.encode , a , max_length=a , padding='max_length' ) # Pair input self.assertRaises(a , tokenizer_r.encode_plus , a , max_length=a , padding='max_length' ) # Pair input self.assertRaises( a , tokenizer_r.batch_encode_plus , a , max_length=a , padding='max_length' , ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : List[Any] = CodeGenTokenizer.from_pretrained(self.tmpdirname , pad_token='<pad>' ) # Simple input __lowerCamelCase : int = 'This is a simple input' __lowerCamelCase : Any = ['This is a simple input looooooooong', 'This is a simple input'] __lowerCamelCase : Optional[Any] = ('This is a simple input', 'This is a pair') __lowerCamelCase : Union[str, Any] = [ ('This is a simple input loooooong', 'This is a simple input'), ('This is a simple pair loooooong', 'This is a simple pair'), ] __lowerCamelCase : Dict = tokenizer.pad_token_id __lowerCamelCase : str = tokenizer(a , padding='max_length' , max_length=30 , return_tensors='np' ) __lowerCamelCase : Optional[int] = tokenizer(a , padding=a , truncate=a , return_tensors='np' ) __lowerCamelCase : List[str] = tokenizer(*a , padding='max_length' , max_length=60 , return_tensors='np' ) __lowerCamelCase : int = tokenizer(a , padding=a , truncate=a , return_tensors='np' ) # s # test single string max_length padding self.assertEqual(out_s['input_ids'].shape[-1] , 30 ) self.assertTrue(pad_token_id in out_s['input_ids'] ) self.assertTrue(0 in out_s['attention_mask'] ) # s2 # test automatic padding self.assertEqual(out_sa['input_ids'].shape[-1] , 33 ) # long slice doesn't have padding self.assertFalse(pad_token_id in out_sa['input_ids'][0] ) self.assertFalse(0 in out_sa['attention_mask'][0] ) # short slice does have padding self.assertTrue(pad_token_id in out_sa['input_ids'][1] ) self.assertTrue(0 in out_sa['attention_mask'][1] ) # p # test single pair max_length padding self.assertEqual(out_p['input_ids'].shape[-1] , 60 ) self.assertTrue(pad_token_id in out_p['input_ids'] ) self.assertTrue(0 in out_p['attention_mask'] ) # p2 # test automatic padding pair self.assertEqual(out_pa['input_ids'].shape[-1] , 52 ) # long slice pair doesn't have padding self.assertFalse(pad_token_id in out_pa['input_ids'][0] ) self.assertFalse(0 in out_pa['attention_mask'][0] ) # short slice pair does have padding self.assertTrue(pad_token_id in out_pa['input_ids'][1] ) self.assertTrue(0 in out_pa['attention_mask'][1] ) def _snake_case ( self: str ): __lowerCamelCase : int = '$$$' __lowerCamelCase : int = CodeGenTokenizer.from_pretrained(self.tmpdirname , bos_token=a , add_bos_token=a ) __lowerCamelCase : str = 'This is a simple input' __lowerCamelCase : Dict = ['This is a simple input 1', 'This is a simple input 2'] __lowerCamelCase : List[Any] = tokenizer.bos_token_id __lowerCamelCase : int = tokenizer(a ) __lowerCamelCase : Tuple = tokenizer(a ) self.assertEqual(out_s.input_ids[0] , a ) self.assertTrue(all(o[0] == bos_token_id for o in out_sa.input_ids ) ) __lowerCamelCase : Optional[Any] = tokenizer.decode(out_s.input_ids ) __lowerCamelCase : Tuple = tokenizer.batch_decode(out_sa.input_ids ) self.assertEqual(decode_s.split()[0] , a ) self.assertTrue(all(d.split()[0] == bos_token for d in decode_sa ) ) @slow def _snake_case ( self: Tuple ): __lowerCamelCase : Dict = CodeGenTokenizer.from_pretrained('Salesforce/codegen-350M-mono' ) __lowerCamelCase : Any = '\nif len_a > len_b:\n result = a\nelse:\n result = b\n\n\n\n#' __lowerCamelCase : Dict = '\nif len_a > len_b: result = a\nelse: result = b' __lowerCamelCase : List[str] = tokenizer.encode(a ) __lowerCamelCase : Tuple = ['^#', re.escape('<|endoftext|>' ), '^\'\'\'', '^"""', '\n\n\n'] __lowerCamelCase : List[Any] = tokenizer.decode(a , truncate_before_pattern=a ) self.assertEqual(a , a ) def _snake_case ( self: int ): pass
669
import math from datetime import datetime, timedelta def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = year % 19 __lowerCamelCase : int = year % 4 __lowerCamelCase : Any = year % 7 __lowerCamelCase : Dict = math.floor(year / 100 ) __lowerCamelCase : str = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCamelCase : Optional[int] = leap_day_inhibits / 4 __lowerCamelCase : str = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCamelCase : Optional[Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCamelCase : Optional[int] = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __lowerCamelCase : Tuple = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 18 ) else: return datetime(SCREAMING_SNAKE_CASE__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): lowercase_ = 'will be' if year > datetime.now().year else 'was' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
669
1
from __future__ import annotations def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : list[list[int]] = [] __lowerCamelCase : list[int] = [] __lowerCamelCase : int = 0 __lowerCamelCase : Optional[int] = sum(SCREAMING_SNAKE_CASE__ ) create_state_space_tree(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return result def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ): if sum(SCREAMING_SNAKE_CASE__ ) > max_sum or (remaining_nums_sum + sum(SCREAMING_SNAKE_CASE__ )) < max_sum: return if sum(SCREAMING_SNAKE_CASE__ ) == max_sum: result.append(SCREAMING_SNAKE_CASE__ ) return for index in range(SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ): create_state_space_tree( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index + 1 , [*path, nums[index]] , SCREAMING_SNAKE_CASE__ , remaining_nums_sum - nums[index] , ) lowercase_ = [3, 3_4, 4, 1_2, 5, 2] lowercase_ = 9 lowercase_ = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
669
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch 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_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' __snake_case = 1 @register_to_config def __init__( self: str , a: str=2000 , a: List[str]=0.1 , a: Any=20 , a: Dict=1e-3 ): __lowerCamelCase : Dict = None __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = None def _snake_case ( self: int , a: str , a: Union[str, torch.device] = None ): __lowerCamelCase : int = torch.linspace(1 , self.config.sampling_eps , a , device=a ) def _snake_case ( self: List[Any] , a: Union[str, Any] , a: Tuple , a: Optional[Any] , a: Dict=None ): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __lowerCamelCase : Tuple = ( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __lowerCamelCase : Optional[int] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __lowerCamelCase : Optional[Any] = std.flatten() while len(std.shape ) < len(score.shape ): __lowerCamelCase : List[str] = std.unsqueeze(-1 ) __lowerCamelCase : Any = -score / std # compute __lowerCamelCase : List[Any] = -1.0 / len(self.timesteps ) __lowerCamelCase : Any = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __lowerCamelCase : Dict = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __lowerCamelCase : int = beta_t.unsqueeze(-1 ) __lowerCamelCase : Any = -0.5 * beta_t * x __lowerCamelCase : List[Any] = torch.sqrt(a ) __lowerCamelCase : Tuple = drift - diffusion**2 * score __lowerCamelCase : str = x + drift * dt # add noise __lowerCamelCase : Any = randn_tensor(x.shape , layout=x.layout , generator=a , device=x.device , dtype=x.dtype ) __lowerCamelCase : Any = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self: Optional[int] ): return self.config.num_train_timesteps
669
1
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") lowercase_ = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find('meta', {'property': 'og:image'})['content'] lowercase_ = requests.get(image_url).content lowercase_ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__ ) if n_element < 1: __lowerCamelCase : str = ValueError('a should be a positive number' ) raise my_error __lowerCamelCase : Tuple = [1] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = (0, 0, 0) __lowerCamelCase : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowercase_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') lowercase_ = hamming(int(n)) print('-----------------------------------------------------') print(F"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
669
1
import collections import os import re from pathlib import Path lowercase_ = 'src/transformers' # Matches is_xxx_available() lowercase_ = re.compile(R'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} lowercase_ = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] lowercase_ = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available lowercase_ = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") lowercase_ = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] lowercase_ = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", lowercase_ = re.compile(R'^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], lowercase_ = re.compile(R'^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo lowercase_ = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: lowercase_ = re.compile(R'^\s*try:') # Catches a line with else: lowercase_ = re.compile(R'^\s*else:') def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): if _re_test_backend.search(SCREAMING_SNAKE_CASE__ ) is None: return None __lowerCamelCase : Tuple = [b[0] for b in _re_backend.findall(SCREAMING_SNAKE_CASE__ )] backends.sort() return "_and_".join(SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): with open(SCREAMING_SNAKE_CASE__ , 'r' , encoding='utf-8' , newline='\n' ) as f: __lowerCamelCase : Optional[int] = f.readlines() __lowerCamelCase : str = 0 while line_index < len(SCREAMING_SNAKE_CASE__ ) and not lines[line_index].startswith('_import_structure = {' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(SCREAMING_SNAKE_CASE__ ): return None # First grab the objects without a specific backend in _import_structure __lowerCamelCase : Optional[Any] = [] while not lines[line_index].startswith('if TYPE_CHECKING' ) and find_backend(lines[line_index] ) is None: __lowerCamelCase : List[Any] = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = _re_one_line_import_struct.search(SCREAMING_SNAKE_CASE__ ).groups()[0] __lowerCamelCase : List[str] = re.findall(r'\[([^\]]+)\]' , SCREAMING_SNAKE_CASE__ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(', ' )] ) line_index += 1 continue __lowerCamelCase : Optional[Any] = _re_import_struct_key_value.search(SCREAMING_SNAKE_CASE__ ) if single_line_import_search is not None: __lowerCamelCase : Optional[int] = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(', ' ) if len(SCREAMING_SNAKE_CASE__ ) > 0] objects.extend(SCREAMING_SNAKE_CASE__ ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) line_index += 1 __lowerCamelCase : Any = {'none': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('if TYPE_CHECKING' ): # If the line is an if not is_backend_available, we grab all objects associated. __lowerCamelCase : List[Any] = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __lowerCamelCase : str = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __lowerCamelCase : Optional[int] = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 4 ): __lowerCamelCase : str = lines[line_index] if _re_import_struct_add_one.search(SCREAMING_SNAKE_CASE__ ) is not None: objects.append(_re_import_struct_add_one.search(SCREAMING_SNAKE_CASE__ ).groups()[0] ) elif _re_import_struct_add_many.search(SCREAMING_SNAKE_CASE__ ) is not None: __lowerCamelCase : Union[str, Any] = _re_import_struct_add_many.search(SCREAMING_SNAKE_CASE__ ).groups()[0].split(', ' ) __lowerCamelCase : Union[str, Any] = [obj[1:-1] for obj in imports if len(SCREAMING_SNAKE_CASE__ ) > 0] objects.extend(SCREAMING_SNAKE_CASE__ ) elif _re_between_brackets.search(SCREAMING_SNAKE_CASE__ ) is not None: __lowerCamelCase : Optional[int] = _re_between_brackets.search(SCREAMING_SNAKE_CASE__ ).groups()[0].split(', ' ) __lowerCamelCase : Optional[int] = [obj[1:-1] for obj in imports if len(SCREAMING_SNAKE_CASE__ ) > 0] objects.extend(SCREAMING_SNAKE_CASE__ ) elif _re_quote_object.search(SCREAMING_SNAKE_CASE__ ) is not None: objects.append(_re_quote_object.search(SCREAMING_SNAKE_CASE__ ).groups()[0] ) elif line.startswith(' ' * 8 + '"' ): objects.append(line[9:-3] ) elif line.startswith(' ' * 12 + '"' ): objects.append(line[13:-3] ) line_index += 1 __lowerCamelCase : int = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend __lowerCamelCase : Any = [] while ( line_index < len(SCREAMING_SNAKE_CASE__ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('else' ) ): __lowerCamelCase : Optional[Any] = lines[line_index] __lowerCamelCase : List[Any] = _re_import.search(SCREAMING_SNAKE_CASE__ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 8 ): objects.append(line[8:-2] ) line_index += 1 __lowerCamelCase : int = {'none': objects} # Let's continue with backend-specific objects while line_index < len(SCREAMING_SNAKE_CASE__ ): # If the line is an if is_backend_available, we grab all objects associated. __lowerCamelCase : Optional[Any] = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: __lowerCamelCase : str = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 __lowerCamelCase : Union[str, Any] = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(' ' * 8 ): __lowerCamelCase : Optional[Any] = lines[line_index] __lowerCamelCase : Optional[int] = _re_import.search(SCREAMING_SNAKE_CASE__ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(', ' ) ) elif line.startswith(' ' * 12 ): objects.append(line[12:-2] ) line_index += 1 __lowerCamelCase : Tuple = objects else: line_index += 1 return import_dict_objects, type_hint_objects def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): def find_duplicates(SCREAMING_SNAKE_CASE__ ): return [k for k, v in collections.Counter(SCREAMING_SNAKE_CASE__ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] __lowerCamelCase : Optional[Any] = [] for key in import_dict_objects.keys(): __lowerCamelCase : Tuple = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f'Duplicate _import_structure definitions for: {duplicate_imports}' ) __lowerCamelCase : List[str] = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f'Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): __lowerCamelCase : Optional[Any] = 'base imports' if key == 'none' else f'{key} backend' errors.append(f'Differences for {name}:' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f' {a} in TYPE_HINT but not in _import_structure.' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f' {a} in _import_structure but not in TYPE_HINT.' ) return errors def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = [] for root, _, files in os.walk(SCREAMING_SNAKE_CASE__ ): if "__init__.py" in files: __lowerCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , '__init__.py' ) __lowerCamelCase : str = parse_init(SCREAMING_SNAKE_CASE__ ) if objects is not None: __lowerCamelCase : Optional[Any] = analyze_results(*SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: __lowerCamelCase : Tuple = f'Problem in {fname}, both halves do not define the same objects.\n{errors[0]}' failures.append('\n'.join(SCREAMING_SNAKE_CASE__ ) ) if len(SCREAMING_SNAKE_CASE__ ) > 0: raise ValueError('\n\n'.join(SCREAMING_SNAKE_CASE__ ) ) def UpperCamelCase__ ( ): __lowerCamelCase : Any = [] for path, directories, files in os.walk(SCREAMING_SNAKE_CASE__ ): for folder in directories: # Ignore private modules if folder.startswith('_' ): directories.remove(SCREAMING_SNAKE_CASE__ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(SCREAMING_SNAKE_CASE__ ) / folder).glob('*.py' ) ) ) == 0: continue __lowerCamelCase : Dict = str((Path(SCREAMING_SNAKE_CASE__ ) / folder).relative_to(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : Dict = short_path.replace(os.path.sep , '.' ) submodules.append(SCREAMING_SNAKE_CASE__ ) for fname in files: if fname == "__init__.py": continue __lowerCamelCase : List[Any] = str((Path(SCREAMING_SNAKE_CASE__ ) / fname).relative_to(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : int = short_path.replace('.py' , '' ).replace(os.path.sep , '.' ) if len(submodule.split('.' ) ) == 1: submodules.append(SCREAMING_SNAKE_CASE__ ) return submodules lowercase_ = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', 'models.esm.openfold_utils', ] def UpperCamelCase__ ( ): # This is to make sure the transformers module imported is the one in the repo. from transformers.utils import direct_transformers_import __lowerCamelCase : Union[str, Any] = direct_transformers_import(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = set(transformers._import_structure.keys() ) # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and # (potentiall re-) add them. with open(os.path.join(SCREAMING_SNAKE_CASE__ , '__init__.py' ) , 'r' ) as f: __lowerCamelCase : Tuple = f.read() import_structure_keys.update(set(re.findall(r'import_structure\[\"([^\"]*)\"\]' , SCREAMING_SNAKE_CASE__ ) ) ) __lowerCamelCase : Union[str, Any] = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in import_structure_keys ] if len(SCREAMING_SNAKE_CASE__ ) > 0: __lowerCamelCase : List[Any] = '\n'.join(f'- {module}' for module in module_not_registered ) raise ValueError( 'The following submodules are not properly registed in the main init of Transformers:\n' f'{list_of_modules}\n' 'Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.' ) if __name__ == "__main__": check_all_inits() check_submodules()
669
import unittest from knapsack import greedy_knapsack as kp class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: List[Any] ): __lowerCamelCase : str = [10, 20, 30, 40, 50, 60] __lowerCamelCase : List[str] = [2, 4, 6, 8, 10, 12] __lowerCamelCase : Tuple = 100 self.assertEqual(kp.calc_profit(a , a , a ) , 210 ) def _snake_case ( self: str ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'Weight can not be negative.' ) def _snake_case ( self: Dict ): self.assertRaisesRegex(a , 'Profit can not be negative.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: Any ): self.assertRaisesRegex( a , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
669
1
from __future__ import annotations from collections.abc import Callable from typing import Generic, TypeVar lowercase_ = TypeVar('T') lowercase_ = TypeVar('U') class A_ ( Generic[T, U] ): '''simple docstring''' def __init__( self: Dict , a: T | None , a: U | None ): __lowerCamelCase : Union[str, Any] = key __lowerCamelCase : Union[str, Any] = val __lowerCamelCase : DoubleLinkedListNode[T, U] | None = None __lowerCamelCase : DoubleLinkedListNode[T, U] | None = None def __repr__( self: Any ): return ( F'Node: key: {self.key}, val: {self.val}, ' F'has next: {bool(self.next )}, has prev: {bool(self.prev )}' ) class A_ ( Generic[T, U] ): '''simple docstring''' def __init__( self: Tuple ): __lowerCamelCase : DoubleLinkedListNode[T, U] = DoubleLinkedListNode(a , a ) __lowerCamelCase : DoubleLinkedListNode[T, U] = DoubleLinkedListNode(a , a ) __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.rear, self.head def __repr__( self: str ): __lowerCamelCase : Dict = ['DoubleLinkedList'] __lowerCamelCase : str = self.head while node.next is not None: rep.append(str(a ) ) __lowerCamelCase : List[str] = node.next rep.append(str(self.rear ) ) return ",\n ".join(a ) def _snake_case ( self: List[str] , a: DoubleLinkedListNode[T, U] ): __lowerCamelCase : Union[str, Any] = self.rear.prev # All nodes other than self.head are guaranteed to have non-None previous assert previous is not None __lowerCamelCase : int = node __lowerCamelCase : List[Any] = previous __lowerCamelCase : Optional[int] = node __lowerCamelCase : List[str] = self.rear def _snake_case ( self: Any , a: DoubleLinkedListNode[T, U] ): if node.prev is None or node.next is None: return None __lowerCamelCase : Dict = node.next __lowerCamelCase : Tuple = node.prev __lowerCamelCase : Dict = None __lowerCamelCase : Any = None return node class A_ ( Generic[T, U] ): '''simple docstring''' __snake_case = {} def __init__( self: List[Any] , a: int ): __lowerCamelCase : DoubleLinkedList[T, U] = DoubleLinkedList() __lowerCamelCase : Tuple = capacity __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 __lowerCamelCase : Optional[Any] = 0 __lowerCamelCase : dict[T, DoubleLinkedListNode[T, U]] = {} def __repr__( self: List[str] ): return ( F'CacheInfo(hits={self.hits}, misses={self.miss}, ' F'capacity={self.capacity}, current size={self.num_keys})' ) def __contains__( self: List[Any] , a: T ): return key in self.cache def _snake_case ( self: Tuple , a: T ): # Note: pythonic interface would throw KeyError rather than return None if key in self.cache: self.hits += 1 __lowerCamelCase : DoubleLinkedListNode[T, U] = self.cache[key] __lowerCamelCase : Tuple = self.list.remove(self.cache[key] ) assert node == value_node # node is guaranteed not None because it is in self.cache assert node is not None self.list.add(a ) return node.val self.miss += 1 return None def _snake_case ( self: Union[str, Any] , a: T , a: U ): if key not in self.cache: if self.num_keys >= self.capacity: # delete first node (oldest) when over capacity __lowerCamelCase : List[Any] = self.list.head.next # guaranteed to have a non-None first node when num_keys > 0 # explain to type checker via assertions assert first_node is not None assert first_node.key is not None assert ( self.list.remove(a ) is not None ) # node guaranteed to be in list assert node.key is not None del self.cache[first_node.key] self.num_keys -= 1 __lowerCamelCase : Dict = DoubleLinkedListNode(a , a ) self.list.add(self.cache[key] ) self.num_keys += 1 else: # bump node to the end of the list, update value __lowerCamelCase : List[str] = self.list.remove(self.cache[key] ) assert node is not None # node guaranteed to be in list __lowerCamelCase : Optional[Any] = value self.list.add(a ) @classmethod def _snake_case ( cls: Any , a: int = 128 ): def cache_decorator_inner(a: Callable[[T], U] ) -> Callable[..., U]: def cache_decorator_wrapper(*a: T ) -> U: if func not in cls.decorator_function_to_instance_map: __lowerCamelCase : Any = LRUCache(a ) __lowerCamelCase : List[str] = cls.decorator_function_to_instance_map[func].get(args[0] ) if result is None: __lowerCamelCase : List[str] = func(*a ) cls.decorator_function_to_instance_map[func].put(args[0] , a ) return result def cache_info() -> LRUCache[T, U]: return cls.decorator_function_to_instance_map[func] setattr(a , 'cache_info' , a ) # noqa: B010 return cache_decorator_wrapper return cache_decorator_inner if __name__ == "__main__": import doctest doctest.testmod()
669
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any]=2 , a: str=3 , a: Any=4 , a: Union[str, Any]=2 , a: Tuple=7 , a: int=True , a: Tuple=True , a: List[str]=True , a: Union[str, Any]=True , a: str=99 , a: Tuple=36 , a: int=2 , a: Dict=4 , a: Union[str, Any]=37 , a: List[str]="gelu" , a: List[Any]=0.1 , a: Optional[int]=0.1 , a: Dict=512 , a: Union[str, Any]=16 , a: str=2 , a: int=0.0_2 , a: Optional[Any]=6 , a: Optional[int]=6 , a: Dict=3 , a: Optional[Any]=4 , a: Optional[Any]=None , a: Dict=1000 , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Optional[int] = num_channels __lowerCamelCase : str = image_size __lowerCamelCase : int = patch_size __lowerCamelCase : List[str] = is_training __lowerCamelCase : Dict = use_input_mask __lowerCamelCase : Any = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : str = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : List[Any] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : int = type_sequence_label_size __lowerCamelCase : List[str] = initializer_range __lowerCamelCase : List[str] = coordinate_size __lowerCamelCase : int = shape_size __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : int = num_choices __lowerCamelCase : int = scope __lowerCamelCase : Any = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __lowerCamelCase : Any = text_seq_length __lowerCamelCase : Optional[Any] = (image_size // patch_size) ** 2 + 1 __lowerCamelCase : Any = self.text_seq_length + self.image_seq_length def _snake_case ( self: List[str] ): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __lowerCamelCase : int = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __lowerCamelCase : List[str] = bbox[i, j, 3] __lowerCamelCase : str = bbox[i, j, 1] __lowerCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __lowerCamelCase : Tuple = bbox[i, j, 2] __lowerCamelCase : Any = bbox[i, j, 0] __lowerCamelCase : List[str] = tmp_coordinate __lowerCamelCase : str = tf.constant(a ) __lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.text_seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __lowerCamelCase : Dict = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self: Tuple , a: List[Any] , a: Any , a: List[str] , a: Dict , a: Optional[Any] , a: Dict ): __lowerCamelCase : Optional[Any] = TFLayoutLMvaModel(config=a ) # text + image __lowerCamelCase : Optional[Any] = model(a , pixel_values=a , training=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , training=a , ) __lowerCamelCase : List[Any] = model(a , bbox=a , pixel_values=a , training=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __lowerCamelCase : List[Any] = model(a , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __lowerCamelCase : Optional[Any] = model({'pixel_values': pixel_values} , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self: Dict , a: Dict , a: Optional[Any] , a: int , a: Optional[int] , a: List[str] , a: List[str] , a: List[str] ): __lowerCamelCase : List[str] = self.num_labels __lowerCamelCase : str = TFLayoutLMvaForSequenceClassification(config=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any] , a: Dict , a: Optional[Any] , a: Tuple , a: Optional[Any] , a: List[Any] ): __lowerCamelCase : Union[str, Any] = self.num_labels __lowerCamelCase : Any = TFLayoutLMvaForTokenClassification(config=a ) __lowerCamelCase : Optional[Any] = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self: Dict , a: Optional[Any] , a: str , a: Dict , a: Union[str, Any] , a: List[Any] , a: Optional[int] , a: List[str] ): __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Any = TFLayoutLMvaForQuestionAnswering(config=a ) __lowerCamelCase : Any = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , training=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] ): __lowerCamelCase : str = self.prepare_config_and_inputs() ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : List[Any] = config_and_inputs __lowerCamelCase : Tuple = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: int , a: List[str] , a: Any , a: Optional[Any] , a: Tuple , a: Tuple ): return True def _snake_case ( self: str , a: Any , a: Any , a: Optional[int]=False ): __lowerCamelCase : List[str] = copy.deepcopy(a ) if model_class in get_values(a ): __lowerCamelCase : Tuple = { k: tf.tile(tf.expand_dims(a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a ): __lowerCamelCase : Any = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Dict = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def _snake_case ( self: Tuple ): __lowerCamelCase : int = TFLayoutLMvaModelTester(self ) __lowerCamelCase : str = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self: Union[str, Any] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : int = model_class(a ) if getattr(a , 'hf_compute_loss' , a ): # The number of elements in the loss should be the same as the number of elements in the label __lowerCamelCase : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : int = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=a )[0] ] __lowerCamelCase : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __lowerCamelCase : Optional[int] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : Dict = prepared_for_class.pop('input_ids' ) __lowerCamelCase : str = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __lowerCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : List[str] = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __lowerCamelCase : int = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __lowerCamelCase : Tuple = -100 __lowerCamelCase : Tuple = tf.convert_to_tensor(a ) __lowerCamelCase : Tuple = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __lowerCamelCase : int = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : str = model(a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __lowerCamelCase : str = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) # Get keys that were added with the _prepare_for_class function __lowerCamelCase : Optional[Any] = prepared_for_class.keys() - inputs_dict.keys() __lowerCamelCase : List[Any] = inspect.signature(model.call ).parameters __lowerCamelCase : List[str] = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __lowerCamelCase : Optional[int] = {0: 'input_ids'} for label_key in label_keys: __lowerCamelCase : Dict = signature_names.index(a ) __lowerCamelCase : str = label_key __lowerCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __lowerCamelCase : Optional[int] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __lowerCamelCase : Optional[int] = prepared_for_class[value] __lowerCamelCase : Any = tuple(a ) # Send to model __lowerCamelCase : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def _snake_case ( self: List[str] ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: int ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: Dict ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( a , a , a , a , a , a , a ) @slow def _snake_case ( self: int ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Dict = TFLayoutLMvaModel.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self: Optional[int] ): return LayoutLMvaImageProcessor(apply_ocr=a ) if is_vision_available() else None @slow def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Tuple = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __lowerCamelCase : Union[str, Any] = self.default_image_processor __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : str = image_processor(images=a , return_tensors='tf' ).pixel_values __lowerCamelCase : Union[str, Any] = tf.constant([[1, 2]] ) __lowerCamelCase : str = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __lowerCamelCase : int = model(input_ids=a , bbox=a , pixel_values=a , training=a ) # verify the logits __lowerCamelCase : Optional[int] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , a ) __lowerCamelCase : Any = tf.constant( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-4 ) )
669
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase_ = { 'configuration_data2vec_audio': ['DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecAudioConfig'], 'configuration_data2vec_text': [ 'DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecTextConfig', 'Data2VecTextOnnxConfig', ], 'configuration_data2vec_vision': [ 'DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecVisionConfig', 'Data2VecVisionOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecAudioForAudioFrameClassification', 'Data2VecAudioForCTC', 'Data2VecAudioForSequenceClassification', 'Data2VecAudioForXVector', 'Data2VecAudioModel', 'Data2VecAudioPreTrainedModel', ] lowercase_ = [ 'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecTextForCausalLM', 'Data2VecTextForMaskedLM', 'Data2VecTextForMultipleChoice', 'Data2VecTextForQuestionAnswering', 'Data2VecTextForSequenceClassification', 'Data2VecTextForTokenClassification', 'Data2VecTextModel', 'Data2VecTextPreTrainedModel', ] lowercase_ = [ 'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecVisionForImageClassification', 'Data2VecVisionForMaskedImageModeling', 'Data2VecVisionForSemanticSegmentation', 'Data2VecVisionModel', 'Data2VecVisionPreTrainedModel', ] if is_tf_available(): lowercase_ = [ 'TFData2VecVisionForImageClassification', 'TFData2VecVisionForSemanticSegmentation', 'TFData2VecVisionModel', 'TFData2VecVisionPreTrainedModel', ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
669
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = CLIPTokenizer __snake_case = CLIPTokenizerFast __snake_case = True __snake_case = {} __snake_case = False def _snake_case ( self: Union[str, Any] ): super().setUp() # fmt: off __lowerCamelCase : Any = ['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 __lowerCamelCase : Tuple = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : List[Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>'] __lowerCamelCase : Tuple = {'unk_token': '<unk>'} __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : 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(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: Tuple , **a: Union[str, Any] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Union[str, Any] , **a: List[str] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : Tuple = 'lower newer' __lowerCamelCase : Tuple = 'lower newer' return input_text, output_text def _snake_case ( self: List[str] ): __lowerCamelCase : List[Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase : Optional[Any] = 'lower newer' __lowerCamelCase : int = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>'] __lowerCamelCase : Optional[int] = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : int = tokens + [tokenizer.unk_token] __lowerCamelCase : int = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def _snake_case ( self: Union[str, Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[Any] = self.tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : int = self.rust_tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : str = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.' __lowerCamelCase : Optional[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[Any] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __lowerCamelCase : List[Any] = 'xa\u0303y' + ' ' + 'x\xe3y' __lowerCamelCase : Tuple = tokenizer_s.tokenize(a ) __lowerCamelCase : Any = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type __lowerCamelCase : List[Any] = [ '\u0009', # (horizontal tab, '\t') '\u000B', # (vertical tab) '\u000C', # (form feed) '\u0020', # (space, ' ') '\u200E', # (left-to-right mark):w '\u200F', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __lowerCamelCase : List[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[int] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type __lowerCamelCase : str = [ '\u000A', # (line feed, '\n') '\r\n', # (carriage return and line feed, '\r\n') '\u000D', # (carriage return, '\r') '\r', # (carriage return, '\r') '\u000D', # (carriage return, '\r') '\u2028', # (line separator) '\u2029', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __lowerCamelCase : Dict = tokenizer_s.tokenize(a ) __lowerCamelCase : List[str] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def _snake_case ( self: List[Any] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : Optional[int] = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` __lowerCamelCase : Optional[int] = F'{text_of_1_token} {text_of_1_token}' __lowerCamelCase : Dict = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) __lowerCamelCase : List[Any] = F' {text}' __lowerCamelCase : str = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def _snake_case ( self: str ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def _snake_case ( self: Tuple ): super().test_tokenization_python_rust_equals() def _snake_case ( self: Tuple ): # CLIP always lower cases letters pass
669
1
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """tokenizer"""] __snake_case = """BlipImageProcessor""" __snake_case = """AutoTokenizer""" def __init__( self: int , a: str , a: List[Any] , a: int ): super().__init__(a , a ) # add QFormer tokenizer __lowerCamelCase : Any = qformer_tokenizer def __call__( self: Tuple , a: ImageInput = None , a: Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , a: bool = True , a: Union[bool, str, PaddingStrategy] = False , a: Union[bool, str, TruncationStrategy] = None , a: Optional[int] = None , a: int = 0 , a: Optional[int] = None , a: Optional[bool] = None , a: bool = False , a: bool = False , a: bool = False , a: bool = False , a: bool = False , a: bool = True , a: Optional[Union[str, TensorType]] = None , **a: List[str] , ): if images is None and text is None: raise ValueError('You have to specify at least images or text.' ) __lowerCamelCase : List[str] = BatchFeature() if text is not None: __lowerCamelCase : Optional[int] = self.tokenizer( text=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_token_type_ids=a , return_length=a , verbose=a , return_tensors=a , **a , ) encoding.update(a ) __lowerCamelCase : Any = self.qformer_tokenizer( text=a , add_special_tokens=a , padding=a , truncation=a , max_length=a , stride=a , pad_to_multiple_of=a , return_attention_mask=a , return_overflowing_tokens=a , return_special_tokens_mask=a , return_offsets_mapping=a , return_token_type_ids=a , return_length=a , verbose=a , return_tensors=a , **a , ) __lowerCamelCase : Dict = qformer_text_encoding.pop('input_ids' ) __lowerCamelCase : Tuple = qformer_text_encoding.pop('attention_mask' ) if images is not None: __lowerCamelCase : Tuple = self.image_processor(a , return_tensors=a ) encoding.update(a ) return encoding def _snake_case ( self: List[Any] , *a: Dict , **a: str ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: Optional[int] , *a: List[str] , **a: Any ): return self.tokenizer.decode(*a , **a ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def _snake_case ( self: Dict ): __lowerCamelCase : Union[str, Any] = self.tokenizer.model_input_names __lowerCamelCase : Optional[int] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def _snake_case ( self: Optional[int] , a: List[str] , **a: Dict ): if os.path.isfile(a ): raise ValueError(F'Provided path ({save_directory}) should be a directory, not a file' ) os.makedirs(a , exist_ok=a ) __lowerCamelCase : Union[str, Any] = os.path.join(a , 'qformer_tokenizer' ) self.qformer_tokenizer.save_pretrained(a ) return super().save_pretrained(a , **a ) @classmethod def _snake_case ( cls: Tuple , a: str , **a: Any ): __lowerCamelCase : Optional[int] = AutoTokenizer.from_pretrained(a , subfolder='qformer_tokenizer' ) __lowerCamelCase : Dict = cls._get_arguments_from_pretrained(a , **a ) args.append(a ) return cls(*a )
669
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowercase_ = False try: lowercase_ = _is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class A_ : '''simple docstring''' def __init__( self: int , a: str = None , a: list = [] ): __lowerCamelCase : Dict = 0 __lowerCamelCase : Dict = choices __lowerCamelCase : Tuple = prompt if sys.platform == "win32": __lowerCamelCase : Union[str, Any] = '*' else: __lowerCamelCase : Any = '➔ ' def _snake_case ( self: Any , a: Tuple , a: str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def _snake_case ( self: Tuple , a: int ): if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def _snake_case ( self: Optional[int] , a: Direction , a: int = 1 ): __lowerCamelCase : str = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['up'] ) def _snake_case ( self: Tuple ): self.move_direction(Direction.UP ) @input.mark(KEYMAP['down'] ) def _snake_case ( self: Optional[int] ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['newline'] ) def _snake_case ( self: str ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) return self.position @input.mark(KEYMAP['interrupt'] ) def _snake_case ( self: Union[str, Any] ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def _snake_case ( self: str ): __lowerCamelCase : List[Any] = int(chr(self.current_selection ) ) __lowerCamelCase : Any = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def _snake_case ( self: str , a: int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , '\n' ) if in_colab: forceWrite('Please input a choice index (starting from 0), and press enter' , '\n' ) else: forceWrite('Please select a choice using the arrow or number keys, and selecting with enter' , '\n' ) __lowerCamelCase : Dict = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('\n' ) move_cursor(len(self.choices ) - self.position , 'UP' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase : Any = int(builtins.input() ) except ValueError: __lowerCamelCase : str = default_choice else: __lowerCamelCase : Optional[int] = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , 'UP' ) clear_line() self.write_choice(a , '\n' ) return choice
669
1
import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class A_ : '''simple docstring''' def __init__( self: List[Any] , a: Dict , a: List[Any]=13 , a: List[str]=7 , a: Optional[int]=True , a: List[Any]=True , a: List[str]=True , a: str=True , a: Tuple=99 , a: Dict=16 , a: List[str]=36 , a: List[Any]=6 , a: str=6 , a: int=6 , a: Dict=37 , a: Tuple="gelu" , a: Optional[Any]=0.1 , a: int=0.1 , a: Dict=512 , a: int=16 , a: Union[str, Any]=2 , a: int=0.0_2 , a: Any=3 , a: Optional[Any]=4 , a: Any=None , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Any = batch_size __lowerCamelCase : Optional[int] = seq_length __lowerCamelCase : Dict = is_training __lowerCamelCase : int = use_input_mask __lowerCamelCase : List[str] = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : List[Any] = vocab_size __lowerCamelCase : str = embedding_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : int = num_hidden_layers __lowerCamelCase : int = num_hidden_groups __lowerCamelCase : Optional[Any] = num_attention_heads __lowerCamelCase : Optional[int] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Dict = attention_probs_dropout_prob __lowerCamelCase : str = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : Any = type_sequence_label_size __lowerCamelCase : Dict = initializer_range __lowerCamelCase : List[Any] = num_labels __lowerCamelCase : Optional[Any] = num_choices __lowerCamelCase : Any = scope def _snake_case ( self: int ): __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCamelCase : Tuple = None __lowerCamelCase : Optional[int] = None __lowerCamelCase : Dict = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) __lowerCamelCase : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _snake_case ( self: Dict ): return AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , ) def _snake_case ( self: Union[str, Any] , a: int , a: Optional[int] , a: int , a: Dict , a: Optional[int] , a: str , a: str ): __lowerCamelCase : Optional[Any] = AlbertModel(config=a ) model.to(a ) model.eval() __lowerCamelCase : Union[str, Any] = model(a , attention_mask=a , token_type_ids=a ) __lowerCamelCase : Any = model(a , token_type_ids=a ) __lowerCamelCase : List[str] = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _snake_case ( self: List[str] , a: Dict , a: Optional[Any] , a: int , a: Tuple , a: Any , a: Tuple , a: int ): __lowerCamelCase : Dict = AlbertForPreTraining(config=a ) model.to(a ) model.eval() __lowerCamelCase : Any = model( a , attention_mask=a , token_type_ids=a , labels=a , sentence_order_label=a , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def _snake_case ( self: List[str] , a: int , a: Tuple , a: Optional[Any] , a: Any , a: Any , a: Any , a: List[str] ): __lowerCamelCase : int = AlbertForMaskedLM(config=a ) model.to(a ) model.eval() __lowerCamelCase : Any = model(a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self: Optional[int] , a: Union[str, Any] , a: Optional[int] , a: Union[str, Any] , a: List[str] , a: Optional[Any] , a: Dict , a: List[Any] ): __lowerCamelCase : List[str] = AlbertForQuestionAnswering(config=a ) model.to(a ) model.eval() __lowerCamelCase : Optional[Any] = model( a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] , a: Optional[Any] , a: List[Any] , a: Union[str, Any] , a: List[Any] , a: int , a: Optional[Any] , a: List[Any] ): __lowerCamelCase : List[Any] = self.num_labels __lowerCamelCase : List[str] = AlbertForSequenceClassification(a ) model.to(a ) model.eval() __lowerCamelCase : List[Any] = model(a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Dict , a: List[Any] , a: int , a: Any , a: Optional[int] , a: Optional[int] , a: int , a: Tuple ): __lowerCamelCase : Optional[int] = self.num_labels __lowerCamelCase : int = AlbertForTokenClassification(config=a ) model.to(a ) model.eval() __lowerCamelCase : List[Any] = model(a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _snake_case ( self: Dict , a: Optional[int] , a: Optional[int] , a: Dict , a: Union[str, Any] , a: List[str] , a: List[Any] , a: List[str] ): __lowerCamelCase : Optional[int] = self.num_choices __lowerCamelCase : Optional[int] = AlbertForMultipleChoice(config=a ) model.to(a ) model.eval() __lowerCamelCase : List[str] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase : str = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase : Any = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __lowerCamelCase : Dict = model( a , attention_mask=a , token_type_ids=a , labels=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _snake_case ( self: int ): __lowerCamelCase : Tuple = self.prepare_config_and_inputs() ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Optional[int] = config_and_inputs __lowerCamelCase : Union[str, Any] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) __snake_case = ( { """feature-extraction""": AlbertModel, """fill-mask""": AlbertForMaskedLM, """question-answering""": AlbertForQuestionAnswering, """text-classification""": AlbertForSequenceClassification, """token-classification""": AlbertForTokenClassification, """zero-shot""": AlbertForSequenceClassification, } if is_torch_available() else {} ) __snake_case = True def _snake_case ( self: List[Any] , a: Tuple , a: Optional[int] , a: List[str]=False ): __lowerCamelCase : str = super()._prepare_for_class(a , a , return_labels=a ) if return_labels: if model_class in get_values(a ): __lowerCamelCase : Any = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=a ) __lowerCamelCase : Any = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a ) return inputs_dict def _snake_case ( self: Tuple ): __lowerCamelCase : List[Any] = AlbertModelTester(self ) __lowerCamelCase : List[Any] = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Tuple ): self.config_tester.run_common_tests() def _snake_case ( self: Dict ): __lowerCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a ) def _snake_case ( self: str ): __lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*a ) def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a ) def _snake_case ( self: List[Any] ): __lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase : str = type self.model_tester.create_and_check_model(*a ) @slow def _snake_case ( self: Any ): for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Optional[int] = AlbertModel.from_pretrained(a ) self.assertIsNotNone(a ) @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' @slow def _snake_case ( self: Tuple ): __lowerCamelCase : Any = AlbertModel.from_pretrained('albert-base-v2' ) __lowerCamelCase : Dict = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) __lowerCamelCase : int = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): __lowerCamelCase : Tuple = model(a , attention_mask=a )[0] __lowerCamelCase : List[str] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , a ) __lowerCamelCase : int = torch.tensor( [[[-0.6_5_1_3, 1.5_0_3_5, -0.2_7_6_6], [-0.6_5_1_5, 1.5_0_4_6, -0.2_7_8_0], [-0.6_5_1_2, 1.5_0_4_9, -0.2_7_8_4]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a , atol=1e-4 ) )
669
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = (CMStochasticIterativeScheduler,) __snake_case = 10 def _snake_case ( self: Any , **a: Dict ): __lowerCamelCase : Optional[Any] = { 'num_train_timesteps': 201, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } config.update(**a ) return config def _snake_case ( self: List[Any] ): __lowerCamelCase : Any = 10 __lowerCamelCase : Any = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = self.scheduler_classes[0](**a ) scheduler.set_timesteps(a ) __lowerCamelCase : Any = scheduler.timesteps[0] __lowerCamelCase : List[str] = scheduler.timesteps[1] __lowerCamelCase : Union[str, Any] = self.dummy_sample __lowerCamelCase : int = 0.1 * sample __lowerCamelCase : Optional[Any] = scheduler.step(a , a , a ).prev_sample __lowerCamelCase : List[str] = scheduler.step(a , a , a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self: Optional[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a ) def _snake_case ( self: List[str] ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=a ) def _snake_case ( self: Tuple ): __lowerCamelCase : Tuple = self.scheduler_classes[0] __lowerCamelCase : Tuple = self.get_scheduler_config() __lowerCamelCase : Tuple = scheduler_class(**a ) __lowerCamelCase : int = 1 scheduler.set_timesteps(a ) __lowerCamelCase : Optional[int] = scheduler.timesteps __lowerCamelCase : List[str] = torch.manual_seed(0 ) __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(a ): # 1. scale model input __lowerCamelCase : List[str] = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Optional[int] = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : str = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : str = pred_prev_sample __lowerCamelCase : List[str] = torch.sum(torch.abs(a ) ) __lowerCamelCase : str = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**a ) __lowerCamelCase : List[Any] = [106, 0] scheduler.set_timesteps(timesteps=a ) __lowerCamelCase : Dict = scheduler.timesteps __lowerCamelCase : int = torch.manual_seed(0 ) __lowerCamelCase : Any = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __lowerCamelCase : Tuple = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Tuple = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : Any = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : Any = pred_prev_sample __lowerCamelCase : Dict = torch.sum(torch.abs(a ) ) __lowerCamelCase : Optional[Any] = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : int = self.get_scheduler_config() __lowerCamelCase : List[Any] = scheduler_class(**a ) __lowerCamelCase : Optional[Any] = [39, 30, 12, 15, 0] with self.assertRaises(a , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=a ) def _snake_case ( self: int ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Union[str, Any] = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [39, 30, 12, 1, 0] __lowerCamelCase : List[Any] = len(a ) with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=a , timesteps=a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Dict = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=a )
669
1
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_ = { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """xlm-roberta""" def __init__( self: Optional[Any] , a: int=3_0522 , a: List[Any]=768 , a: Tuple=12 , a: List[str]=12 , a: Dict=3072 , a: List[str]="gelu" , a: Any=0.1 , a: Optional[Any]=0.1 , a: str=512 , a: Optional[int]=2 , a: int=0.0_2 , a: str=1e-12 , a: str=1 , a: List[Any]=0 , a: Dict=2 , a: Dict="absolute" , a: List[Any]=True , a: str=None , **a: List[Any] , ): super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : str = hidden_act __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : int = max_position_embeddings __lowerCamelCase : Any = type_vocab_size __lowerCamelCase : int = initializer_range __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : List[Any] = position_embedding_type __lowerCamelCase : List[str] = use_cache __lowerCamelCase : Optional[int] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
669
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") lowercase_ = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find('meta', {'property': 'og:image'})['content'] lowercase_ = requests.get(image_url).content lowercase_ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
669
1
import torch from transformers import CamembertForMaskedLM, CamembertTokenizer def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=5 ): # Adapted from https://github.com/pytorch/fairseq/blob/master/fairseq/models/roberta/hub_interface.py assert masked_input.count('<mask>' ) == 1 __lowerCamelCase : Union[str, Any] = torch.tensor(tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) ).unsqueeze(0 ) # Batch size 1 __lowerCamelCase : str = model(SCREAMING_SNAKE_CASE__ )[0] # The last hidden-state is the first element of the output tuple __lowerCamelCase : Optional[int] = (input_ids.squeeze() == tokenizer.mask_token_id).nonzero().item() __lowerCamelCase : int = logits[0, masked_index, :] __lowerCamelCase : Dict = logits.softmax(dim=0 ) __lowerCamelCase , __lowerCamelCase : int = prob.topk(k=SCREAMING_SNAKE_CASE__ , dim=0 ) __lowerCamelCase : List[str] = ' '.join( [tokenizer.convert_ids_to_tokens(indices[i].item() ) for i in range(len(SCREAMING_SNAKE_CASE__ ) )] ) __lowerCamelCase : int = tokenizer.mask_token __lowerCamelCase : Optional[int] = [] for index, predicted_token_bpe in enumerate(topk_predicted_token_bpe.split(' ' ) ): __lowerCamelCase : str = predicted_token_bpe.replace('\u2581' , ' ' ) if " {0}".format(SCREAMING_SNAKE_CASE__ ) in masked_input: topk_filled_outputs.append( ( masked_input.replace(' {0}'.format(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ), values[index].item(), predicted_token, ) ) else: topk_filled_outputs.append( ( masked_input.replace(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ), values[index].item(), predicted_token, ) ) return topk_filled_outputs lowercase_ = CamembertTokenizer.from_pretrained('camembert-base') lowercase_ = CamembertForMaskedLM.from_pretrained('camembert-base') model.eval() lowercase_ = 'Le camembert est <mask> :)' print(fill_mask(masked_input, model, tokenizer, topk=3))
669
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore lowercase_ = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" lowercase_ = [file for file in filepaths if file != file.lower()] if upper_files: print(F"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') lowercase_ = [file for file in filepaths if ' ' in file] if space_files: print(F"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') lowercase_ = [file for file in filepaths if '-' in file] if hyphen_files: print(F"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') lowercase_ = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') lowercase_ = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
669
1
from PIL import Image def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): def brightness(SCREAMING_SNAKE_CASE__ ) -> float: return 128 + level + (c - 128) if not -255.0 <= level <= 255.0: raise ValueError('level must be between -255.0 (black) and 255.0 (white)' ) return img.point(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": # Load image with Image.open('image_data/lena.jpg') as img: # Change brightness to 100 lowercase_ = change_brightness(img, 1_0_0) brigt_img.save('image_data/lena_brightness.png', format='png')
669
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_ = { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """xlm-roberta""" def __init__( self: Optional[Any] , a: int=3_0522 , a: List[Any]=768 , a: Tuple=12 , a: List[str]=12 , a: Dict=3072 , a: List[str]="gelu" , a: Any=0.1 , a: Optional[Any]=0.1 , a: str=512 , a: Optional[int]=2 , a: int=0.0_2 , a: str=1e-12 , a: str=1 , a: List[Any]=0 , a: Dict=2 , a: Dict="absolute" , a: List[Any]=True , a: str=None , **a: List[Any] , ): super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : str = hidden_act __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : int = max_position_embeddings __lowerCamelCase : Any = type_vocab_size __lowerCamelCase : int = initializer_range __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : List[Any] = position_embedding_type __lowerCamelCase : List[str] = use_cache __lowerCamelCase : Optional[int] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
669
1
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_with_bytefallback.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = GPTSwaTokenizer __snake_case = False __snake_case = True __snake_case = False def _snake_case ( self: int ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : Any = GPTSwaTokenizer(a , eos_token='<unk>' , bos_token='<unk>' , pad_token='<unk>' ) tokenizer.save_pretrained(self.tmpdirname ) def _snake_case ( self: Optional[int] , a: Tuple ): __lowerCamelCase : int = 'This is a test' __lowerCamelCase : List[Any] = 'This is a test' return input_text, output_text def _snake_case ( self: List[Any] ): __lowerCamelCase : Union[str, Any] = '<s>' __lowerCamelCase : Optional[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Dict = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , 'j' ) self.assertEqual(len(a ) , 2000 ) def _snake_case ( self: Any ): self.assertEqual(self.get_tokenizer().vocab_size , 2000 ) def _snake_case ( self: List[Any] ): __lowerCamelCase : List[str] = GPTSwaTokenizer(a ) __lowerCamelCase : Any = tokenizer.tokenize('This is a test' ) self.assertListEqual(a , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , [465, 287, 265, 631, 842] ) __lowerCamelCase : Union[str, Any] = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) # fmt: off self.assertListEqual( a , ['▁I', '▁was', '▁bor', 'n', '▁in', '▁', '<0x39>', '2', '0', '0', '0', ',', '▁and', '▁this', '▁is', '▁f', 'al', 's', '<0xC3>', '<0xA9>', '.'] , ) # fmt: on __lowerCamelCase : str = tokenizer.convert_tokens_to_ids(a ) self.assertListEqual( a , [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , ) __lowerCamelCase : str = tokenizer.convert_ids_to_tokens(a ) # fmt: off self.assertListEqual( a , ['▁I', '▁was', '▁bor', 'n', '▁in', '▁', '<0x39>', '2', '0', '0', '0', ',', '▁and', '▁this', '▁is', '▁f', 'al', 's', '<0xC3>', '<0xA9>', '.'] ) # fmt: on def _snake_case ( self: List[Any] ): __lowerCamelCase : int = GPTSwaTokenizer(a ) __lowerCamelCase : Optional[Any] = ['This is a test', 'I was born in 92000, and this is falsé.'] __lowerCamelCase : Optional[Any] = [ [465, 287, 265, 631, 842], [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(a , a ): self.assertListEqual(tokenizer.encode_fast(a ) , a ) # Test that decode_fast returns the input text for text, token_ids in zip(a , a ): self.assertEqual(tokenizer.decode_fast(a ) , a ) @slow def _snake_case ( self: List[Any] ): __lowerCamelCase : Optional[int] = [ '<|python|>def fibonacci(n)\n if n < 0:\n print(\'Incorrect input\')', 'Hey there, how are you doing this fine day?', 'This is a text with a trailing spaces followed by a dot .', 'Häj sväjs lillebrör! =)', 'Det är inget fel på Mr. Cool', ] # fmt: off __lowerCamelCase : Union[str, Any] = {'input_ids': [[6_3423, 5, 6811, 1_4954, 282, 816, 3821, 6_3466, 6_3425, 6_3462, 18, 6_3978, 678, 301, 1320, 6_3423, 6_3455, 6_3458, 18, 6_3982, 4246, 3940, 1901, 4_7789, 5547, 1_8994], [1_9630, 1100, 6_3446, 1342, 633, 544, 4488, 593, 5102, 2416, 6_3495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 5_8593, 2_2413, 9106, 546, 268, 3_3213, 6_3979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_5130, 6_3450, 924, 6_3449, 2249, 4062, 1558, 318, 6_3504, 2_1498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 6_3443, 2_6801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [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], [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]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='AI-Sweden/gpt-sw3-126m' , sequences=a , )
669
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ConsistencyModelPipeline __snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __snake_case = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def _snake_case ( self: str ): __lowerCamelCase : Tuple = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _snake_case ( self: Tuple ): __lowerCamelCase : List[str] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _snake_case ( self: int , a: str=False ): if class_cond: __lowerCamelCase : str = self.dummy_cond_unet else: __lowerCamelCase : str = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCamelCase : Tuple = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def _snake_case ( self: int , a: List[str] , a: Any=0 ): if str(a ).startswith('mps' ): __lowerCamelCase : List[Any] = torch.manual_seed(a ) else: __lowerCamelCase : Tuple = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : Optional[Any] = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : str = ConsistencyModelPipeline(**a ) __lowerCamelCase : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Any = self.get_dummy_inputs(a ) __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[int] = ConsistencyModelPipeline(**a ) __lowerCamelCase : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(a ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : List[str] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Optional[int] = self.get_dummy_components() __lowerCamelCase : Tuple = ConsistencyModelPipeline(**a ) __lowerCamelCase : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = self.get_dummy_inputs(a ) __lowerCamelCase : str = 1 __lowerCamelCase : Optional[int] = None __lowerCamelCase : Any = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[int] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: List[str] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : List[Any] = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[Any] = ConsistencyModelPipeline(**a ) __lowerCamelCase : List[Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_dummy_inputs(a ) __lowerCamelCase : List[str] = 1 __lowerCamelCase : List[str] = None __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Optional[int] , a: str=0 , a: Tuple=False , a: Tuple="cpu" , a: List[str]=torch.floataa , a: Optional[Any]=(1, 3, 64, 64) ): __lowerCamelCase : Optional[Any] = torch.manual_seed(a ) __lowerCamelCase : Optional[int] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __lowerCamelCase : Dict = self.get_fixed_latents(seed=a , device=a , dtype=a , shape=a ) __lowerCamelCase : Optional[Any] = latents return inputs def _snake_case ( self: Any , a: Any=0 , a: List[str]="cpu" , a: Optional[Any]=torch.floataa , a: int=(1, 3, 64, 64) ): if type(a ) == str: __lowerCamelCase : Dict = torch.device(a ) __lowerCamelCase : Union[str, Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : str = randn_tensor(a , generator=a , device=a , dtype=a ) return latents def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs() __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Dict = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_inputs() __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Tuple = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : List[Any] = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs(get_fixed_latents=a , device=a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : int = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[Any] = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def _snake_case ( self: Dict ): __lowerCamelCase : Dict = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = self.get_inputs(get_fixed_latents=a , device=a ) __lowerCamelCase : str = 1 __lowerCamelCase : Union[str, Any] = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : str = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
669
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available lowercase_ = { 'configuration_audio_spectrogram_transformer': [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ASTConfig', ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'ASTForAudioClassification', 'ASTModel', 'ASTPreTrainedModel', ] try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['ASTFeatureExtractor'] if TYPE_CHECKING: from .configuration_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, ASTConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_audio_spectrogram_transformer import ( AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ASTForAudioClassification, ASTModel, ASTPreTrainedModel, ) try: if not is_speech_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
669
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """trocr""" __snake_case = ["""past_key_values"""] __snake_case = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Dict , a: List[str]=5_0265 , a: Optional[Any]=1024 , a: Tuple=12 , a: Dict=16 , a: Optional[Any]=4096 , a: Optional[Any]="gelu" , a: Optional[int]=512 , a: int=0.1 , a: str=0.0 , a: Union[str, Any]=0.0 , a: Any=2 , a: Optional[int]=0.0_2 , a: Optional[Any]=0.0 , a: List[Any]=True , a: Any=False , a: int=True , a: Optional[Any]=True , a: Tuple=1 , a: Union[str, Any]=0 , a: Any=2 , **a: List[Any] , ): __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : List[str] = decoder_layers __lowerCamelCase : Optional[Any] = decoder_attention_heads __lowerCamelCase : List[str] = decoder_ffn_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : Optional[Any] = max_position_embeddings __lowerCamelCase : Dict = dropout __lowerCamelCase : int = attention_dropout __lowerCamelCase : List[str] = activation_dropout __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Tuple = decoder_layerdrop __lowerCamelCase : str = use_cache __lowerCamelCase : List[Any] = scale_embedding __lowerCamelCase : Any = use_learned_position_embeddings __lowerCamelCase : List[Any] = layernorm_embedding super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , decoder_start_token_id=a , **a , )
669
1
import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename lowercase_ = 'http://www.mocksite.com/file1.txt' lowercase_ = '"text": ["foo", "foo"]' lowercase_ = '6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8' class A_ : '''simple docstring''' __snake_case = 200 __snake_case = {"""Content-Length""": """100"""} __snake_case = {} def _snake_case ( self: Optional[Any] , **a: Tuple ): return [bytes(a , 'utf-8' )] def UpperCamelCase__ ( *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ): return MockResponse() @pytest.mark.parametrize('urls_type' , [str, list, dict] ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): import requests monkeypatch.setattr(SCREAMING_SNAKE_CASE__ , 'request' , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = URL if issubclass(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = url elif issubclass(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = [url] elif issubclass(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = {'train': url} __lowerCamelCase : Tuple = 'dummy' __lowerCamelCase : Any = 'downloads' __lowerCamelCase : List[str] = tmp_path __lowerCamelCase : List[Any] = DownloadConfig( cache_dir=os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) , use_etag=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase : str = DownloadManager(dataset_name=SCREAMING_SNAKE_CASE__ , download_config=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = dl_manager.download(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = urls for downloaded_paths in [downloaded_paths]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = [downloaded_paths] __lowerCamelCase : Union[str, Any] = [urls] elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): assert "train" in downloaded_paths.keys() __lowerCamelCase : Optional[Any] = downloaded_paths.values() __lowerCamelCase : Union[str, Any] = urls.values() assert downloaded_paths for downloaded_path, input_url in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): assert downloaded_path == dl_manager.downloaded_paths[input_url] __lowerCamelCase : Optional[int] = Path(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = downloaded_path.parts assert parts[-1] == HASH assert parts[-2] == cache_subdir assert downloaded_path.exists() __lowerCamelCase : Union[str, Any] = downloaded_path.read_text() assert content == CONTENT __lowerCamelCase : Tuple = downloaded_path.with_suffix('.json' ) assert metadata_downloaded_path.exists() __lowerCamelCase : List[str] = json.loads(metadata_downloaded_path.read_text() ) assert metadata_content == {"url": URL, "etag": None} @pytest.mark.parametrize('paths_type' , [str, list, dict] ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = str(SCREAMING_SNAKE_CASE__ ) if issubclass(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = filename elif issubclass(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = [filename] elif issubclass(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = {'train': filename} __lowerCamelCase : Tuple = 'dummy' __lowerCamelCase : Optional[Any] = xz_file.parent __lowerCamelCase : Dict = 'extracted' __lowerCamelCase : Dict = DownloadConfig( cache_dir=SCREAMING_SNAKE_CASE__ , use_etag=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase : Optional[int] = DownloadManager(dataset_name=SCREAMING_SNAKE_CASE__ , download_config=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[Any] = dl_manager.extract(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = paths for extracted_paths in [extracted_paths]: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = [extracted_paths] __lowerCamelCase : Optional[Any] = [paths] elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): assert "train" in extracted_paths.keys() __lowerCamelCase : Optional[Any] = extracted_paths.values() __lowerCamelCase : Tuple = paths.values() assert extracted_paths for extracted_path, input_path in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): assert extracted_path == dl_manager.extracted_paths[input_path] __lowerCamelCase : Tuple = Path(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = extracted_path.parts assert parts[-1] == hash_url_to_filename(SCREAMING_SNAKE_CASE__ , etag=SCREAMING_SNAKE_CASE__ ) assert parts[-2] == extracted_subdir assert extracted_path.exists() __lowerCamelCase : Optional[Any] = extracted_path.read_text() __lowerCamelCase : Tuple = text_file.read_text() assert extracted_file_content == expected_file_content def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): assert path.endswith('.jsonl' ) for num_items, line in enumerate(SCREAMING_SNAKE_CASE__ , start=1 ): __lowerCamelCase : Dict = json.loads(line.decode('utf-8' ) ) assert item.keys() == {"col_1", "col_2", "col_3"} assert num_items == 4 @pytest.mark.parametrize('archive_jsonl' , ['tar_jsonl_path', 'zip_jsonl_path'] ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = request.getfixturevalue(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = DownloadManager() for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(SCREAMING_SNAKE_CASE__ ) , start=1 ): _test_jsonl(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert num_jsonl == 2 @pytest.mark.parametrize('archive_nested_jsonl' , ['tar_nested_jsonl_path', 'zip_nested_jsonl_path'] ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[Any] = request.getfixturevalue(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = DownloadManager() for num_tar, (path, file) in enumerate(dl_manager.iter_archive(SCREAMING_SNAKE_CASE__ ) , start=1 ): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(SCREAMING_SNAKE_CASE__ ) , start=1 ): _test_jsonl(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) assert num_tar == 1 assert num_jsonl == 2 def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = DownloadManager() for num_file, file in enumerate(dl_manager.iter_files(SCREAMING_SNAKE_CASE__ ) , start=1 ): assert os.path.basename(SCREAMING_SNAKE_CASE__ ) == ("test.txt" if num_file == 1 else "train.txt") assert num_file == 2
669
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """tokenizer"""] __snake_case = """CLIPImageProcessor""" __snake_case = ("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self: Union[str, Any] , a: int=None , a: List[str]=None , **a: str ): __lowerCamelCase : int = 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 , ) __lowerCamelCase : str = kwargs.pop('feature_extractor' ) __lowerCamelCase : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: List[Any]=None , a: List[str]=None , a: int=None , **a: List[Any] ): if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __lowerCamelCase : Dict = self.tokenizer(a , return_tensors=a , **a ) if images is not None: __lowerCamelCase : Tuple = self.image_processor(a , return_tensors=a , **a ) if text is not None and images is not None: __lowerCamelCase : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a ) , tensor_type=a ) def _snake_case ( self: List[Any] , *a: Optional[Any] , **a: int ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: Any , *a: Union[str, Any] , **a: Optional[Any] ): return self.tokenizer.decode(*a , **a ) @property def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = self.tokenizer.model_input_names __lowerCamelCase : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
669
1
import pytest lowercase_ = '__dummy_dataset1__' lowercase_ = '\nimport json\nimport os\n\nimport datasets\n\n\nREPO_URL = "https://huggingface.co/datasets/albertvillanova/tests-raw-jsonl/resolve/main/"\nURLS = {"train": REPO_URL + "wikiann-bn-train.jsonl", "validation": REPO_URL + "wikiann-bn-validation.jsonl"}\n\n\nclass __DummyDataset1__(datasets.GeneratorBasedBuilder):\n\n def _info(self):\n features = datasets.Features(\n {\n "tokens": datasets.Sequence(datasets.Value("string")),\n "ner_tags": datasets.Sequence(\n datasets.features.ClassLabel(\n names=[\n "O",\n "B-PER",\n "I-PER",\n "B-ORG",\n "I-ORG",\n "B-LOC",\n "I-LOC",\n ]\n )\n ),\n "langs": datasets.Sequence(datasets.Value("string")),\n "spans": datasets.Sequence(datasets.Value("string")),\n }\n )\n return datasets.DatasetInfo(features=features)\n\n def _split_generators(self, dl_manager):\n dl_path = dl_manager.download(URLS)\n return [\n datasets.SplitGenerator(datasets.Split.TRAIN, gen_kwargs={"filepath": dl_path["train"]}),\n datasets.SplitGenerator(datasets.Split.VALIDATION, gen_kwargs={"filepath": dl_path["validation"]}),\n ]\n\n def _generate_examples(self, filepath):\n with open(filepath, "r", encoding="utf-8") as f:\n for i, line in enumerate(f):\n yield i, json.loads(line)\n' @pytest.fixture def UpperCamelCase__ ( ): return DATASET_LOADING_SCRIPT_NAME @pytest.fixture def UpperCamelCase__ ( ): return DATASET_LOADING_SCRIPT_CODE @pytest.fixture def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = dataset_loading_script_name __lowerCamelCase : List[str] = tmp_path / 'datasets' / script_name script_dir.mkdir(parents=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : List[str] = script_dir / f'{script_name}.py' with open(SCREAMING_SNAKE_CASE__ , 'w' ) as f: f.write(SCREAMING_SNAKE_CASE__ ) return str(SCREAMING_SNAKE_CASE__ )
669
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self: int ): torch.manual_seed(0 ) __lowerCamelCase : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Any = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _snake_case ( self: Dict ): torch.manual_seed(0 ) __lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.dummy_uncond_unet __lowerCamelCase : List[str] = DDIMScheduler() __lowerCamelCase : str = self.dummy_vq_model __lowerCamelCase : Optional[int] = LDMPipeline(unet=a , vqvae=a , scheduler=a ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[int] = torch.manual_seed(0 ) __lowerCamelCase : Any = ldm(generator=a , num_inference_steps=2 , output_type='numpy' ).images __lowerCamelCase : Tuple = torch.manual_seed(0 ) __lowerCamelCase : Dict = ldm(generator=a , num_inference_steps=2 , output_type='numpy' , return_dict=a )[0] __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[int] = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) __lowerCamelCase : str = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : int = ldm(generator=a , num_inference_steps=5 , output_type='numpy' ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __lowerCamelCase : List[Any] = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) __lowerCamelCase : Union[str, Any] = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
669
1
import math def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Union[str, Any] = [] __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Dict = int(math.sqrt(SCREAMING_SNAKE_CASE__ ) ) # Size of every segment __lowerCamelCase : Any = [True] * (end + 1) __lowerCamelCase : List[Any] = [] while start <= end: if temp[start] is True: in_prime.append(SCREAMING_SNAKE_CASE__ ) for i in range(start * start , end + 1 , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = False start += 1 prime += in_prime __lowerCamelCase : List[Any] = end + 1 __lowerCamelCase : Optional[int] = min(2 * end , SCREAMING_SNAKE_CASE__ ) while low <= n: __lowerCamelCase : List[str] = [True] * (high - low + 1) for each in in_prime: __lowerCamelCase : List[Any] = math.floor(low / each ) * each if t < low: t += each for j in range(SCREAMING_SNAKE_CASE__ , high + 1 , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = False for j in range(len(SCREAMING_SNAKE_CASE__ ) ): if temp[j] is True: prime.append(j + low ) __lowerCamelCase : Any = high + 1 __lowerCamelCase : int = min(high + end , SCREAMING_SNAKE_CASE__ ) return prime print(sieve(1_0**6))
669
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = 'Usage of script: script_name <size_of_canvas:int>' lowercase_ = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = [[False for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] return canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): for j, _ in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = bool(random.getrandbits(1 ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = np.array(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(SCREAMING_SNAKE_CASE__ ): for c, pt in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = __judge_point( SCREAMING_SNAKE_CASE__ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __lowerCamelCase : Any = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __lowerCamelCase : list[list[bool]] = current_canvas.tolist() return return_canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __lowerCamelCase : Tuple = pt if pt: if alive < 2: __lowerCamelCase : Optional[Any] = False elif alive == 2 or alive == 3: __lowerCamelCase : Any = True elif alive > 3: __lowerCamelCase : Dict = False else: if alive == 3: __lowerCamelCase : Tuple = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ ,lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(['w', 'k']) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
669
1
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = """hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline""" def _snake_case ( self: List[str] , a: int=0 ): __lowerCamelCase : List[str] = floats_tensor((1, 3, 128, 128) , rng=random.Random(a ) ) __lowerCamelCase : Optional[int] = np.random.RandomState(a ) __lowerCamelCase : List[str] = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.7_5, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def _snake_case ( self: str ): __lowerCamelCase : Optional[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_dummy_inputs() __lowerCamelCase : Any = pipe(**a ).images __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) __lowerCamelCase : Optional[Any] = np.array([0.6_9_6_4_3, 0.5_8_4_8_4, 0.5_0_3_1_4, 0.5_8_7_6_0, 0.5_5_3_6_8, 0.5_9_6_4_3, 0.5_1_5_2_9, 0.4_1_2_1_7, 0.4_9_0_8_7] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : str = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __lowerCamelCase : Any = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_dummy_inputs() __lowerCamelCase : Optional[int] = pipe(**a ).images __lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __lowerCamelCase : Optional[Any] = np.array([0.6_1_7_3_7, 0.5_4_6_4_2, 0.5_3_1_8_3, 0.5_4_4_6_5, 0.5_2_7_4_2, 0.6_0_5_2_5, 0.4_9_9_6_9, 0.4_0_6_5_5, 0.4_8_1_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _snake_case ( self: Dict ): __lowerCamelCase : Optional[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __lowerCamelCase : Dict = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=a ) # warmup pass to apply optimizations __lowerCamelCase : List[str] = pipe(**self.get_dummy_inputs() ) __lowerCamelCase : str = self.get_dummy_inputs() __lowerCamelCase : Union[str, Any] = pipe(**a ).images __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __lowerCamelCase : List[str] = np.array([0.5_2_7_6_1, 0.5_9_9_7_7, 0.4_9_0_3_3, 0.4_9_6_1_9, 0.5_4_2_8_2, 0.5_0_3_1_1, 0.4_7_6_0_0, 0.4_0_9_1_8, 0.4_5_2_0_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _snake_case ( self: str ): __lowerCamelCase : List[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __lowerCamelCase : Dict = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_dummy_inputs() __lowerCamelCase : Optional[Any] = pipe(**a ).images __lowerCamelCase : str = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __lowerCamelCase : List[Any] = np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _snake_case ( self: Tuple ): __lowerCamelCase : List[str] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __lowerCamelCase : Any = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Any = self.get_dummy_inputs() __lowerCamelCase : Union[str, Any] = pipe(**a ).images __lowerCamelCase : int = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __lowerCamelCase : Optional[Any] = np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _snake_case ( self: str ): __lowerCamelCase : Dict = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __lowerCamelCase : List[str] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = self.get_dummy_inputs() __lowerCamelCase : Dict = pipe(**a ).images __lowerCamelCase : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __lowerCamelCase : Optional[int] = np.array([0.6_5_3_3_1, 0.5_8_2_7_7, 0.4_8_2_0_4, 0.5_6_0_5_9, 0.5_3_6_6_5, 0.5_6_2_3_5, 0.5_0_9_6_9, 0.4_0_0_0_9, 0.4_6_5_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self: Optional[int] ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _snake_case ( self: List[Any] ): __lowerCamelCase : List[Any] = ort.SessionOptions() __lowerCamelCase : Optional[Any] = False return options def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Union[str, Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) __lowerCamelCase : List[Any] = init_image.resize((768, 512) ) # using the PNDM scheduler by default __lowerCamelCase : Optional[int] = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=a , feature_extractor=a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = 'A fantasy landscape, trending on artstation' __lowerCamelCase : Union[str, Any] = np.random.RandomState(0 ) __lowerCamelCase : int = pipe( prompt=a , image=a , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=10 , generator=a , output_type='np' , ) __lowerCamelCase : Optional[Any] = output.images __lowerCamelCase : Any = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __lowerCamelCase : List[Any] = np.array([0.4_9_0_9, 0.5_0_5_9, 0.5_3_7_2, 0.4_6_2_3, 0.4_8_7_6, 0.5_0_4_9, 0.4_8_2_0, 0.4_9_5_6, 0.5_0_1_9] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : str = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) __lowerCamelCase : str = init_image.resize((768, 512) ) __lowerCamelCase : Union[str, Any] = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) __lowerCamelCase : Dict = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=a , safety_checker=a , feature_extractor=a , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = 'A fantasy landscape, trending on artstation' __lowerCamelCase : Optional[int] = np.random.RandomState(0 ) __lowerCamelCase : Optional[Any] = pipe( prompt=a , image=a , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=20 , generator=a , output_type='np' , ) __lowerCamelCase : List[str] = output.images __lowerCamelCase : Any = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __lowerCamelCase : List[str] = np.array([0.8_0_4_3, 0.9_2_6, 0.9_5_8_1, 0.8_1_1_9, 0.8_9_5_4, 0.9_1_3, 0.7_2_0_9, 0.7_4_6_3, 0.7_4_3_1] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
669
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 A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """char""" __snake_case = """bpe""" __snake_case = """wp""" lowercase_ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """char_tokenizer"""] __snake_case = """ViTImageProcessor""" __snake_case = """MgpstrTokenizer""" def __init__( self: int , a: Dict=None , a: Optional[int]=None , **a: List[str] ): __lowerCamelCase : Optional[int] = 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 , ) __lowerCamelCase : Optional[Any] = kwargs.pop('feature_extractor' ) __lowerCamelCase : 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`.' ) __lowerCamelCase : Any = tokenizer __lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('gpt2' ) __lowerCamelCase : int = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: Optional[int]=None , a: List[Any]=None , a: int=None , **a: str ): 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: __lowerCamelCase : Dict = self.image_processor(a , return_tensors=a , **a ) if text is not None: __lowerCamelCase : Dict = self.char_tokenizer(a , return_tensors=a , **a ) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : List[str] = encodings['input_ids'] return inputs def _snake_case ( self: List[str] , a: List[Any] ): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = sequences __lowerCamelCase : List[str] = char_preds.size(0 ) __lowerCamelCase , __lowerCamelCase : str = self._decode_helper(a , 'char' ) __lowerCamelCase , __lowerCamelCase : Optional[int] = self._decode_helper(a , 'bpe' ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = self._decode_helper(a , 'wp' ) __lowerCamelCase : Tuple = [] __lowerCamelCase : List[Any] = [] for i in range(a ): __lowerCamelCase : List[Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowerCamelCase : Optional[int] = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowerCamelCase : Any = scores.index(max(a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowerCamelCase : List[str] = {} __lowerCamelCase : Optional[int] = final_strs __lowerCamelCase : Dict = final_scores __lowerCamelCase : Dict = char_strs __lowerCamelCase : List[Any] = bpe_strs __lowerCamelCase : Tuple = wp_strs return out def _snake_case ( self: int , a: Optional[int] , a: Optional[Any] ): if format == DecodeType.CHARACTER: __lowerCamelCase : Optional[Any] = self.char_decode __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : List[str] = '[s]' elif format == DecodeType.BPE: __lowerCamelCase : Dict = self.bpe_decode __lowerCamelCase : List[str] = 2 __lowerCamelCase : Any = '#' elif format == DecodeType.WORDPIECE: __lowerCamelCase : List[str] = self.wp_decode __lowerCamelCase : int = 102 __lowerCamelCase : Dict = '[SEP]' else: raise ValueError(F'Format {format} is not supported.' ) __lowerCamelCase , __lowerCamelCase : int = [], [] __lowerCamelCase : Tuple = pred_logits.size(0 ) __lowerCamelCase : List[Any] = pred_logits.size(1 ) __lowerCamelCase , __lowerCamelCase : Dict = pred_logits.topk(1 , dim=-1 , largest=a , sorted=a ) __lowerCamelCase : List[str] = preds_index.view(-1 , a )[:, 1:] __lowerCamelCase : Dict = decoder(a ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = torch.nn.functional.softmax(a , dim=2 ).max(dim=2 ) __lowerCamelCase : List[str] = preds_max_prob[:, 1:] for index in range(a ): __lowerCamelCase : str = preds_str[index].find(a ) __lowerCamelCase : Tuple = preds_str[index][:pred_eos] __lowerCamelCase : Any = preds_index[index].cpu().tolist() __lowerCamelCase : Any = pred_index.index(a ) if eos_token in pred_index else -1 __lowerCamelCase : str = preds_max_prob[index][: pred_eos_index + 1] __lowerCamelCase : Union[str, Any] = 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 _snake_case ( self: Tuple , a: Optional[int] ): __lowerCamelCase : Dict = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(a )] return decode_strs def _snake_case ( self: Optional[int] , a: Tuple ): return self.bpe_tokenizer.batch_decode(a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : int = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(a )] return decode_strs
669
1
from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """perceiver""" def __init__( self: List[Any] , a: Any=256 , a: List[str]=1280 , a: Dict=768 , a: Optional[Any]=1 , a: Optional[Any]=26 , a: Any=8 , a: Any=8 , a: Dict=None , a: List[Any]=None , a: Optional[Any]="kv" , a: Union[str, Any]=1 , a: Any=1 , a: str="gelu" , a: Dict=0.1 , a: Dict=0.0_2 , a: Dict=1e-12 , a: Optional[int]=True , a: Any=262 , a: Any=2048 , a: Any=56 , a: Union[str, Any]=[368, 496] , a: Optional[int]=16 , a: List[str]=1920 , a: Any=16 , a: Optional[int]=[1, 16, 224, 224] , **a: str , ): super().__init__(**a ) __lowerCamelCase : Tuple = num_latents __lowerCamelCase : Dict = d_latents __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : str = num_blocks __lowerCamelCase : Any = num_self_attends_per_block __lowerCamelCase : List[str] = num_self_attention_heads __lowerCamelCase : Optional[int] = num_cross_attention_heads __lowerCamelCase : str = qk_channels __lowerCamelCase : Union[str, Any] = v_channels __lowerCamelCase : Optional[int] = cross_attention_shape_for_attention __lowerCamelCase : Optional[int] = self_attention_widening_factor __lowerCamelCase : int = cross_attention_widening_factor __lowerCamelCase : Union[str, Any] = hidden_act __lowerCamelCase : Dict = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = initializer_range __lowerCamelCase : Tuple = layer_norm_eps __lowerCamelCase : Tuple = use_query_residual # masked language modeling attributes __lowerCamelCase : Union[str, Any] = vocab_size __lowerCamelCase : Union[str, Any] = max_position_embeddings # image classification attributes __lowerCamelCase : str = image_size # flow attributes __lowerCamelCase : List[Any] = train_size # multimodal autoencoding attributes __lowerCamelCase : List[str] = num_frames __lowerCamelCase : Tuple = audio_samples_per_frame __lowerCamelCase : Optional[Any] = samples_per_patch __lowerCamelCase : List[str] = output_shape class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : Dict = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('inputs', dynamic_axis), ('attention_mask', dynamic_axis), ] ) @property def _snake_case ( self: Tuple ): return 1e-4 def _snake_case ( self: Optional[Any] , a: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , a: int = -1 , a: int = -1 , a: int = -1 , a: bool = False , a: Optional[TensorType] = None , a: int = 3 , a: int = 40 , a: int = 40 , ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(a , a ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __lowerCamelCase : int = compute_effective_axis_dimension( a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __lowerCamelCase : Optional[Any] = preprocessor.num_special_tokens_to_add(a ) __lowerCamelCase : Optional[Any] = compute_effective_axis_dimension( a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=a ) # Generate dummy inputs according to compute batch and sequence __lowerCamelCase : Union[str, Any] = [' '.join(['a'] ) * seq_length] * batch_size __lowerCamelCase : Tuple = dict(preprocessor(a , return_tensors=a ) ) __lowerCamelCase : Tuple = inputs.pop('input_ids' ) return inputs elif isinstance(a , a ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __lowerCamelCase : Tuple = compute_effective_axis_dimension(a , fixed_dimension=OnnxConfig.default_fixed_batch ) __lowerCamelCase : Tuple = self._generate_dummy_images(a , a , a , a ) __lowerCamelCase : List[Any] = dict(preprocessor(images=a , return_tensors=a ) ) __lowerCamelCase : str = inputs.pop('pixel_values' ) return inputs else: raise ValueError( 'Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.' )
669
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : Optional[int] = TOKENIZER_CLASSES else: __lowerCamelCase : Union[str, Any] = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE__ , tokenizer_name + 'Fast' )} logger.info(f'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : int = TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Optional[int] = True if checkpoint_name is None: __lowerCamelCase : List[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : Optional[Any] = [checkpoint_name] logger.info(f'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(f'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ ) # Save fast tokenizer logger.info(f'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Tuple = checkpoint.split('/' ) __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif add_prefix: __lowerCamelCase : Any = checkpoint __lowerCamelCase : Dict = dump_path else: __lowerCamelCase : List[str] = None __lowerCamelCase : Optional[int] = dump_path logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : List[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : int = file_path.split(SCREAMING_SNAKE_CASE__ )[-1][0] if next_char == "/": __lowerCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = None logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Dict = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ , filename_prefix=SCREAMING_SNAKE_CASE__ ) logger.info(f'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('tokenizer.json' ): os.remove(SCREAMING_SNAKE_CASE__ ) logger.info(f'=> removing {file_name}' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) lowercase_ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
669
1
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ = 100 ): __lowerCamelCase : Union[str, Any] = n * (n + 1) * (2 * n + 1) / 6 __lowerCamelCase : int = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F"""{solution() = }""")
669
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: List[str] ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : List[str] = PegasusTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[Any] ): return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def _snake_case ( self: Tuple , **a: List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[Any] , a: int ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Dict = '</s>' __lowerCamelCase : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a ) , 1103 ) def _snake_case ( self: Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) __lowerCamelCase : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: int ): __lowerCamelCase : Union[str, Any] = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowerCamelCase : Tuple = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' __lowerCamelCase : Optional[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : Optional[Any] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 __lowerCamelCase : int = 'To ensure a smooth flow of bank resolutions.' __lowerCamelCase : Union[str, Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : List[str] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _snake_case ( self: str ): __lowerCamelCase : List[str] = ['This is going to be way too long.' * 150, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : Union[str, Any] = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : List[str] = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. @slow def _snake_case ( self: List[str] ): # fmt: off __lowerCamelCase : Tuple = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: str ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : str = PegasusTokenizer(a , offset=0 , mask_token_sent=a , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[str] ): return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def _snake_case ( self: Union[str, Any] , **a: Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[str] , a: Any ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) __lowerCamelCase : int = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) @require_torch def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = ['This is going to be way too long.' * 1000, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : str = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : Any = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. def _snake_case ( self: Any ): __lowerCamelCase : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) __lowerCamelCase : Dict = self._large_tokenizer(a ).input_ids self.assertListEqual( a , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
669
1
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = { 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'ctc_proj', 'mask_emb': 'masked_spec_embed', } lowercase_ = [ 'ctc_proj', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for attribute in key.split('.' ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models __lowerCamelCase : int = 'lm_head' __lowerCamelCase : Dict = getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if weight_type is not None: __lowerCamelCase : Dict = getattr(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ).shape else: __lowerCamelCase : Dict = hf_pointer.shape assert hf_shape == value.shape, ( f'Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be' f' {value.shape} for {full_name}' ) if weight_type == "weight": __lowerCamelCase : int = value elif weight_type == "weight_g": __lowerCamelCase : str = value elif weight_type == "weight_v": __lowerCamelCase : int = value elif weight_type == "bias": __lowerCamelCase : Tuple = value else: __lowerCamelCase : List[Any] = value logger.info(f'{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.' ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = [] __lowerCamelCase : List[str] = fairseq_model.state_dict() __lowerCamelCase : int = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): __lowerCamelCase : str = False if "conv_layers" in name: load_conv_layer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hf_model.config.feat_extract_norm == 'group' , ) __lowerCamelCase : Optional[int] = True else: for key, mapped_key in MAPPING.items(): __lowerCamelCase : Union[str, Any] = 'unispeech.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: __lowerCamelCase : Tuple = True if "*" in mapped_key: __lowerCamelCase : str = name.split(SCREAMING_SNAKE_CASE__ )[0].split('.' )[-2] __lowerCamelCase : int = mapped_key.replace('*' , SCREAMING_SNAKE_CASE__ ) if "weight_g" in name: __lowerCamelCase : Union[str, Any] = 'weight_g' elif "weight_v" in name: __lowerCamelCase : Optional[int] = 'weight_v' elif "bias" in name: __lowerCamelCase : Dict = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowerCamelCase : Union[str, Any] = 'weight' else: __lowerCamelCase : int = None set_recursively(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) continue if not is_used: unused_weights.append(SCREAMING_SNAKE_CASE__ ) logger.warning(f'Unused weights: {unused_weights}' ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = full_name.split('conv_layers.' )[-1] __lowerCamelCase : int = name.split('.' ) __lowerCamelCase : Union[str, Any] = int(items[0] ) __lowerCamelCase : Dict = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.' ) __lowerCamelCase : Tuple = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.' ) __lowerCamelCase : Any = value logger.info(f'Feat extract conv layer {layer_id} was initialized from {full_name}.' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f'{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was' " found." ) __lowerCamelCase : Dict = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f'{full_name} has size {value.shape}, but' f' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.' ) __lowerCamelCase : Tuple = value logger.info(f'Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.' ) else: unused_weights.append(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=True ): if config_path is not None: __lowerCamelCase : str = UniSpeechConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase : str = UniSpeechConfig() if is_finetuned: if dict_path: __lowerCamelCase : List[str] = Dictionary.load_from_json(SCREAMING_SNAKE_CASE__ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __lowerCamelCase : Any = target_dict.pad_index __lowerCamelCase : Any = target_dict.bos_index __lowerCamelCase : List[Any] = target_dict.eos_index __lowerCamelCase : int = len(target_dict.symbols ) __lowerCamelCase : List[str] = os.path.join(SCREAMING_SNAKE_CASE__ , 'vocab.json' ) if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(SCREAMING_SNAKE_CASE__ ) ) return os.makedirs(SCREAMING_SNAKE_CASE__ , exist_ok=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Union[str, Any] = target_dict.indices # fairseq has the <pad> and <s> switched __lowerCamelCase : Dict = 42 __lowerCamelCase : Union[str, Any] = 43 with open(SCREAMING_SNAKE_CASE__ , 'w' , encoding='utf-8' ) as vocab_handle: json.dump(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Tuple = WavaVecaPhonemeCTCTokenizer( SCREAMING_SNAKE_CASE__ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase : List[Any] = True if config.feat_extract_norm == 'layer' else False __lowerCamelCase : Optional[int] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16_000 , padding_value=0 , do_normalize=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase : int = WavaVecaProcessor(feature_extractor=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Dict = UniSpeechForCTC(SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase : List[Any] = UniSpeechForPreTraining(SCREAMING_SNAKE_CASE__ ) if is_finetuned: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] ), 'w2v_path': checkpoint_path} ) else: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Optional[int] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) __lowerCamelCase : Dict = model[0].eval() recursively_load_weights(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) hf_unispeech.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not' ) lowercase_ = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if density <= 0: raise ValueError('Impossible fluid density' ) if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
669
1
import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants lowercase_ = Mapping[str, np.ndarray] lowercase_ = Mapping[str, Any] # Is a nested dict. lowercase_ = 0.01 @dataclasses.dataclass(frozen=__UpperCamelCase ) class A_ : '''simple docstring''' __snake_case = 42 # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. __snake_case = 42 # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. __snake_case = 42 # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. __snake_case = 42 # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. __snake_case = 42 # [num_res, num_atom_type] # Chain indices for multi-chain predictions __snake_case = None # Optional remark about the protein. Included as a comment in output PDB # files __snake_case = None # Templates used to generate this protein (prediction-only) __snake_case = None # Chain corresponding to each parent __snake_case = None def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = r'(\[[A-Z]+\]\n)' __lowerCamelCase : List[str] = [tag.strip() for tag in re.split(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0] __lowerCamelCase : Iterator[Tuple[str, List[str]]] = zip(tags[0::2] , [l.split('\n' ) for l in tags[1::2]] ) __lowerCamelCase : List[str] = ["N", "CA", "C"] __lowerCamelCase : Tuple = None __lowerCamelCase : Optional[Any] = None __lowerCamelCase : List[Any] = None for g in groups: if "[PRIMARY]" == g[0]: __lowerCamelCase : Any = g[1][0].strip() for i in range(len(SCREAMING_SNAKE_CASE__ ) ): if seq[i] not in residue_constants.restypes: __lowerCamelCase : str = 'X' # FIXME: strings are immutable __lowerCamelCase : Dict = np.array( [residue_constants.restype_order.get(SCREAMING_SNAKE_CASE__ , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: __lowerCamelCase : List[List[float]] = [] for axis in range(3 ): tertiary.append(list(map(SCREAMING_SNAKE_CASE__ , g[1][axis].split() ) ) ) __lowerCamelCase : Dict = np.array(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Union[str, Any] = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: __lowerCamelCase : List[Any] = np.array(list(map({'-': 0, '+': 1}.get , g[1][0].strip() ) ) ) __lowerCamelCase : Any = np.zeros( ( len(SCREAMING_SNAKE_CASE__ ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=SCREAMING_SNAKE_CASE__ , atom_mask=SCREAMING_SNAKE_CASE__ , aatype=SCREAMING_SNAKE_CASE__ , residue_index=np.arange(len(SCREAMING_SNAKE_CASE__ ) ) , b_factors=SCREAMING_SNAKE_CASE__ , ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 0 ): __lowerCamelCase : List[str] = [] __lowerCamelCase : Any = prot.remark if remark is not None: pdb_headers.append(f'REMARK {remark}' ) __lowerCamelCase : str = prot.parents __lowerCamelCase : Any = prot.parents_chain_index if parents is not None and parents_chain_index is not None: __lowerCamelCase : str = [p for i, p in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if i == chain_id] if parents is None or len(SCREAMING_SNAKE_CASE__ ) == 0: __lowerCamelCase : int = ['N/A'] pdb_headers.append(f'PARENT {" ".join(SCREAMING_SNAKE_CASE__ )}' ) return pdb_headers def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[str] = [] __lowerCamelCase : List[str] = pdb_str.split('\n' ) __lowerCamelCase : Optional[Any] = prot.remark if remark is not None: out_pdb_lines.append(f'REMARK {remark}' ) __lowerCamelCase : List[List[str]] if prot.parents is not None and len(prot.parents ) > 0: __lowerCamelCase : Optional[Any] = [] if prot.parents_chain_index is not None: __lowerCamelCase : Dict[str, List[str]] = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(SCREAMING_SNAKE_CASE__ ) , [] ) parent_dict[str(SCREAMING_SNAKE_CASE__ )].append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = max([int(SCREAMING_SNAKE_CASE__ ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): __lowerCamelCase : List[str] = parent_dict.get(str(SCREAMING_SNAKE_CASE__ ) , ['N/A'] ) parents_per_chain.append(SCREAMING_SNAKE_CASE__ ) else: parents_per_chain.append(list(prot.parents ) ) else: __lowerCamelCase : List[str] = [['N/A']] def make_parent_line(SCREAMING_SNAKE_CASE__ ) -> str: return f'PARENT {" ".join(SCREAMING_SNAKE_CASE__ )}' out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) __lowerCamelCase : int = 0 for i, l in enumerate(SCREAMING_SNAKE_CASE__ ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(SCREAMING_SNAKE_CASE__ ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = parents_per_chain[chain_counter] else: __lowerCamelCase : str = ['N/A'] out_pdb_lines.append(make_parent_line(SCREAMING_SNAKE_CASE__ ) ) return "\n".join(SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Optional[int] = residue_constants.restypes + ['X'] def res_atoa(SCREAMING_SNAKE_CASE__ ) -> str: return residue_constants.restype_atoa.get(restypes[r] , 'UNK' ) __lowerCamelCase : Union[str, Any] = residue_constants.atom_types __lowerCamelCase : List[str] = [] __lowerCamelCase : Dict = prot.atom_mask __lowerCamelCase : Any = prot.aatype __lowerCamelCase : str = prot.atom_positions __lowerCamelCase : int = prot.residue_index.astype(np.intaa ) __lowerCamelCase : Optional[int] = prot.b_factors __lowerCamelCase : Optional[int] = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError('Invalid aatypes.' ) __lowerCamelCase : Dict = get_pdb_headers(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: pdb_lines.extend(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = aatype.shape[0] __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : Any = 0 __lowerCamelCase : Any = string.ascii_uppercase __lowerCamelCase : str = None # Add all atom sites. for i in range(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(SCREAMING_SNAKE_CASE__ , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue __lowerCamelCase : Optional[int] = 'ATOM' __lowerCamelCase : List[Any] = atom_name if len(SCREAMING_SNAKE_CASE__ ) == 4 else f' {atom_name}' __lowerCamelCase : Optional[int] = '' __lowerCamelCase : List[Any] = '' __lowerCamelCase : List[str] = 1.00 __lowerCamelCase : Any = atom_name[0] # Protein supports only C, N, O, S, this works. __lowerCamelCase : int = '' __lowerCamelCase : Dict = 'A' if chain_index is not None: __lowerCamelCase : Optional[int] = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! __lowerCamelCase : Optional[Any] = ( f'{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}' f'{res_name_a:>3} {chain_tag:>1}' f'{residue_index[i]:>4}{insertion_code:>1} ' f'{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}' f'{occupancy:>6.2f}{b_factor:>6.2f} ' f'{element:>2}{charge:>2}' ) pdb_lines.append(SCREAMING_SNAKE_CASE__ ) atom_index += 1 __lowerCamelCase : str = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: __lowerCamelCase : List[str] = True __lowerCamelCase : List[str] = chain_index[i + 1] if should_terminate: # Close the chain. __lowerCamelCase : Optional[int] = 'TER' __lowerCamelCase : Union[str, Any] = ( f'{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}' ) pdb_lines.append(SCREAMING_SNAKE_CASE__ ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) pdb_lines.append('END' ) pdb_lines.append('' ) return "\n".join(SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ): return Protein( aatype=features['aatype'] , atom_positions=result['final_atom_positions'] , atom_mask=result['final_atom_mask'] , residue_index=features['residue_index'] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result['final_atom_mask'] ) , chain_index=SCREAMING_SNAKE_CASE__ , remark=SCREAMING_SNAKE_CASE__ , parents=SCREAMING_SNAKE_CASE__ , parents_chain_index=SCREAMING_SNAKE_CASE__ , )
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = 1 __lowerCamelCase : str = 2 while i * i <= n: __lowerCamelCase : int = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def UpperCamelCase__ ( ): __lowerCamelCase : str = 1 __lowerCamelCase : List[str] = 1 while True: i += 1 t_num += i if count_divisors(SCREAMING_SNAKE_CASE__ ) > 500: break return t_num if __name__ == "__main__": print(solution())
669
1
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: List[str] ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : List[str] = PegasusTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[Any] ): return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def _snake_case ( self: Tuple , **a: List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[Any] , a: int ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Dict = '</s>' __lowerCamelCase : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a ) , 1103 ) def _snake_case ( self: Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) __lowerCamelCase : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: int ): __lowerCamelCase : Union[str, Any] = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowerCamelCase : Tuple = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' __lowerCamelCase : Optional[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : Optional[Any] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 __lowerCamelCase : int = 'To ensure a smooth flow of bank resolutions.' __lowerCamelCase : Union[str, Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : List[str] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _snake_case ( self: str ): __lowerCamelCase : List[str] = ['This is going to be way too long.' * 150, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : Union[str, Any] = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : List[str] = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. @slow def _snake_case ( self: List[str] ): # fmt: off __lowerCamelCase : Tuple = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: str ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : str = PegasusTokenizer(a , offset=0 , mask_token_sent=a , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[str] ): return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def _snake_case ( self: Union[str, Any] , **a: Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[str] , a: Any ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) __lowerCamelCase : int = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) @require_torch def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = ['This is going to be way too long.' * 1000, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : str = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : Any = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. def _snake_case ( self: Any ): __lowerCamelCase : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) __lowerCamelCase : Dict = self._large_tokenizer(a ).input_ids self.assertListEqual( a , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
669
import numpy as np class A_ : '''simple docstring''' def __init__( self: Optional[int] ): __lowerCamelCase : int = (0, 0) __lowerCamelCase : List[str] = None __lowerCamelCase : int = 0 __lowerCamelCase : int = 0 __lowerCamelCase : Union[str, Any] = 0 def __eq__( self: Optional[int] , a: List[Any] ): return self.position == cell.position def _snake_case ( self: Any ): print(self.position ) class A_ : '''simple docstring''' def __init__( self: str , a: List[str]=(5, 5) ): __lowerCamelCase : Optional[Any] = np.zeros(a ) __lowerCamelCase : List[str] = world_size[0] __lowerCamelCase : Optional[int] = world_size[1] def _snake_case ( self: List[Any] ): print(self.w ) def _snake_case ( self: Optional[int] , a: str ): __lowerCamelCase : Tuple = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __lowerCamelCase : Optional[int] = cell.position[0] __lowerCamelCase : List[str] = cell.position[1] __lowerCamelCase : Dict = [] for n in neughbour_cord: __lowerCamelCase : Dict = current_x + n[0] __lowerCamelCase : Optional[Any] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __lowerCamelCase : Optional[Any] = Cell() __lowerCamelCase : Any = (x, y) __lowerCamelCase : Dict = cell neighbours.append(a ) return neighbours def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = [] __lowerCamelCase : int = [] _open.append(SCREAMING_SNAKE_CASE__ ) while _open: __lowerCamelCase : Union[str, Any] = np.argmin([n.f for n in _open] ) __lowerCamelCase : int = _open[min_f] _closed.append(_open.pop(SCREAMING_SNAKE_CASE__ ) ) if current == goal: break for n in world.get_neigbours(SCREAMING_SNAKE_CASE__ ): for c in _closed: if c == n: continue __lowerCamelCase : Optional[int] = current.g + 1 __lowerCamelCase , __lowerCamelCase : int = n.position __lowerCamelCase , __lowerCamelCase : Tuple = goal.position __lowerCamelCase : Dict = (ya - ya) ** 2 + (xa - xa) ** 2 __lowerCamelCase : str = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [] while current.parent is not None: path.append(current.position ) __lowerCamelCase : int = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowercase_ = Gridworld() # Start position and goal lowercase_ = Cell() lowercase_ = (0, 0) lowercase_ = Cell() lowercase_ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowercase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowercase_ = 1 print(world.w)
669
1
import math import flax.linen as nn import jax.numpy as jnp def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 1 , SCREAMING_SNAKE_CASE__ = 1 , SCREAMING_SNAKE_CASE__ = 1.0e4 , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = 1.0 , ): assert timesteps.ndim == 1, "Timesteps should be a 1d-array" assert embedding_dim % 2 == 0, f'Embedding dimension {embedding_dim} should be even' __lowerCamelCase : int = float(embedding_dim // 2 ) __lowerCamelCase : int = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift) __lowerCamelCase : str = min_timescale * jnp.exp(jnp.arange(SCREAMING_SNAKE_CASE__ , dtype=jnp.floataa ) * -log_timescale_increment ) __lowerCamelCase : List[str] = jnp.expand_dims(SCREAMING_SNAKE_CASE__ , 1 ) * jnp.expand_dims(SCREAMING_SNAKE_CASE__ , 0 ) # scale embeddings __lowerCamelCase : Optional[Any] = scale * emb if flip_sin_to_cos: __lowerCamelCase : List[Any] = jnp.concatenate([jnp.cos(SCREAMING_SNAKE_CASE__ ), jnp.sin(SCREAMING_SNAKE_CASE__ )] , axis=1 ) else: __lowerCamelCase : Optional[Any] = jnp.concatenate([jnp.sin(SCREAMING_SNAKE_CASE__ ), jnp.cos(SCREAMING_SNAKE_CASE__ )] , axis=1 ) __lowerCamelCase : List[str] = jnp.reshape(SCREAMING_SNAKE_CASE__ , [jnp.shape(SCREAMING_SNAKE_CASE__ )[0], embedding_dim] ) return signal class A_ ( nn.Module ): '''simple docstring''' __snake_case = 32 __snake_case = jnp.floataa @nn.compact def __call__( self: Tuple , a: int ): __lowerCamelCase : Any = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_1' )(a ) __lowerCamelCase : int = nn.silu(a ) __lowerCamelCase : List[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='linear_2' )(a ) return temb class A_ ( nn.Module ): '''simple docstring''' __snake_case = 32 __snake_case = False __snake_case = 1 @nn.compact def __call__( self: int , a: str ): return get_sinusoidal_embeddings( a , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
669
import math from datetime import datetime, timedelta def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = year % 19 __lowerCamelCase : int = year % 4 __lowerCamelCase : Any = year % 7 __lowerCamelCase : Dict = math.floor(year / 100 ) __lowerCamelCase : str = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCamelCase : Optional[int] = leap_day_inhibits / 4 __lowerCamelCase : str = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCamelCase : Optional[Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCamelCase : Optional[int] = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __lowerCamelCase : Tuple = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 18 ) else: return datetime(SCREAMING_SNAKE_CASE__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): lowercase_ = 'will be' if year > datetime.now().year else 'was' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
669
1
from random import randint from tempfile import TemporaryFile import numpy as np def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = 0 if start < end: __lowerCamelCase : Tuple = randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : str = a[end] __lowerCamelCase : str = a[pivot] __lowerCamelCase : Tuple = temp __lowerCamelCase , __lowerCamelCase : List[Any] = _in_place_partition(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , p - 1 ) count += _in_place_quick_sort(SCREAMING_SNAKE_CASE__ , p + 1 , SCREAMING_SNAKE_CASE__ ) return count def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Dict = randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = a[end] __lowerCamelCase : Tuple = a[pivot] __lowerCamelCase : Optional[int] = temp __lowerCamelCase : List[str] = start - 1 for index in range(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value __lowerCamelCase : Optional[int] = new_pivot_index + 1 __lowerCamelCase : Optional[int] = a[new_pivot_index] __lowerCamelCase : Optional[Any] = a[index] __lowerCamelCase : List[str] = temp __lowerCamelCase : str = a[new_pivot_index + 1] __lowerCamelCase : int = a[end] __lowerCamelCase : Union[str, Any] = temp return new_pivot_index + 1, count lowercase_ = TemporaryFile() lowercase_ = 1_0_0 # 1000 elements are to be sorted lowercase_ ,lowercase_ = 0, 1 # mean and standard deviation lowercase_ = np.random.normal(mu, sigma, p) np.save(outfile, X) print('The array is') print(X) outfile.seek(0) # using the same array lowercase_ = np.load(outfile) lowercase_ = len(M) - 1 lowercase_ = _in_place_quick_sort(M, 0, r) print( 'No of Comparisons for 100 elements selected from a standard normal distribution' 'is :' ) print(z)
669
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch 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_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' __snake_case = 1 @register_to_config def __init__( self: str , a: str=2000 , a: List[str]=0.1 , a: Any=20 , a: Dict=1e-3 ): __lowerCamelCase : Dict = None __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = None def _snake_case ( self: int , a: str , a: Union[str, torch.device] = None ): __lowerCamelCase : int = torch.linspace(1 , self.config.sampling_eps , a , device=a ) def _snake_case ( self: List[Any] , a: Union[str, Any] , a: Tuple , a: Optional[Any] , a: Dict=None ): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __lowerCamelCase : Tuple = ( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __lowerCamelCase : Optional[int] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __lowerCamelCase : Optional[Any] = std.flatten() while len(std.shape ) < len(score.shape ): __lowerCamelCase : List[str] = std.unsqueeze(-1 ) __lowerCamelCase : Any = -score / std # compute __lowerCamelCase : List[Any] = -1.0 / len(self.timesteps ) __lowerCamelCase : Any = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __lowerCamelCase : Dict = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __lowerCamelCase : int = beta_t.unsqueeze(-1 ) __lowerCamelCase : Any = -0.5 * beta_t * x __lowerCamelCase : List[Any] = torch.sqrt(a ) __lowerCamelCase : Tuple = drift - diffusion**2 * score __lowerCamelCase : str = x + drift * dt # add noise __lowerCamelCase : Any = randn_tensor(x.shape , layout=x.layout , generator=a , device=x.device , dtype=x.dtype ) __lowerCamelCase : Any = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self: Optional[int] ): return self.config.num_train_timesteps
669
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) lowercase_ = {'configuration_plbart': ['PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PLBartConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = ['PLBartTokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase_ = [ 'PLBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'PLBartForCausalLM', 'PLBartForConditionalGeneration', 'PLBartForSequenceClassification', 'PLBartModel', 'PLBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys lowercase_ = _LazyModule(__name__, globals()['__file__'], _import_structure)
669
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__ ) if n_element < 1: __lowerCamelCase : str = ValueError('a should be a positive number' ) raise my_error __lowerCamelCase : Tuple = [1] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = (0, 0, 0) __lowerCamelCase : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowercase_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') lowercase_ = hamming(int(n)) print('-----------------------------------------------------') print(F"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
669
1
import pytest import datasets # Import fixture modules as plugins lowercase_ = ['tests.fixtures.files', 'tests.fixtures.hub', 'tests.fixtures.fsspec'] def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # Mark tests as "unit" by default if not marked as "integration" (or already marked as "unit") for item in items: if any(marker in item.keywords for marker in ['integration', 'unit'] ): continue item.add_marker(pytest.mark.unit ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): config.addinivalue_line('markers' , 'torchaudio_latest: mark test to run with torchaudio>=0.12' ) @pytest.fixture(autouse=SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): # test_hf_cache_home = tmp_path_factory.mktemp("cache") # TODO: why a cache dir per test function does not work? __lowerCamelCase : Optional[Any] = tmp_path_factory.getbasetemp() / 'cache' __lowerCamelCase : Any = test_hf_cache_home / 'datasets' __lowerCamelCase : Optional[int] = test_hf_cache_home / 'metrics' __lowerCamelCase : List[Any] = test_hf_cache_home / 'modules' monkeypatch.setattr('datasets.config.HF_DATASETS_CACHE' , str(SCREAMING_SNAKE_CASE__ ) ) monkeypatch.setattr('datasets.config.HF_METRICS_CACHE' , str(SCREAMING_SNAKE_CASE__ ) ) monkeypatch.setattr('datasets.config.HF_MODULES_CACHE' , str(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : Union[str, Any] = test_hf_datasets_cache / 'downloads' monkeypatch.setattr('datasets.config.DOWNLOADED_DATASETS_PATH' , str(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase : Optional[int] = test_hf_datasets_cache / 'downloads' / 'extracted' monkeypatch.setattr('datasets.config.EXTRACTED_DATASETS_PATH' , str(SCREAMING_SNAKE_CASE__ ) ) @pytest.fixture(autouse=SCREAMING_SNAKE_CASE__ , scope='session' ) def UpperCamelCase__ ( ): datasets.disable_progress_bar() @pytest.fixture(autouse=SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): # don't take tests into account when counting downloads monkeypatch.setattr('datasets.config.HF_UPDATE_DOWNLOAD_COUNTS' , SCREAMING_SNAKE_CASE__ ) @pytest.fixture def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): # Required to suppress RemovedIn20Warning when feature(s) are not compatible with SQLAlchemy 2.0 # To be removed once SQLAlchemy 2.0 supported monkeypatch.setattr('sqlalchemy.util.deprecations.SILENCE_UBER_WARNING' , SCREAMING_SNAKE_CASE__ )
669
import unittest from knapsack import greedy_knapsack as kp class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: List[Any] ): __lowerCamelCase : str = [10, 20, 30, 40, 50, 60] __lowerCamelCase : List[str] = [2, 4, 6, 8, 10, 12] __lowerCamelCase : Tuple = 100 self.assertEqual(kp.calc_profit(a , a , a ) , 210 ) def _snake_case ( self: str ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'Weight can not be negative.' ) def _snake_case ( self: Dict ): self.assertRaisesRegex(a , 'Profit can not be negative.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: Any ): self.assertRaisesRegex( a , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
669
1
import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin class A_ ( unittest.TestCase , __UpperCamelCase ): '''simple docstring''' def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Tuple = load_tool('text-classification' ) self.tool.setup() __lowerCamelCase : Any = load_tool('text-classification' , remote=a ) def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : List[Any] = self.tool('That\'s quite cool' , ['positive', 'negative'] ) self.assertEqual(a , 'positive' ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.remote_tool('That\'s quite cool' , ['positive', 'negative'] ) self.assertEqual(a , 'positive' ) def _snake_case ( self: Dict ): __lowerCamelCase : Optional[int] = self.tool(text='That\'s quite cool' , labels=['positive', 'negative'] ) self.assertEqual(a , 'positive' ) def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = self.remote_tool(text='That\'s quite cool' , labels=['positive', 'negative'] ) self.assertEqual(a , 'positive' )
669
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any]=2 , a: str=3 , a: Any=4 , a: Union[str, Any]=2 , a: Tuple=7 , a: int=True , a: Tuple=True , a: List[str]=True , a: Union[str, Any]=True , a: str=99 , a: Tuple=36 , a: int=2 , a: Dict=4 , a: Union[str, Any]=37 , a: List[str]="gelu" , a: List[Any]=0.1 , a: Optional[int]=0.1 , a: Dict=512 , a: Union[str, Any]=16 , a: str=2 , a: int=0.0_2 , a: Optional[Any]=6 , a: Optional[int]=6 , a: Dict=3 , a: Optional[Any]=4 , a: Optional[Any]=None , a: Dict=1000 , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Optional[int] = num_channels __lowerCamelCase : str = image_size __lowerCamelCase : int = patch_size __lowerCamelCase : List[str] = is_training __lowerCamelCase : Dict = use_input_mask __lowerCamelCase : Any = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : str = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : List[Any] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : int = type_sequence_label_size __lowerCamelCase : List[str] = initializer_range __lowerCamelCase : List[str] = coordinate_size __lowerCamelCase : int = shape_size __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : int = num_choices __lowerCamelCase : int = scope __lowerCamelCase : Any = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __lowerCamelCase : Any = text_seq_length __lowerCamelCase : Optional[Any] = (image_size // patch_size) ** 2 + 1 __lowerCamelCase : Any = self.text_seq_length + self.image_seq_length def _snake_case ( self: List[str] ): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __lowerCamelCase : int = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __lowerCamelCase : List[str] = bbox[i, j, 3] __lowerCamelCase : str = bbox[i, j, 1] __lowerCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __lowerCamelCase : Tuple = bbox[i, j, 2] __lowerCamelCase : Any = bbox[i, j, 0] __lowerCamelCase : List[str] = tmp_coordinate __lowerCamelCase : str = tf.constant(a ) __lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.text_seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __lowerCamelCase : Dict = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self: Tuple , a: List[Any] , a: Any , a: List[str] , a: Dict , a: Optional[Any] , a: Dict ): __lowerCamelCase : Optional[Any] = TFLayoutLMvaModel(config=a ) # text + image __lowerCamelCase : Optional[Any] = model(a , pixel_values=a , training=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , training=a , ) __lowerCamelCase : List[Any] = model(a , bbox=a , pixel_values=a , training=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __lowerCamelCase : List[Any] = model(a , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __lowerCamelCase : Optional[Any] = model({'pixel_values': pixel_values} , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self: Dict , a: Dict , a: Optional[Any] , a: int , a: Optional[int] , a: List[str] , a: List[str] , a: List[str] ): __lowerCamelCase : List[str] = self.num_labels __lowerCamelCase : str = TFLayoutLMvaForSequenceClassification(config=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any] , a: Dict , a: Optional[Any] , a: Tuple , a: Optional[Any] , a: List[Any] ): __lowerCamelCase : Union[str, Any] = self.num_labels __lowerCamelCase : Any = TFLayoutLMvaForTokenClassification(config=a ) __lowerCamelCase : Optional[Any] = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self: Dict , a: Optional[Any] , a: str , a: Dict , a: Union[str, Any] , a: List[Any] , a: Optional[int] , a: List[str] ): __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Any = TFLayoutLMvaForQuestionAnswering(config=a ) __lowerCamelCase : Any = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , training=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] ): __lowerCamelCase : str = self.prepare_config_and_inputs() ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : List[Any] = config_and_inputs __lowerCamelCase : Tuple = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: int , a: List[str] , a: Any , a: Optional[Any] , a: Tuple , a: Tuple ): return True def _snake_case ( self: str , a: Any , a: Any , a: Optional[int]=False ): __lowerCamelCase : List[str] = copy.deepcopy(a ) if model_class in get_values(a ): __lowerCamelCase : Tuple = { k: tf.tile(tf.expand_dims(a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a ): __lowerCamelCase : Any = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Dict = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def _snake_case ( self: Tuple ): __lowerCamelCase : int = TFLayoutLMvaModelTester(self ) __lowerCamelCase : str = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self: Union[str, Any] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : int = model_class(a ) if getattr(a , 'hf_compute_loss' , a ): # The number of elements in the loss should be the same as the number of elements in the label __lowerCamelCase : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : int = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=a )[0] ] __lowerCamelCase : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __lowerCamelCase : Optional[int] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : Dict = prepared_for_class.pop('input_ids' ) __lowerCamelCase : str = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __lowerCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : List[str] = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __lowerCamelCase : int = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __lowerCamelCase : Tuple = -100 __lowerCamelCase : Tuple = tf.convert_to_tensor(a ) __lowerCamelCase : Tuple = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __lowerCamelCase : int = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : str = model(a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __lowerCamelCase : str = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) # Get keys that were added with the _prepare_for_class function __lowerCamelCase : Optional[Any] = prepared_for_class.keys() - inputs_dict.keys() __lowerCamelCase : List[Any] = inspect.signature(model.call ).parameters __lowerCamelCase : List[str] = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __lowerCamelCase : Optional[int] = {0: 'input_ids'} for label_key in label_keys: __lowerCamelCase : Dict = signature_names.index(a ) __lowerCamelCase : str = label_key __lowerCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __lowerCamelCase : Optional[int] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __lowerCamelCase : Optional[int] = prepared_for_class[value] __lowerCamelCase : Any = tuple(a ) # Send to model __lowerCamelCase : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def _snake_case ( self: List[str] ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: int ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: Dict ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( a , a , a , a , a , a , a ) @slow def _snake_case ( self: int ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Dict = TFLayoutLMvaModel.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self: Optional[int] ): return LayoutLMvaImageProcessor(apply_ocr=a ) if is_vision_available() else None @slow def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Tuple = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __lowerCamelCase : Union[str, Any] = self.default_image_processor __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : str = image_processor(images=a , return_tensors='tf' ).pixel_values __lowerCamelCase : Union[str, Any] = tf.constant([[1, 2]] ) __lowerCamelCase : str = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __lowerCamelCase : int = model(input_ids=a , bbox=a , pixel_values=a , training=a ) # verify the logits __lowerCamelCase : Optional[int] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , a ) __lowerCamelCase : Any = tf.constant( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-4 ) )
669
1
import gzip import hashlib import json import multiprocessing import os import re import shutil import time from pathlib import Path import numpy as np from arguments import PreprocessingArguments from datasets import load_dataset from minhash_deduplication import deduplicate_dataset from transformers import AutoTokenizer, HfArgumentParser lowercase_ = re.compile(R'\s+') def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): return {"hash": hashlib.mda(re.sub(SCREAMING_SNAKE_CASE__ , '' , example['content'] ).encode('utf-8' ) ).hexdigest()} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Any = [len(SCREAMING_SNAKE_CASE__ ) for line in example['content'].splitlines()] return {"line_mean": np.mean(SCREAMING_SNAKE_CASE__ ), "line_max": max(SCREAMING_SNAKE_CASE__ )} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = np.mean([c.isalnum() for c in example['content']] ) return {"alpha_frac": alpha_frac} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if example["hash"] in uniques: uniques.remove(example['hash'] ) return True else: return False def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=5 ): __lowerCamelCase : str = ['auto-generated', 'autogenerated', 'automatically generated'] __lowerCamelCase : int = example['content'].splitlines() for _, line in zip(range(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ): for keyword in keywords: if keyword in line.lower(): return {"autogenerated": True} else: return {"autogenerated": False} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=5 , SCREAMING_SNAKE_CASE__=0.05 ): __lowerCamelCase : Any = ['unit tests', 'test file', 'configuration file'] __lowerCamelCase : List[Any] = example['content'].splitlines() __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Any = 0 # first test for _, line in zip(range(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ): for keyword in keywords: if keyword in line.lower(): return {"config_or_test": True} # second test __lowerCamelCase : Any = example['content'].count('\n' ) __lowerCamelCase : str = int(coeff * nlines ) for line in lines: count_config += line.lower().count('config' ) count_test += line.lower().count('test' ) if count_config > threshold or count_test > threshold: return {"config_or_test": True} return {"config_or_test": False} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[str] = ['def ', 'class ', 'for ', 'while '] __lowerCamelCase : List[Any] = example['content'].splitlines() for line in lines: for keyword in keywords: if keyword in line.lower(): return {"has_no_keywords": False} return {"has_no_keywords": True} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=4 ): __lowerCamelCase : Optional[int] = example['content'].splitlines() __lowerCamelCase : List[Any] = 0 for line in lines: counter += line.lower().count('=' ) if counter > minimum: return {"has_few_assignments": False} return {"has_few_assignments": True} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = tokenizer(example['content'] , truncation=SCREAMING_SNAKE_CASE__ )['input_ids'] __lowerCamelCase : str = len(example['content'] ) / len(SCREAMING_SNAKE_CASE__ ) return {"ratio": ratio} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = {} results.update(get_hash(SCREAMING_SNAKE_CASE__ ) ) results.update(line_stats(SCREAMING_SNAKE_CASE__ ) ) results.update(alpha_stats(SCREAMING_SNAKE_CASE__ ) ) results.update(char_token_ratio(SCREAMING_SNAKE_CASE__ ) ) results.update(is_autogenerated(SCREAMING_SNAKE_CASE__ ) ) results.update(is_config_or_test(SCREAMING_SNAKE_CASE__ ) ) results.update(has_no_keywords(SCREAMING_SNAKE_CASE__ ) ) results.update(has_few_assignments(SCREAMING_SNAKE_CASE__ ) ) return results def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if not check_uniques(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): return False elif example["autogenerated"]: return False elif example["line_max"] > args.line_max: return False elif example["line_mean"] > args.line_mean: return False elif example["alpha_frac"] < args.alpha_frac: return False elif example["ratio"] < args.min_token_ratio: return False elif example["config_or_test"] and np.random.rand() <= args.filter_proba: return False elif example["has_no_keywords"] and np.random.rand() <= args.filter_proba: return False elif example["has_few_assignments"]: return False else: return True def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): with open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f_in: with gzip.open(str(SCREAMING_SNAKE_CASE__ ) + '.gz' , 'wb' , compresslevel=6 ) as f_out: shutil.copyfileobj(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) os.unlink(SCREAMING_SNAKE_CASE__ ) # Settings lowercase_ = HfArgumentParser(PreprocessingArguments) lowercase_ = parser.parse_args() if args.num_workers is None: lowercase_ = multiprocessing.cpu_count() lowercase_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) # Load dataset lowercase_ = time.time() lowercase_ = load_dataset(args.dataset_name, split='train') print(F"""Time to load dataset: {time.time()-t_start:.2f}""") # Run preprocessing lowercase_ = time.time() lowercase_ = ds.map(preprocess, num_proc=args.num_workers) print(F"""Time to preprocess dataset: {time.time()-t_start:.2f}""") # Deduplicate hashes lowercase_ = set(ds.unique('hash')) lowercase_ = len(uniques) / len(ds) print(F"""Fraction of duplicates: {1-frac:.2%}""") # Deduplicate data and apply heuristics lowercase_ = time.time() lowercase_ = ds.filter(filter, fn_kwargs={'uniques': uniques, 'args': args}) print(F"""Time to filter dataset: {time.time()-t_start:.2f}""") print(F"""Size of filtered dataset: {len(ds_filter)}""") # Deduplicate with minhash and jaccard similarity if args.near_deduplication: lowercase_ = time.time() lowercase_ ,lowercase_ = deduplicate_dataset(ds_filter, args.jaccard_threshold) print(F"""Time to deduplicate dataset: {time.time()-t_start:.2f}""") print(F"""Size of deduplicate dataset: {len(ds_filter)}""") # Save data in batches of samples_per_file lowercase_ = Path(args.output_dir) output_dir.mkdir(exist_ok=True) # save duplicate_clusters in the output_dir as artifacts # not sure it is the right place the save it if args.near_deduplication: with open(output_dir / 'duplicate_clusters.json', 'w') as f: json.dump(duplicate_clusters, f) lowercase_ = output_dir / 'data' data_dir.mkdir(exist_ok=True) lowercase_ = time.time() for file_number, index in enumerate(range(0, len(ds_filter), args.samples_per_file)): lowercase_ = str(data_dir / F"""file-{file_number+1:012}.json""") lowercase_ = min(len(ds_filter), index + args.samples_per_file) ds_filter.select(list(range(index, end_index))).to_json(file_path) compress_file(file_path) print(F"""Time to save dataset: {time.time()-t_start:.2f}""")
669
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = CLIPTokenizer __snake_case = CLIPTokenizerFast __snake_case = True __snake_case = {} __snake_case = False def _snake_case ( self: Union[str, Any] ): super().setUp() # fmt: off __lowerCamelCase : Any = ['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 __lowerCamelCase : Tuple = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : List[Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>'] __lowerCamelCase : Tuple = {'unk_token': '<unk>'} __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : 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(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: Tuple , **a: Union[str, Any] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Union[str, Any] , **a: List[str] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : Tuple = 'lower newer' __lowerCamelCase : Tuple = 'lower newer' return input_text, output_text def _snake_case ( self: List[str] ): __lowerCamelCase : List[Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase : Optional[Any] = 'lower newer' __lowerCamelCase : int = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>'] __lowerCamelCase : Optional[int] = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : int = tokens + [tokenizer.unk_token] __lowerCamelCase : int = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def _snake_case ( self: Union[str, Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[Any] = self.tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : int = self.rust_tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : str = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.' __lowerCamelCase : Optional[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[Any] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __lowerCamelCase : List[Any] = 'xa\u0303y' + ' ' + 'x\xe3y' __lowerCamelCase : Tuple = tokenizer_s.tokenize(a ) __lowerCamelCase : Any = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type __lowerCamelCase : List[Any] = [ '\u0009', # (horizontal tab, '\t') '\u000B', # (vertical tab) '\u000C', # (form feed) '\u0020', # (space, ' ') '\u200E', # (left-to-right mark):w '\u200F', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __lowerCamelCase : List[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[int] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type __lowerCamelCase : str = [ '\u000A', # (line feed, '\n') '\r\n', # (carriage return and line feed, '\r\n') '\u000D', # (carriage return, '\r') '\r', # (carriage return, '\r') '\u000D', # (carriage return, '\r') '\u2028', # (line separator) '\u2029', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __lowerCamelCase : Dict = tokenizer_s.tokenize(a ) __lowerCamelCase : List[str] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def _snake_case ( self: List[Any] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : Optional[int] = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` __lowerCamelCase : Optional[int] = F'{text_of_1_token} {text_of_1_token}' __lowerCamelCase : Dict = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) __lowerCamelCase : List[Any] = F' {text}' __lowerCamelCase : str = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def _snake_case ( self: str ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def _snake_case ( self: Tuple ): super().test_tokenization_python_rust_equals() def _snake_case ( self: Tuple ): # CLIP always lower cases letters pass
669
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowercase_ = logging.get_logger(__name__) lowercase_ = { 'SenseTime/deformable-detr': 'https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json', # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """deformable_detr""" __snake_case = { """hidden_size""": """d_model""", """num_attention_heads""": """encoder_attention_heads""", } def __init__( self: Tuple , a: Optional[Any]=True , a: Optional[int]=None , a: List[str]=3 , a: Dict=300 , a: str=1024 , a: Union[str, Any]=6 , a: List[Any]=1024 , a: Optional[int]=8 , a: List[str]=6 , a: Dict=1024 , a: Dict=8 , a: Optional[int]=0.0 , a: List[Any]=True , a: List[Any]="relu" , a: Any=256 , a: Tuple=0.1 , a: int=0.0 , a: Any=0.0 , a: List[Any]=0.0_2 , a: Optional[Any]=1.0 , a: List[str]=True , a: Optional[int]=False , a: Tuple="sine" , a: int="resnet50" , a: Any=True , a: Any=False , a: Union[str, Any]=4 , a: Any=4 , a: List[str]=4 , a: Tuple=False , a: Optional[Any]=300 , a: Optional[int]=False , a: Dict=1 , a: Optional[int]=5 , a: int=2 , a: Union[str, Any]=1 , a: Dict=1 , a: Optional[int]=5 , a: Dict=2 , a: Optional[Any]=0.1 , a: Union[str, Any]=0.2_5 , a: Dict=False , **a: List[Any] , ): 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 : Optional[Any] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(a , a ): __lowerCamelCase : str = backbone_config.get('model_type' ) __lowerCamelCase : Dict = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase : Any = config_class.from_dict(a ) __lowerCamelCase : Tuple = use_timm_backbone __lowerCamelCase : Any = backbone_config __lowerCamelCase : Dict = num_channels __lowerCamelCase : Optional[Any] = num_queries __lowerCamelCase : Tuple = max_position_embeddings __lowerCamelCase : List[Any] = d_model __lowerCamelCase : List[Any] = encoder_ffn_dim __lowerCamelCase : int = encoder_layers __lowerCamelCase : Tuple = encoder_attention_heads __lowerCamelCase : Tuple = decoder_ffn_dim __lowerCamelCase : List[str] = decoder_layers __lowerCamelCase : Optional[int] = decoder_attention_heads __lowerCamelCase : Union[str, Any] = dropout __lowerCamelCase : List[str] = attention_dropout __lowerCamelCase : int = activation_dropout __lowerCamelCase : List[str] = activation_function __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Optional[Any] = init_xavier_std __lowerCamelCase : Optional[int] = encoder_layerdrop __lowerCamelCase : int = auxiliary_loss __lowerCamelCase : Any = position_embedding_type __lowerCamelCase : Tuple = backbone __lowerCamelCase : Any = use_pretrained_backbone __lowerCamelCase : int = dilation # deformable attributes __lowerCamelCase : Optional[Any] = num_feature_levels __lowerCamelCase : str = encoder_n_points __lowerCamelCase : Optional[int] = decoder_n_points __lowerCamelCase : int = two_stage __lowerCamelCase : Tuple = two_stage_num_proposals __lowerCamelCase : Tuple = with_box_refine if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher __lowerCamelCase : str = class_cost __lowerCamelCase : Optional[Any] = bbox_cost __lowerCamelCase : Dict = giou_cost # Loss coefficients __lowerCamelCase : Optional[int] = mask_loss_coefficient __lowerCamelCase : Union[str, Any] = dice_loss_coefficient __lowerCamelCase : List[str] = bbox_loss_coefficient __lowerCamelCase : Any = giou_loss_coefficient __lowerCamelCase : List[str] = eos_coefficient __lowerCamelCase : List[str] = focal_alpha __lowerCamelCase : Dict = disable_custom_kernels super().__init__(is_encoder_decoder=a , **a ) @property def _snake_case ( self: Union[str, Any] ): return self.encoder_attention_heads @property def _snake_case ( self: str ): return self.d_model def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: __lowerCamelCase : Union[str, Any] = self.backbone_config.to_dict() __lowerCamelCase : int = self.__class__.model_type return output
669
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowercase_ = False try: lowercase_ = _is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class A_ : '''simple docstring''' def __init__( self: int , a: str = None , a: list = [] ): __lowerCamelCase : Dict = 0 __lowerCamelCase : Dict = choices __lowerCamelCase : Tuple = prompt if sys.platform == "win32": __lowerCamelCase : Union[str, Any] = '*' else: __lowerCamelCase : Any = '➔ ' def _snake_case ( self: Any , a: Tuple , a: str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def _snake_case ( self: Tuple , a: int ): if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def _snake_case ( self: Optional[int] , a: Direction , a: int = 1 ): __lowerCamelCase : str = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['up'] ) def _snake_case ( self: Tuple ): self.move_direction(Direction.UP ) @input.mark(KEYMAP['down'] ) def _snake_case ( self: Optional[int] ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['newline'] ) def _snake_case ( self: str ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) return self.position @input.mark(KEYMAP['interrupt'] ) def _snake_case ( self: Union[str, Any] ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def _snake_case ( self: str ): __lowerCamelCase : List[Any] = int(chr(self.current_selection ) ) __lowerCamelCase : Any = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def _snake_case ( self: str , a: int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , '\n' ) if in_colab: forceWrite('Please input a choice index (starting from 0), and press enter' , '\n' ) else: forceWrite('Please select a choice using the arrow or number keys, and selecting with enter' , '\n' ) __lowerCamelCase : Dict = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('\n' ) move_cursor(len(self.choices ) - self.position , 'UP' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase : Any = int(builtins.input() ) except ValueError: __lowerCamelCase : str = default_choice else: __lowerCamelCase : Optional[int] = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , 'UP' ) clear_line() self.write_choice(a , '\n' ) return choice
669
1
from math import ceil from typing import List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, spectrogram, window_function from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor from ...utils import TensorType, logging lowercase_ = logging.get_logger(__name__) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""audio_values""", """audio_mask"""] def __init__( self: Any , a: str=2048 , a: List[Any]=1 , a: int=[16, 16] , a: str=128 , a: int=4_4100 , a: str=86 , a: Any=2048 , a: Optional[int]=0.0 , **a: Any , ): super().__init__( feature_size=a , sampling_rate=a , padding_value=a , **a , ) __lowerCamelCase : List[str] = spectrogram_length __lowerCamelCase : Optional[Any] = num_channels __lowerCamelCase : str = patch_size __lowerCamelCase : int = feature_size // self.patch_size[1] __lowerCamelCase : Optional[int] = n_fft __lowerCamelCase : Optional[Any] = sampling_rate // hop_length_to_sampling_rate __lowerCamelCase : Union[str, Any] = sampling_rate __lowerCamelCase : Optional[int] = padding_value __lowerCamelCase : List[Any] = mel_filter_bank( num_frequency_bins=1 + n_fft // 2 , num_mel_filters=a , min_frequency=0.0 , max_frequency=2_2_0_5_0.0 , sampling_rate=a , norm='slaney' , mel_scale='slaney' , ).T def _snake_case ( self: List[str] , a: np.array ): __lowerCamelCase : Optional[int] = spectrogram( a , window_function(self.n_fft , 'hann' ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel='dB' , db_range=8_0.0 , ) __lowerCamelCase : List[Any] = log_spec[:, :-1] __lowerCamelCase : List[str] = log_spec - 2_0.0 __lowerCamelCase : Any = np.clip(log_spec / 4_0.0 , -2.0 , 0.0 ) + 1.0 return log_spec def __call__( self: Dict , a: Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , a: Optional[Union[str, TensorType]] = None , a: Optional[bool] = True , a: Optional[int] = None , a: bool = False , a: bool = False , **a: Optional[Any] , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( 'This feature extractor is set to support sampling rate' F' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled' F' 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 : int = isinstance(a , 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 : List[str] = is_batched_numpy or ( isinstance(a , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: __lowerCamelCase : Union[str, Any] = [np.asarray([speech] , dtype=np.floataa ).T for speech in raw_speech] elif not is_batched and not isinstance(a , np.ndarray ): __lowerCamelCase : Optional[int] = np.asarray(a , dtype=np.floataa ) elif isinstance(a , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ): __lowerCamelCase : int = raw_speech.astype(np.floataa ) # always return batch if not is_batched: __lowerCamelCase : Any = [np.asarray([raw_speech] ).T] # Convert audio signals to log mel spectrograms, truncate by time axis __lowerCamelCase : Optional[int] = [ self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech ] if isinstance(audio_features[0] , a ): __lowerCamelCase : Union[str, Any] = [np.asarray(a , dtype=np.floataa ) for feature in audio_features] # Create audio attention mask __lowerCamelCase : int = max( [ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch if return_attention_mask: __lowerCamelCase : Optional[int] = [ (ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1] + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0] for feature in audio_features ] __lowerCamelCase : Any = np.array(a ).astype(np.floataa ) # convert into correct format for padding __lowerCamelCase : Any = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch __lowerCamelCase : Tuple = np.ones([len(a ), 1, max_time_len, self.feature_size] ).astype(np.floataa ) __lowerCamelCase : int = padded_audio_features * self.padding_value for i in range(len(a ) ): __lowerCamelCase : Any = audio_features[i] __lowerCamelCase : Any = feature # return as BatchFeature if return_attention_mask: __lowerCamelCase : Union[str, Any] = {'audio_values': padded_audio_features, 'audio_mask': audio_mask} else: __lowerCamelCase : Dict = {'audio_values': padded_audio_features} __lowerCamelCase : str = BatchFeature(data=a , tensor_type=a ) return encoded_inputs
669
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = (CMStochasticIterativeScheduler,) __snake_case = 10 def _snake_case ( self: Any , **a: Dict ): __lowerCamelCase : Optional[Any] = { 'num_train_timesteps': 201, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } config.update(**a ) return config def _snake_case ( self: List[Any] ): __lowerCamelCase : Any = 10 __lowerCamelCase : Any = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = self.scheduler_classes[0](**a ) scheduler.set_timesteps(a ) __lowerCamelCase : Any = scheduler.timesteps[0] __lowerCamelCase : List[str] = scheduler.timesteps[1] __lowerCamelCase : Union[str, Any] = self.dummy_sample __lowerCamelCase : int = 0.1 * sample __lowerCamelCase : Optional[Any] = scheduler.step(a , a , a ).prev_sample __lowerCamelCase : List[str] = scheduler.step(a , a , a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self: Optional[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a ) def _snake_case ( self: List[str] ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=a ) def _snake_case ( self: Tuple ): __lowerCamelCase : Tuple = self.scheduler_classes[0] __lowerCamelCase : Tuple = self.get_scheduler_config() __lowerCamelCase : Tuple = scheduler_class(**a ) __lowerCamelCase : int = 1 scheduler.set_timesteps(a ) __lowerCamelCase : Optional[int] = scheduler.timesteps __lowerCamelCase : List[str] = torch.manual_seed(0 ) __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(a ): # 1. scale model input __lowerCamelCase : List[str] = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Optional[int] = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : str = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : str = pred_prev_sample __lowerCamelCase : List[str] = torch.sum(torch.abs(a ) ) __lowerCamelCase : str = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**a ) __lowerCamelCase : List[Any] = [106, 0] scheduler.set_timesteps(timesteps=a ) __lowerCamelCase : Dict = scheduler.timesteps __lowerCamelCase : int = torch.manual_seed(0 ) __lowerCamelCase : Any = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __lowerCamelCase : Tuple = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Tuple = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : Any = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : Any = pred_prev_sample __lowerCamelCase : Dict = torch.sum(torch.abs(a ) ) __lowerCamelCase : Optional[Any] = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : int = self.get_scheduler_config() __lowerCamelCase : List[Any] = scheduler_class(**a ) __lowerCamelCase : Optional[Any] = [39, 30, 12, 15, 0] with self.assertRaises(a , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=a ) def _snake_case ( self: int ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Union[str, Any] = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [39, 30, 12, 1, 0] __lowerCamelCase : List[Any] = len(a ) with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=a , timesteps=a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Dict = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=a )
669
1
import csv import tweepy # Twitter API credentials lowercase_ = '' lowercase_ = '' lowercase_ = '' lowercase_ = '' def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): # authorize twitter, initialize tweepy __lowerCamelCase : int = tweepy.OAuthHandler(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) auth.set_access_token(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Any = tweepy.API(SCREAMING_SNAKE_CASE__ ) # initialize a list to hold all the tweepy Tweets __lowerCamelCase : int = [] # make initial request for most recent tweets (200 is the maximum allowed count) __lowerCamelCase : List[Any] = api.user_timeline(screen_name=SCREAMING_SNAKE_CASE__ , count=200 ) # save most recent tweets alltweets.extend(SCREAMING_SNAKE_CASE__ ) # save the id of the oldest tweet less one __lowerCamelCase : str = alltweets[-1].id - 1 # keep grabbing tweets until there are no tweets left to grab while len(SCREAMING_SNAKE_CASE__ ) > 0: print(f'getting tweets before {oldest}' ) # all subsequent requests use the max_id param to prevent duplicates __lowerCamelCase : Tuple = api.user_timeline( screen_name=SCREAMING_SNAKE_CASE__ , count=200 , max_id=SCREAMING_SNAKE_CASE__ ) # save most recent tweets alltweets.extend(SCREAMING_SNAKE_CASE__ ) # update the id of the oldest tweet less one __lowerCamelCase : Any = alltweets[-1].id - 1 print(f'...{len(SCREAMING_SNAKE_CASE__ )} tweets downloaded so far' ) # transform the tweepy tweets into a 2D array that will populate the csv __lowerCamelCase : Union[str, Any] = [[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 : Tuple = csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['id', 'created_at', 'text'] ) writer.writerows(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": # pass in the username of the account you want to download get_all_tweets('FirePing32')
669
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") lowercase_ = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find('meta', {'property': 'og:image'})['content'] lowercase_ = requests.get(image_url).content lowercase_ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
669
1
import datasets import faiss import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch from elia_utils import ( embed_questions_for_retrieval, make_qa_sas_model, qa_sas_generate, query_es_index, query_qa_dense_index, ) import transformers from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer lowercase_ = 'bart' lowercase_ = True @st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( ): if LOAD_DENSE_INDEX: __lowerCamelCase : Optional[int] = AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased' ) __lowerCamelCase : Optional[Any] = AutoModel.from_pretrained('yjernite/retribert-base-uncased' ).to('cuda:0' ) __lowerCamelCase : Any = qar_model.eval() else: __lowerCamelCase , __lowerCamelCase : Optional[int] = (None, None) if MODEL_TYPE == "bart": __lowerCamelCase : Any = AutoTokenizer.from_pretrained('yjernite/bart_eli5' ) __lowerCamelCase : Dict = AutoModelForSeqaSeqLM.from_pretrained('yjernite/bart_eli5' ).to('cuda:0' ) __lowerCamelCase : str = torch.load('seq2seq_models/eli5_bart_model_blm_2.pth' ) sas_model.load_state_dict(save_dict['model'] ) __lowerCamelCase : Any = sas_model.eval() else: __lowerCamelCase , __lowerCamelCase : Union[str, Any] = make_qa_sas_model( model_name='t5-small' , from_file='seq2seq_models/eli5_t5_model_1024_4.pth' , device='cuda:0' ) return (qar_tokenizer, qar_model, sas_tokenizer, sas_model) @st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( ): if LOAD_DENSE_INDEX: __lowerCamelCase : str = faiss.StandardGpuResources() __lowerCamelCase : Tuple = datasets.load_dataset(path='wiki_snippets' , name='wiki40b_en_100_0' )['train'] __lowerCamelCase : Tuple = np.memmap( 'wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat' , dtype='float32' , mode='r' , shape=(wikiaab_passages.num_rows, 128) , ) __lowerCamelCase : Tuple = faiss.IndexFlatIP(128 ) __lowerCamelCase : Union[str, Any] = faiss.index_cpu_to_gpu(SCREAMING_SNAKE_CASE__ , 1 , SCREAMING_SNAKE_CASE__ ) wikiaab_gpu_index_flat.add(SCREAMING_SNAKE_CASE__ ) # TODO fix for larger GPU else: __lowerCamelCase , __lowerCamelCase : Union[str, Any] = (None, None) __lowerCamelCase : str = Elasticsearch([{'host': 'localhost', 'port': '9200'}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE__ ) def UpperCamelCase__ ( ): __lowerCamelCase : Dict = datasets.load_dataset('eli5' , name='LFQA_reddit' ) __lowerCamelCase : Dict = elia['train_eli5'] __lowerCamelCase : str = np.memmap( 'eli5_questions_reps.dat' , dtype='float32' , mode='r' , shape=(elia_train.num_rows, 128) ) __lowerCamelCase : Union[str, Any] = faiss.IndexFlatIP(128 ) eli5_train_q_index.add(SCREAMING_SNAKE_CASE__ ) return (elia_train, eli5_train_q_index) lowercase_ ,lowercase_ ,lowercase_ = load_indexes() lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ = load_models() lowercase_ ,lowercase_ = load_train_data() def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=10 ): __lowerCamelCase : Union[str, Any] = embed_questions_for_retrieval([question] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase : Tuple = eli5_train_q_index.search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Union[str, Any] = [elia_train[int(SCREAMING_SNAKE_CASE__ )] for i in I[0]] return nn_examples def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__="wiki40b" , SCREAMING_SNAKE_CASE__="dense" , SCREAMING_SNAKE_CASE__=10 ): if source == "none": __lowerCamelCase , __lowerCamelCase : List[Any] = (' <P> '.join(['' for _ in range(11 )] ).strip(), []) else: if method == "dense": __lowerCamelCase , __lowerCamelCase : List[Any] = query_qa_dense_index( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase , __lowerCamelCase : int = query_es_index( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index_name='english_wiki40b_snippets_100w' , n_results=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase : Dict = [ (res['article_title'], res['section_title'].strip(), res['score'], res['passage_text']) for res in hit_lst ] __lowerCamelCase : int = 'question: {} context: {}'.format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return question_doc, support_list @st.cache( hash_funcs={ torch.Tensor: (lambda SCREAMING_SNAKE_CASE__ : None), transformers.models.bart.tokenization_bart.BartTokenizer: (lambda SCREAMING_SNAKE_CASE__ : None), } ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=64 , SCREAMING_SNAKE_CASE__=256 , SCREAMING_SNAKE_CASE__=False , SCREAMING_SNAKE_CASE__=2 , SCREAMING_SNAKE_CASE__=0.95 , SCREAMING_SNAKE_CASE__=0.8 ): with torch.no_grad(): __lowerCamelCase : Dict = qa_sas_generate( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , num_answers=1 , num_beams=SCREAMING_SNAKE_CASE__ , min_len=SCREAMING_SNAKE_CASE__ , max_len=SCREAMING_SNAKE_CASE__ , do_sample=SCREAMING_SNAKE_CASE__ , temp=SCREAMING_SNAKE_CASE__ , top_p=SCREAMING_SNAKE_CASE__ , top_k=SCREAMING_SNAKE_CASE__ , max_input_length=1_024 , device='cuda:0' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar lowercase_ = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' lowercase_ = '\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class="img-container"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n' % ( header_html, ) st.sidebar.markdown( header_full, unsafe_allow_html=True, ) # Long Form QA with ELI5 and Wikipedia lowercase_ = '\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n' st.sidebar.markdown(description, unsafe_allow_html=True) lowercase_ = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] lowercase_ = st.sidebar.checkbox('Demo options') if demo_options: lowercase_ = st.sidebar.selectbox( '', action_list, index=3, ) lowercase_ = action_list.index(action_st) lowercase_ = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) lowercase_ = show_type == 'Show full text of passages' else: lowercase_ = 3 lowercase_ = True lowercase_ = st.sidebar.checkbox('Retrieval options') if retrieval_options: lowercase_ = '\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n ' st.sidebar.markdown(retriever_info) lowercase_ = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) lowercase_ = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: lowercase_ = 'wiki40b' lowercase_ = 'dense' lowercase_ = 'beam' lowercase_ = 2 lowercase_ = 6_4 lowercase_ = 2_5_6 lowercase_ = None lowercase_ = None lowercase_ = st.sidebar.checkbox('Generation options') if generate_options: lowercase_ = '\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder\'s output probabilities.\n ' st.sidebar.markdown(generate_info) lowercase_ = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) lowercase_ = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=2_5_6, value=6_4, step=8, format=None, key=None ) lowercase_ = st.sidebar.slider( 'Maximum generation length', min_value=6_4, max_value=5_1_2, value=2_5_6, step=1_6, format=None, key=None ) if sampled == "beam": lowercase_ = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: lowercase_ = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) lowercase_ = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) lowercase_ = None # start main text lowercase_ = [ '<MY QUESTION>', 'How do people make chocolate?', 'Why do we get a fever when we are sick?', 'How can different animals perceive different colors?', 'What is natural language processing?', 'What\'s the best way to treat a sunburn?', 'What exactly are vitamins ?', 'How does nuclear energy provide electricity?', 'What\'s the difference between viruses and bacteria?', 'Why are flutes classified as woodwinds when most of them are made out of metal ?', 'Why do people like drinking coffee even though it tastes so bad?', 'What happens when wine ages? How does it make the wine taste better?', 'If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?', 'How can we set a date to the beginning or end of an artistic period? Doesn\'t the change happen gradually?', 'How does New Zealand have so many large bird predators?', ] lowercase_ = st.selectbox( 'What would you like to ask? ---- select <MY QUESTION> to enter a new query', questions_list, index=1, ) if question_s == "<MY QUESTION>": lowercase_ = st.text_input('Enter your question here:', '') else: lowercase_ = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": lowercase_ ,lowercase_ = make_support(question, source=wiki_source, method='dense', n_results=1_0) lowercase_ ,lowercase_ = make_support(question, source=wiki_source, method='sparse', n_results=1_0) lowercase_ = [] for res_d, res_s in zip(support_list_dense, support_list_sparse): if tuple(res_d) not in support_list: support_list += [tuple(res_d)] if tuple(res_s) not in support_list: support_list += [tuple(res_s)] lowercase_ = support_list[:1_0] lowercase_ = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: lowercase_ ,lowercase_ = make_support(question, source=wiki_source, method=index_type, n_results=1_0) if action in [0, 3]: lowercase_ ,lowercase_ = answer_question( question_doc, sas_model, sas_tokenizer, min_len=min_len, max_len=int(max_len), sampling=(sampled == 'sampled'), n_beams=n_beams, top_p=top_p, temp=temp, ) st.markdown('### The model generated answer is:') st.write(answer) if action in [0, 1, 3] and wiki_source != "none": st.markdown('--- \n ### The model is drawing information from the following Wikipedia passages:') for i, res in enumerate(support_list): lowercase_ = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) lowercase_ = res[1].strip() if sec_titles == "": lowercase_ = '[{}]({})'.format(res[0], wiki_url) else: lowercase_ = sec_titles.split(' & ') lowercase_ = ' & '.join( ['[{}]({}#{})'.format(sec.strip(), wiki_url, sec.strip().replace(' ', '_')) for sec in sec_list] ) st.markdown( '{0:02d} - **Article**: {1:<18} <br> _Section_: {2}'.format(i + 1, res[0], sections), unsafe_allow_html=True, ) if show_passages: st.write( '> <span style="font-family:arial; font-size:10pt;">' + res[-1] + '</span>', unsafe_allow_html=True ) if action in [2, 3]: lowercase_ = find_nearest_training(question) lowercase_ = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) lowercase_ = [ '{}. {}'.format(i + 1, ' \n'.join([line.strip() for line in ans.split('\n') if line.strip() != ''])) for i, (ans, sc) in enumerate(zip(train_exple['answers']['text'], train_exple['answers']['score'])) if i == 0 or sc > 2 ] st.markdown('##### Its answers were: \n\n {}'.format('\n'.join(answers_st))) lowercase_ = '\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n' st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
669
import os try: from .build_directory_md import good_file_paths except ImportError: from build_directory_md import good_file_paths # type: ignore lowercase_ = list(good_file_paths()) assert filepaths, "good_file_paths() failed!" lowercase_ = [file for file in filepaths if file != file.lower()] if upper_files: print(F"""{len(upper_files)} files contain uppercase characters:""") print('\n'.join(upper_files) + '\n') lowercase_ = [file for file in filepaths if ' ' in file] if space_files: print(F"""{len(space_files)} files contain space characters:""") print('\n'.join(space_files) + '\n') lowercase_ = [file for file in filepaths if '-' in file] if hyphen_files: print(F"""{len(hyphen_files)} files contain hyphen characters:""") print('\n'.join(hyphen_files) + '\n') lowercase_ = [file for file in filepaths if os.sep not in file] if nodir_files: print(F"""{len(nodir_files)} files are not in a directory:""") print('\n'.join(nodir_files) + '\n') lowercase_ = len(upper_files + space_files + hyphen_files + nodir_files) if bad_files: import sys sys.exit(bad_files)
669
1
from __future__ import annotations import csv import requests from bsa import BeautifulSoup def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ = "" ): __lowerCamelCase : List[Any] = url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250' __lowerCamelCase : List[Any] = BeautifulSoup(requests.get(SCREAMING_SNAKE_CASE__ ).text , 'html.parser' ) __lowerCamelCase : Any = soup.find_all('td' , attrs='titleColumn' ) __lowerCamelCase : Any = soup.find_all('td' , class_='ratingColumn imdbRating' ) return { title.a.text: float(rating.strong.text ) for title, rating in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) } def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ = "IMDb_Top_250_Movies.csv" ): __lowerCamelCase : Union[str, Any] = get_imdb_top_aaa_movies() with open(SCREAMING_SNAKE_CASE__ , 'w' , newline='' ) as out_file: __lowerCamelCase : Union[str, Any] = csv.writer(SCREAMING_SNAKE_CASE__ ) writer.writerow(['Movie title', 'IMDb rating'] ) for title, rating in movies.items(): writer.writerow([title, rating] ) if __name__ == "__main__": write_movies()
669
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_ = { 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json' ), } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """xlm-roberta""" def __init__( self: Optional[Any] , a: int=3_0522 , a: List[Any]=768 , a: Tuple=12 , a: List[str]=12 , a: Dict=3072 , a: List[str]="gelu" , a: Any=0.1 , a: Optional[Any]=0.1 , a: str=512 , a: Optional[int]=2 , a: int=0.0_2 , a: str=1e-12 , a: str=1 , a: List[Any]=0 , a: Dict=2 , a: Dict="absolute" , a: List[Any]=True , a: str=None , **a: List[Any] , ): super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a ) __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Optional[Any] = hidden_size __lowerCamelCase : Dict = num_hidden_layers __lowerCamelCase : List[str] = num_attention_heads __lowerCamelCase : str = hidden_act __lowerCamelCase : Dict = intermediate_size __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : int = max_position_embeddings __lowerCamelCase : Any = type_vocab_size __lowerCamelCase : int = initializer_range __lowerCamelCase : Optional[Any] = layer_norm_eps __lowerCamelCase : List[Any] = position_embedding_type __lowerCamelCase : List[str] = use_cache __lowerCamelCase : Optional[int] = classifier_dropout class A_ ( __UpperCamelCase ): '''simple docstring''' @property def _snake_case ( self: Optional[Any] ): if self.task == "multiple-choice": __lowerCamelCase : int = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __lowerCamelCase : List[str] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
669
1
import inspect import unittest from transformers import ViTMSNConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTMSNForImageClassification, ViTMSNModel from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCamelCase_ : def __init__( self , __lowerCAmelCase , __lowerCAmelCase=1_3 , __lowerCAmelCase=3_0 , __lowerCAmelCase=2 , __lowerCAmelCase=3 , __lowerCAmelCase=True , __lowerCAmelCase=True , __lowerCAmelCase=3_2 , __lowerCAmelCase=5 , __lowerCAmelCase=4 , __lowerCAmelCase=3_7 , __lowerCAmelCase="gelu" , __lowerCAmelCase=0.1 , __lowerCAmelCase=0.1 , __lowerCAmelCase=1_0 , __lowerCAmelCase=0.02 , __lowerCAmelCase=None , ): """simple docstring""" __magic_name__ :Tuple = parent __magic_name__ :Dict = batch_size __magic_name__ :Optional[int] = image_size __magic_name__ :Optional[Any] = patch_size __magic_name__ :int = num_channels __magic_name__ :Union[str, Any] = is_training __magic_name__ :Optional[Any] = use_labels __magic_name__ :str = hidden_size __magic_name__ :Optional[int] = num_hidden_layers __magic_name__ :Optional[Any] = num_attention_heads __magic_name__ :Optional[Any] = intermediate_size __magic_name__ :str = hidden_act __magic_name__ :Tuple = hidden_dropout_prob __magic_name__ :Optional[int] = attention_probs_dropout_prob __magic_name__ :int = type_sequence_label_size __magic_name__ :Optional[int] = initializer_range __magic_name__ :Any = scope # in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __magic_name__ :Tuple = (image_size // patch_size) ** 2 __magic_name__ :int = num_patches + 1 def A ( self ): """simple docstring""" __magic_name__ :Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __magic_name__ :List[Any] = None if self.use_labels: __magic_name__ :Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ :str = self.get_config() return config, pixel_values, labels def A ( self ): """simple docstring""" return ViTMSNConfig( 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 , initializer_range=self.initializer_range , ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Optional[Any] = ViTMSNModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() __magic_name__ :Union[str, Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def A ( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ): """simple docstring""" __magic_name__ :Tuple = self.type_sequence_label_size __magic_name__ :List[str] = ViTMSNForImageClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() __magic_name__ :Union[str, Any] = model(__lowerCAmelCase , labels=__lowerCAmelCase ) print('''Pixel and labels shape: {pixel_values.shape}, {labels.shape}''' ) print('''Labels: {labels}''' ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __magic_name__ :Optional[int] = 1 __magic_name__ :Any = ViTMSNForImageClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() __magic_name__ :Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __magic_name__ :Dict = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def A ( self ): """simple docstring""" __magic_name__ :int = self.prepare_config_and_inputs() __magic_name__ , __magic_name__ , __magic_name__ :Union[str, Any] = config_and_inputs __magic_name__ :int = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCamelCase_ ( lowerCamelCase , lowerCamelCase , unittest.TestCase ): a__ = (ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else () a__ = ( {'''feature-extraction''': ViTMSNModel, '''image-classification''': ViTMSNForImageClassification} if is_torch_available() else {} ) a__ = False a__ = False a__ = False a__ = False def A ( self ): """simple docstring""" __magic_name__ :Tuple = ViTMSNModelTester(self ) __magic_name__ :Any = ConfigTester(self , config_class=__lowerCAmelCase , has_text_modality=__lowerCAmelCase , hidden_size=3_7 ) def A ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMSN does not use inputs_embeds''' ) def A ( self ): """simple docstring""" pass def A ( self ): """simple docstring""" __magic_name__ , __magic_name__ :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __magic_name__ :int = model_class(__lowerCAmelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __magic_name__ :Optional[Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__lowerCAmelCase , nn.Linear ) ) def A ( self ): """simple docstring""" __magic_name__ , __magic_name__ :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __magic_name__ :Union[str, Any] = model_class(__lowerCAmelCase ) __magic_name__ :List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __magic_name__ :List[str] = [*signature.parameters.keys()] __magic_name__ :str = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def A ( self ): """simple docstring""" __magic_name__ :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase ) @slow def A ( self ): """simple docstring""" for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ :str = ViTMSNModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) def __lowercase ( ): """simple docstring""" __magic_name__ :Optional[int] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCamelCase_ ( unittest.TestCase ): @cached_property def A ( self ): """simple docstring""" return ViTImageProcessor.from_pretrained('''facebook/vit-msn-small''' ) if is_vision_available() else None @slow def A ( self ): """simple docstring""" torch.manual_seed(2 ) __magic_name__ :int = ViTMSNForImageClassification.from_pretrained('''facebook/vit-msn-small''' ).to(__lowerCAmelCase ) __magic_name__ :Any = self.default_image_processor __magic_name__ :Dict = prepare_img() __magic_name__ :Any = image_processor(images=__lowerCAmelCase , return_tensors='''pt''' ).to(__lowerCAmelCase ) # forward pass with torch.no_grad(): __magic_name__ :Tuple = model(**__lowerCAmelCase ) # verify the logits __magic_name__ :Union[str, Any] = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , __lowerCAmelCase ) __magic_name__ :Tuple = torch.tensor([-0.0803, -0.4454, -0.2375] ).to(__lowerCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __lowerCAmelCase , atol=1E-4 ) )
0
import gc import unittest import numpy as np import torch from torch.backends.cuda import sdp_kernel from diffusers import ( CMStochasticIterativeScheduler, ConsistencyModelPipeline, UNetaDModel, ) from diffusers.utils import randn_tensor, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ConsistencyModelPipeline __snake_case = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __snake_case = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS # Override required_optional_params to remove num_images_per_prompt __snake_case = frozenset( [ """num_inference_steps""", """generator""", """latents""", """output_type""", """return_dict""", """callback""", """callback_steps""", ] ) @property def _snake_case ( self: str ): __lowerCamelCase : Tuple = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet' , ) return unet @property def _snake_case ( self: Tuple ): __lowerCamelCase : List[str] = UNetaDModel.from_pretrained( 'diffusers/consistency-models-test' , subfolder='test_unet_class_cond' , ) return unet def _snake_case ( self: int , a: str=False ): if class_cond: __lowerCamelCase : str = self.dummy_cond_unet else: __lowerCamelCase : str = self.dummy_uncond_unet # Default to CM multistep sampler __lowerCamelCase : Tuple = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, } return components def _snake_case ( self: int , a: List[str] , a: Any=0 ): if str(a ).startswith('mps' ): __lowerCamelCase : List[Any] = torch.manual_seed(a ) else: __lowerCamelCase : Tuple = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : Optional[Any] = { 'batch_size': 1, 'num_inference_steps': None, 'timesteps': [22, 0], 'generator': generator, 'output_type': 'np', } return inputs def _snake_case ( self: Optional[Any] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components() __lowerCamelCase : str = ConsistencyModelPipeline(**a ) __lowerCamelCase : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Any = self.get_dummy_inputs(a ) __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Dict = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[int] = ConsistencyModelPipeline(**a ) __lowerCamelCase : Any = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Union[str, Any] = self.get_dummy_inputs(a ) __lowerCamelCase : Tuple = 0 __lowerCamelCase : List[str] = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : Dict = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: Optional[int] ): __lowerCamelCase : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : Optional[int] = self.get_dummy_components() __lowerCamelCase : Tuple = ConsistencyModelPipeline(**a ) __lowerCamelCase : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : Tuple = self.get_dummy_inputs(a ) __lowerCamelCase : str = 1 __lowerCamelCase : Optional[int] = None __lowerCamelCase : Any = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[int] = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def _snake_case ( self: List[str] ): __lowerCamelCase : int = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase : List[Any] = self.get_dummy_components(class_cond=a ) __lowerCamelCase : Optional[Any] = ConsistencyModelPipeline(**a ) __lowerCamelCase : List[Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_dummy_inputs(a ) __lowerCamelCase : List[str] = 1 __lowerCamelCase : List[str] = None __lowerCamelCase : str = 0 __lowerCamelCase : Tuple = pipe(**a ).images assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Any ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self: Optional[int] , a: str=0 , a: Tuple=False , a: Tuple="cpu" , a: List[str]=torch.floataa , a: Optional[Any]=(1, 3, 64, 64) ): __lowerCamelCase : Optional[Any] = torch.manual_seed(a ) __lowerCamelCase : Optional[int] = { 'num_inference_steps': None, 'timesteps': [22, 0], 'class_labels': 0, 'generator': generator, 'output_type': 'np', } if get_fixed_latents: __lowerCamelCase : Dict = self.get_fixed_latents(seed=a , device=a , dtype=a , shape=a ) __lowerCamelCase : Optional[Any] = latents return inputs def _snake_case ( self: Any , a: Any=0 , a: List[str]="cpu" , a: Optional[Any]=torch.floataa , a: int=(1, 3, 64, 64) ): if type(a ) == str: __lowerCamelCase : Dict = torch.device(a ) __lowerCamelCase : Union[str, Any] = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase : str = randn_tensor(a , generator=a , device=a , dtype=a ) return latents def _snake_case ( self: str ): __lowerCamelCase : Optional[int] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Union[str, Any] = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs() __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Any = np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : int = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : Dict = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : List[str] = self.get_inputs() __lowerCamelCase : Optional[Any] = 1 __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Tuple = np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 @require_torch_a def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : List[Any] = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : int = self.get_inputs(get_fixed_latents=a , device=a ) # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : int = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[Any] = image[0, -3:, -3:, -1] __lowerCamelCase : Optional[Any] = np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 @require_torch_a def _snake_case ( self: Dict ): __lowerCamelCase : Dict = UNetaDModel.from_pretrained('diffusers/consistency_models' , subfolder='diffusers_cd_imagenet64_l2' ) __lowerCamelCase : Any = CMStochasticIterativeScheduler( num_train_timesteps=40 , sigma_min=0.0_0_2 , sigma_max=8_0.0 , ) __lowerCamelCase : str = ConsistencyModelPipeline(unet=a , scheduler=a ) pipe.to(torch_device=a , torch_dtype=torch.floataa ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase : str = self.get_inputs(get_fixed_latents=a , device=a ) __lowerCamelCase : str = 1 __lowerCamelCase : Union[str, Any] = None # Ensure usage of flash attention in torch 2.0 with sdp_kernel(enable_flash=a , enable_math=a , enable_mem_efficient=a ): __lowerCamelCase : Optional[int] = pipe(**a ).images assert image.shape == (1, 64, 64, 3) __lowerCamelCase : str = image[0, -3:, -3:, -1] __lowerCamelCase : str = np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
669
0
def _A ( _lowercase = 1_00 ) -> int: """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 0 for i in range(1 , n + 1 ): sum_of_squares += i**2 sum_of_ints += i return sum_of_ints**2 - sum_of_squares if __name__ == "__main__": print(f"""{solution() = }""")
1
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase_ = logging.get_logger(__name__) lowercase_ = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """trocr""" __snake_case = ["""past_key_values"""] __snake_case = { """num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model""", """num_hidden_layers""": """decoder_layers""", } def __init__( self: Dict , a: List[str]=5_0265 , a: Optional[Any]=1024 , a: Tuple=12 , a: Dict=16 , a: Optional[Any]=4096 , a: Optional[Any]="gelu" , a: Optional[int]=512 , a: int=0.1 , a: str=0.0 , a: Union[str, Any]=0.0 , a: Any=2 , a: Optional[int]=0.0_2 , a: Optional[Any]=0.0 , a: List[Any]=True , a: Any=False , a: int=True , a: Optional[Any]=True , a: Tuple=1 , a: Union[str, Any]=0 , a: Any=2 , **a: List[Any] , ): __lowerCamelCase : Optional[int] = vocab_size __lowerCamelCase : Union[str, Any] = d_model __lowerCamelCase : List[str] = decoder_layers __lowerCamelCase : Optional[Any] = decoder_attention_heads __lowerCamelCase : List[str] = decoder_ffn_dim __lowerCamelCase : Optional[int] = activation_function __lowerCamelCase : Optional[Any] = max_position_embeddings __lowerCamelCase : Dict = dropout __lowerCamelCase : int = attention_dropout __lowerCamelCase : List[str] = activation_dropout __lowerCamelCase : Union[str, Any] = init_std __lowerCamelCase : Tuple = decoder_layerdrop __lowerCamelCase : str = use_cache __lowerCamelCase : List[Any] = scale_embedding __lowerCamelCase : Any = use_learned_position_embeddings __lowerCamelCase : List[Any] = layernorm_embedding super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , decoder_start_token_id=a , **a , )
669
0
UpperCAmelCase_ = { """meter""": """m""", """kilometer""": """km""", """megametre""": """Mm""", """gigametre""": """Gm""", """terametre""": """Tm""", """petametre""": """Pm""", """exametre""": """Em""", """zettametre""": """Zm""", """yottametre""": """Ym""", } # Exponent of the factor(meter) UpperCAmelCase_ = { """m""": 0, """km""": 3, """Mm""": 6, """Gm""": 9, """Tm""": 1_2, """Pm""": 1_5, """Em""": 1_8, """Zm""": 2_1, """Ym""": 2_4, } def SCREAMING_SNAKE_CASE_ ( _snake_case :float , _snake_case :str , _snake_case :str ) -> float: _A = from_type.lower().strip('''s''' ) _A = to_type.lower().strip('''s''' ) _A = UNIT_SYMBOL.get(_snake_case , _snake_case ) _A = UNIT_SYMBOL.get(_snake_case , _snake_case ) if from_sanitized not in METRIC_CONVERSION: _A = ( F'''Invalid \'from_type\' value: {from_type!r}.\n''' F'''Conversion abbreviations are: {', '.join(_snake_case )}''' ) raise ValueError(_snake_case ) if to_sanitized not in METRIC_CONVERSION: _A = ( F'''Invalid \'to_type\' value: {to_type!r}.\n''' F'''Conversion abbreviations are: {', '.join(_snake_case )}''' ) raise ValueError(_snake_case ) _A = METRIC_CONVERSION[from_sanitized] _A = METRIC_CONVERSION[to_sanitized] _A = 1 if from_exponent > to_exponent: _A = from_exponent - to_exponent else: _A = -(to_exponent - from_exponent) return value * pow(10 , _snake_case ) if __name__ == "__main__": from doctest import testmod testmod()
2
import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """tokenizer"""] __snake_case = """CLIPImageProcessor""" __snake_case = ("""XLMRobertaTokenizer""", """XLMRobertaTokenizerFast""") def __init__( self: Union[str, Any] , a: int=None , a: List[str]=None , **a: str ): __lowerCamelCase : int = 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 , ) __lowerCamelCase : str = kwargs.pop('feature_extractor' ) __lowerCamelCase : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: List[Any]=None , a: List[str]=None , a: int=None , **a: List[Any] ): if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: __lowerCamelCase : Dict = self.tokenizer(a , return_tensors=a , **a ) if images is not None: __lowerCamelCase : Tuple = self.image_processor(a , return_tensors=a , **a ) if text is not None and images is not None: __lowerCamelCase : str = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a ) , tensor_type=a ) def _snake_case ( self: List[Any] , *a: Optional[Any] , **a: int ): return self.tokenizer.batch_decode(*a , **a ) def _snake_case ( self: Any , *a: Union[str, Any] , **a: Optional[Any] ): return self.tokenizer.decode(*a , **a ) @property def _snake_case ( self: List[str] ): __lowerCamelCase : Optional[Any] = self.tokenizer.model_input_names __lowerCamelCase : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
669
0
'''simple docstring''' import os import pytest from attr import dataclass lowerCAmelCase : Dict = 'us-east-1' # defaults region @dataclass class SCREAMING_SNAKE_CASE__ : lowerCAmelCase_ = 42 lowerCAmelCase_ = """arn:aws:iam::558105141721:role/sagemaker_execution_role""" lowerCAmelCase_ = { """task_name""": """mnli""", """per_device_train_batch_size""": 16, """per_device_eval_batch_size""": 16, """do_train""": True, """do_eval""": True, """do_predict""": True, """output_dir""": """/opt/ml/model""", """overwrite_output_dir""": True, """max_steps""": 5_00, """save_steps""": 55_00, } lowerCAmelCase_ = {**hyperparameters, """max_steps""": 10_00} @property def UpperCAmelCase_ ( self )-> str: '''simple docstring''' if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def UpperCAmelCase_ ( self )-> str: '''simple docstring''' return F'''{self.framework}-transfromers-test''' @property def UpperCAmelCase_ ( self )-> str: '''simple docstring''' return F'''./tests/sagemaker/scripts/{self.framework}''' @property def UpperCAmelCase_ ( self )-> str: '''simple docstring''' if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class') def A_( A : Optional[int]): UpperCamelCase = SageMakerTestEnvironment(framework=request.cls.framework)
3
import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A_ ( unittest.TestCase ): '''simple docstring''' @property def _snake_case ( self: int ): torch.manual_seed(0 ) __lowerCamelCase : int = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) return model @property def _snake_case ( self: str ): torch.manual_seed(0 ) __lowerCamelCase : Any = VQModel( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=3 , ) return model @property def _snake_case ( self: Dict ): torch.manual_seed(0 ) __lowerCamelCase : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(a ) def _snake_case ( self: List[str] ): __lowerCamelCase : Union[str, Any] = self.dummy_uncond_unet __lowerCamelCase : List[str] = DDIMScheduler() __lowerCamelCase : str = self.dummy_vq_model __lowerCamelCase : Optional[int] = LDMPipeline(unet=a , vqvae=a , scheduler=a ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Optional[int] = torch.manual_seed(0 ) __lowerCamelCase : Any = ldm(generator=a , num_inference_steps=2 , output_type='numpy' ).images __lowerCamelCase : Tuple = torch.manual_seed(0 ) __lowerCamelCase : Dict = ldm(generator=a , num_inference_steps=2 , output_type='numpy' , return_dict=a )[0] __lowerCamelCase : Union[str, Any] = image[0, -3:, -3:, -1] __lowerCamelCase : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase : Optional[int] = np.array([0.8_5_1_2, 0.8_1_8, 0.6_4_1_1, 0.6_8_0_8, 0.4_4_6_5, 0.5_6_1_8, 0.4_6, 0.6_2_3_1, 0.5_1_7_2] ) __lowerCamelCase : str = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < tolerance @slow @require_torch class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: Optional[int] ): __lowerCamelCase : int = LDMPipeline.from_pretrained('CompVis/ldm-celebahq-256' ) ldm.to(a ) ldm.set_progress_bar_config(disable=a ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : int = ldm(generator=a , num_inference_steps=5 , output_type='numpy' ).images __lowerCamelCase : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __lowerCamelCase : List[Any] = np.array([0.4_3_9_9, 0.4_4_9_7_5, 0.4_6_8_2_5, 0.4_7_4, 0.4_3_5_9, 0.4_5_8_1, 0.4_5_0_9_5, 0.4_3_4_1, 0.4_4_4_7] ) __lowerCamelCase : Union[str, Any] = 1e-2 if torch_device != 'mps' else 3e-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
669
0
"""simple docstring""" def _SCREAMING_SNAKE_CASE (_UpperCAmelCase : int ): if num <= 0: raise ValueError('Input must be a positive integer' ) lowerCAmelCase = [True] * (num + 1) lowerCAmelCase = 2 while p * p <= num: if primes[p]: for i in range(p * p , num + 1 , _UpperCAmelCase ): lowerCAmelCase = False p += 1 return [prime for prime in range(2 , num + 1 ) if primes[prime]] if __name__ == "__main__": import doctest doctest.testmod() __UpperCamelCase : Union[str, Any] = int(input('''Enter a positive integer: ''').strip()) print(prime_sieve_eratosthenes(user_num))
4
import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowercase_ = 'Usage of script: script_name <size_of_canvas:int>' lowercase_ = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = [[False for i in range(SCREAMING_SNAKE_CASE__ )] for j in range(SCREAMING_SNAKE_CASE__ )] return canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): for i, row in enumerate(SCREAMING_SNAKE_CASE__ ): for j, _ in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = bool(random.getrandbits(1 ) ) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = np.array(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[Any] = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(SCREAMING_SNAKE_CASE__ ): for c, pt in enumerate(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : int = __judge_point( SCREAMING_SNAKE_CASE__ , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) __lowerCamelCase : Any = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. __lowerCamelCase : list[list[bool]] = current_canvas.tolist() return return_canvas def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : List[Any] = 0 __lowerCamelCase : Optional[Any] = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. __lowerCamelCase : Tuple = pt if pt: if alive < 2: __lowerCamelCase : Optional[Any] = False elif alive == 2 or alive == 3: __lowerCamelCase : Any = True elif alive > 3: __lowerCamelCase : Dict = False else: if alive == 3: __lowerCamelCase : Tuple = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowercase_ = int(sys.argv[1]) # main working structure of this module. lowercase_ = create_canvas(canvas_size) seed(c) lowercase_ ,lowercase_ = plt.subplots() fig.show() lowercase_ = ListedColormap(['w', 'k']) try: while True: lowercase_ = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
669
0
'''simple docstring''' import heapq import sys import numpy as np _lowercase = tuple[int, int] class UpperCAmelCase_ : '''simple docstring''' def __init__( self ): """simple docstring""" _lowerCAmelCase = [] _lowerCAmelCase = set() def _lowercase ( self ): """simple docstring""" if not self.empty(): return self.elements[0][0] else: return float("""inf""" ) def _lowercase ( self ): """simple docstring""" return len(self.elements ) == 0 def _lowercase ( self , _lowercase , _lowercase ): """simple docstring""" if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(_lowercase ) else: # update # print("update", item) _lowerCAmelCase = [] ((_lowerCAmelCase) , (_lowerCAmelCase)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((_lowerCAmelCase) , (_lowerCAmelCase)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def _lowercase ( self , _lowercase ): """simple docstring""" if item in self.set: self.set.remove(_lowercase ) _lowerCAmelCase = [] ((_lowerCAmelCase) , (_lowerCAmelCase)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((_lowerCAmelCase) , (_lowerCAmelCase)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def _lowercase ( self ): """simple docstring""" return self.elements[0][1] def _lowercase ( self ): """simple docstring""" ((_lowerCAmelCase) , (_lowerCAmelCase)) = heapq.heappop(self.elements ) self.set.remove(_lowercase ) return (priority, item) def A (__lowerCamelCase :TPos , __lowerCamelCase :TPos ): # euclidean distance _lowerCAmelCase = np.array(__lowerCamelCase ) _lowerCAmelCase = np.array(__lowerCamelCase ) return np.linalg.norm(a - b ) def A (__lowerCamelCase :TPos , __lowerCamelCase :TPos ): # integer division by time variable return consistent_heuristic(__lowerCamelCase , __lowerCamelCase ) // t def A (__lowerCamelCase :TPos , __lowerCamelCase :TPos ): # manhattan distance return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def A (__lowerCamelCase :TPos , __lowerCamelCase :int , __lowerCamelCase :TPos , __lowerCamelCase :dict[TPos, float] ): _lowerCAmelCase = g_function[start] + Wa * heuristics[i](__lowerCamelCase , __lowerCamelCase ) return ans def A (__lowerCamelCase :Tuple , __lowerCamelCase :int , __lowerCamelCase :Dict ): _lowerCAmelCase = np.chararray((n, n) ) for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): _lowerCAmelCase = """*""" for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): if (j, (n - 1) - i) in blocks: _lowerCAmelCase = """#""" _lowerCAmelCase = """-""" _lowerCAmelCase = back_pointer[goal] while x != start: ((_lowerCAmelCase) , (_lowerCAmelCase)) = x # print(x) _lowerCAmelCase = """-""" _lowerCAmelCase = back_pointer[x] _lowerCAmelCase = """-""" for i in range(__lowerCamelCase ): for j in range(__lowerCamelCase ): if (i, j) == (0, n - 1): print(grid[i][j] , end=""" """ ) print("""<-- End position""" , end=""" """ ) else: print(grid[i][j] , end=""" """ ) print() print("""^""" ) print("""Start position""" ) print() print("""# is an obstacle""" ) print("""- is the path taken by algorithm""" ) print("""PATH TAKEN BY THE ALGORITHM IS:-""" ) _lowerCAmelCase = back_pointer[goal] while x != start: print(__lowerCamelCase , end=""" """ ) _lowerCAmelCase = back_pointer[x] print(__lowerCamelCase ) sys.exit() def A (__lowerCamelCase :TPos ): if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def A (__lowerCamelCase :str , __lowerCamelCase :Union[str, Any] , __lowerCamelCase :Optional[int] , __lowerCamelCase :str , __lowerCamelCase :Union[str, Any] , __lowerCamelCase :Optional[int] , __lowerCamelCase :Dict , __lowerCamelCase :Union[str, Any] , ): for itera in range(__lowerCamelCase ): open_list[itera].remove_element(__lowerCamelCase ) # print("s", s) # print("j", j) ((_lowerCAmelCase) , (_lowerCAmelCase)) = s _lowerCAmelCase = (x - 1, y) _lowerCAmelCase = (x + 1, y) _lowerCAmelCase = (x, y + 1) _lowerCAmelCase = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(__lowerCamelCase ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(__lowerCamelCase ) _lowerCAmelCase = -1 _lowerCAmelCase = float("""inf""" ) if valid(__lowerCamelCase ) and g_function[neighbours] > g_function[s] + 1: _lowerCAmelCase = g_function[s] + 1 _lowerCAmelCase = s if neighbours not in close_list_anchor: open_list[0].put(__lowerCamelCase , key(__lowerCamelCase , 0 , __lowerCamelCase , __lowerCamelCase ) ) if neighbours not in close_list_inad: for var in range(1 , __lowerCamelCase ): if key(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) <= Wa * key( __lowerCamelCase , 0 , __lowerCamelCase , __lowerCamelCase ): open_list[j].put( __lowerCamelCase , key(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) ) def A (): _lowerCAmelCase = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(15 , 20 ): some_list.append((x, 17) ) for x in range(10 , 19 ): for y in range(1 , 15 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(12 , 19 ): some_list.append((x, y) ) for x in range(3 , 13 ): for y in range(16 , 19 ): some_list.append((x, y) ) return some_list _lowercase = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} _lowercase = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] _lowercase = make_common_ground() _lowercase = blocks_blk # hyper parameters _lowercase = 1 _lowercase = 1 _lowercase = 20 _lowercase = 3 # one consistent and two other inconsistent # start and end destination _lowercase = (0, 0) _lowercase = (n - 1, n - 1) _lowercase = 1 def A (__lowerCamelCase :TPos , __lowerCamelCase :TPos , __lowerCamelCase :int ): _lowerCAmelCase = {start: 0, goal: float("""inf""" )} _lowerCAmelCase = {start: -1, goal: -1} _lowerCAmelCase = [] _lowerCAmelCase = set() for i in range(__lowerCamelCase ): open_list.append(PriorityQueue() ) open_list[i].put(__lowerCamelCase , key(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) ) _lowerCAmelCase = [] _lowerCAmelCase = [] while open_list[0].minkey() < float("""inf""" ): for i in range(1 , __lowerCamelCase ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("""inf""" ): do_something(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) else: _lowerCAmelCase , _lowerCAmelCase = open_list[i].top_show() visited.add(__lowerCamelCase ) expand_state( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) close_list_inad.append(__lowerCamelCase ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("""inf""" ): do_something(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ) else: _lowerCAmelCase = open_list[0].top_show() visited.add(__lowerCamelCase ) expand_state( __lowerCamelCase , 0 , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , ) close_list_anchor.append(__lowerCamelCase ) print("""No path found to goal""" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(__lowerCamelCase ): if (j, i) in blocks: print("""#""" , end=""" """ ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("""*""" , end=""" """ ) else: print("""-""" , end=""" """ ) else: print("""*""" , end=""" """ ) if (j, i) == (n - 1, n - 1): print("""<-- End position""" , end=""" """ ) print() print("""^""" ) print("""Start position""" ) print() print("""# is an obstacle""" ) print("""- is the path taken by algorithm""" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
5
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 A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = """char""" __snake_case = """bpe""" __snake_case = """wp""" lowercase_ = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = ["""image_processor""", """char_tokenizer"""] __snake_case = """ViTImageProcessor""" __snake_case = """MgpstrTokenizer""" def __init__( self: int , a: Dict=None , a: Optional[int]=None , **a: List[str] ): __lowerCamelCase : Optional[int] = 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 , ) __lowerCamelCase : Optional[Any] = kwargs.pop('feature_extractor' ) __lowerCamelCase : 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`.' ) __lowerCamelCase : Any = tokenizer __lowerCamelCase : Union[str, Any] = AutoTokenizer.from_pretrained('gpt2' ) __lowerCamelCase : int = AutoTokenizer.from_pretrained('bert-base-uncased' ) super().__init__(a , a ) def __call__( self: Optional[int] , a: Optional[int]=None , a: List[Any]=None , a: int=None , **a: str ): 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: __lowerCamelCase : Dict = self.image_processor(a , return_tensors=a , **a ) if text is not None: __lowerCamelCase : Dict = self.char_tokenizer(a , return_tensors=a , **a ) if text is None: return inputs elif images is None: return encodings else: __lowerCamelCase : List[str] = encodings['input_ids'] return inputs def _snake_case ( self: List[str] , a: List[Any] ): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : str = sequences __lowerCamelCase : List[str] = char_preds.size(0 ) __lowerCamelCase , __lowerCamelCase : str = self._decode_helper(a , 'char' ) __lowerCamelCase , __lowerCamelCase : Optional[int] = self._decode_helper(a , 'bpe' ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = self._decode_helper(a , 'wp' ) __lowerCamelCase : Tuple = [] __lowerCamelCase : List[Any] = [] for i in range(a ): __lowerCamelCase : List[Any] = [char_scores[i], bpe_scores[i], wp_scores[i]] __lowerCamelCase : Optional[int] = [char_strs[i], bpe_strs[i], wp_strs[i]] __lowerCamelCase : Any = scores.index(max(a ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __lowerCamelCase : List[str] = {} __lowerCamelCase : Optional[int] = final_strs __lowerCamelCase : Dict = final_scores __lowerCamelCase : Dict = char_strs __lowerCamelCase : List[Any] = bpe_strs __lowerCamelCase : Tuple = wp_strs return out def _snake_case ( self: int , a: Optional[int] , a: Optional[Any] ): if format == DecodeType.CHARACTER: __lowerCamelCase : Optional[Any] = self.char_decode __lowerCamelCase : Union[str, Any] = 1 __lowerCamelCase : List[str] = '[s]' elif format == DecodeType.BPE: __lowerCamelCase : Dict = self.bpe_decode __lowerCamelCase : List[str] = 2 __lowerCamelCase : Any = '#' elif format == DecodeType.WORDPIECE: __lowerCamelCase : List[str] = self.wp_decode __lowerCamelCase : int = 102 __lowerCamelCase : Dict = '[SEP]' else: raise ValueError(F'Format {format} is not supported.' ) __lowerCamelCase , __lowerCamelCase : int = [], [] __lowerCamelCase : Tuple = pred_logits.size(0 ) __lowerCamelCase : List[Any] = pred_logits.size(1 ) __lowerCamelCase , __lowerCamelCase : Dict = pred_logits.topk(1 , dim=-1 , largest=a , sorted=a ) __lowerCamelCase : List[str] = preds_index.view(-1 , a )[:, 1:] __lowerCamelCase : Dict = decoder(a ) __lowerCamelCase , __lowerCamelCase : Optional[Any] = torch.nn.functional.softmax(a , dim=2 ).max(dim=2 ) __lowerCamelCase : List[str] = preds_max_prob[:, 1:] for index in range(a ): __lowerCamelCase : str = preds_str[index].find(a ) __lowerCamelCase : Tuple = preds_str[index][:pred_eos] __lowerCamelCase : Any = preds_index[index].cpu().tolist() __lowerCamelCase : Any = pred_index.index(a ) if eos_token in pred_index else -1 __lowerCamelCase : str = preds_max_prob[index][: pred_eos_index + 1] __lowerCamelCase : Union[str, Any] = 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 _snake_case ( self: Tuple , a: Optional[int] ): __lowerCamelCase : Dict = [seq.replace(' ' , '' ) for seq in self.char_tokenizer.batch_decode(a )] return decode_strs def _snake_case ( self: Optional[int] , a: Tuple ): return self.bpe_tokenizer.batch_decode(a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : int = [seq.replace(' ' , '' ) for seq in self.wp_tokenizer.batch_decode(a )] return decode_strs
669
0
from dataclasses import dataclass from typing import Optional import numpy as np import torch import torch.nn as nn from ..utils import BaseOutput, is_torch_version, randn_tensor from .attention_processor import SpatialNorm from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block @dataclass class UpperCamelCase_ ( UpperCamelCase__ ): lowerCamelCase_ = 42 class UpperCamelCase_ ( nn.Module ): def __init__( self :Any , __A :str=3 , __A :List[Any]=3 , __A :str=("DownEncoderBlock2D",) , __A :Optional[int]=(64,) , __A :str=2 , __A :Optional[Any]=32 , __A :int="silu" , __A :List[Any]=True , ) -> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = layers_per_block SCREAMING_SNAKE_CASE__ = torch.nn.Convad( __A , block_out_channels[0] , kernel_size=3 , stride=1 , padding=1 , ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = nn.ModuleList([] ) # down SCREAMING_SNAKE_CASE__ = block_out_channels[0] for i, down_block_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = output_channel SCREAMING_SNAKE_CASE__ = block_out_channels[i] SCREAMING_SNAKE_CASE__ = i == len(__A ) - 1 SCREAMING_SNAKE_CASE__ = get_down_block( __A , num_layers=self.layers_per_block , in_channels=__A , out_channels=__A , add_downsample=not is_final_block , resnet_eps=1E-6 , downsample_padding=0 , resnet_act_fn=__A , resnet_groups=__A , attention_head_dim=__A , temb_channels=__A , ) self.down_blocks.append(__A ) # mid SCREAMING_SNAKE_CASE__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=__A , output_scale_factor=1 , resnet_time_scale_shift="""default""" , attention_head_dim=block_out_channels[-1] , resnet_groups=__A , temb_channels=__A , ) # out SCREAMING_SNAKE_CASE__ = nn.GroupNorm(num_channels=block_out_channels[-1] , num_groups=__A , eps=1E-6 ) SCREAMING_SNAKE_CASE__ = nn.SiLU() SCREAMING_SNAKE_CASE__ = 2 * out_channels if double_z else out_channels SCREAMING_SNAKE_CASE__ = nn.Convad(block_out_channels[-1] , __A , 3 , padding=1 ) SCREAMING_SNAKE_CASE__ = False def _snake_case ( self :Optional[int] , __A :Tuple ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = x SCREAMING_SNAKE_CASE__ = self.conv_in(__A ) if self.training and self.gradient_checkpointing: def create_custom_forward(__A :Tuple ): def custom_forward(*__A :List[Any] ): return module(*__A ) return custom_forward # down if is_torch_version(""">=""" , """1.11.0""" ): for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(__A ) , __A , use_reentrant=__A ) # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , use_reentrant=__A ) else: for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(__A ) , __A ) # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block ) , __A ) else: # down for down_block in self.down_blocks: SCREAMING_SNAKE_CASE__ = down_block(__A ) # middle SCREAMING_SNAKE_CASE__ = self.mid_block(__A ) # post-process SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A ) SCREAMING_SNAKE_CASE__ = self.conv_act(__A ) SCREAMING_SNAKE_CASE__ = self.conv_out(__A ) return sample class UpperCamelCase_ ( nn.Module ): def __init__( self :Any , __A :List[Any]=3 , __A :str=3 , __A :Tuple=("UpDecoderBlock2D",) , __A :Tuple=(64,) , __A :Any=2 , __A :int=32 , __A :Optional[int]="silu" , __A :Optional[Any]="group" , ) -> Optional[int]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = layers_per_block SCREAMING_SNAKE_CASE__ = nn.Convad( __A , block_out_channels[-1] , kernel_size=3 , stride=1 , padding=1 , ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = nn.ModuleList([] ) SCREAMING_SNAKE_CASE__ = in_channels if norm_type == """spatial""" else None # mid SCREAMING_SNAKE_CASE__ = UNetMidBlockaD( in_channels=block_out_channels[-1] , resnet_eps=1E-6 , resnet_act_fn=__A , output_scale_factor=1 , resnet_time_scale_shift="""default""" if norm_type == """group""" else norm_type , attention_head_dim=block_out_channels[-1] , resnet_groups=__A , temb_channels=__A , ) # up SCREAMING_SNAKE_CASE__ = list(reversed(__A ) ) SCREAMING_SNAKE_CASE__ = reversed_block_out_channels[0] for i, up_block_type in enumerate(__A ): SCREAMING_SNAKE_CASE__ = output_channel SCREAMING_SNAKE_CASE__ = reversed_block_out_channels[i] SCREAMING_SNAKE_CASE__ = i == len(__A ) - 1 SCREAMING_SNAKE_CASE__ = get_up_block( __A , num_layers=self.layers_per_block + 1 , in_channels=__A , out_channels=__A , prev_output_channel=__A , add_upsample=not is_final_block , resnet_eps=1E-6 , resnet_act_fn=__A , resnet_groups=__A , attention_head_dim=__A , temb_channels=__A , resnet_time_scale_shift=__A , ) self.up_blocks.append(__A ) SCREAMING_SNAKE_CASE__ = output_channel # out if norm_type == "spatial": SCREAMING_SNAKE_CASE__ = SpatialNorm(block_out_channels[0] , __A ) else: SCREAMING_SNAKE_CASE__ = nn.GroupNorm(num_channels=block_out_channels[0] , num_groups=__A , eps=1E-6 ) SCREAMING_SNAKE_CASE__ = nn.SiLU() SCREAMING_SNAKE_CASE__ = nn.Convad(block_out_channels[0] , __A , 3 , padding=1 ) SCREAMING_SNAKE_CASE__ = False def _snake_case ( self :str , __A :Tuple , __A :int=None ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ = z SCREAMING_SNAKE_CASE__ = self.conv_in(__A ) SCREAMING_SNAKE_CASE__ = next(iter(self.up_blocks.parameters() ) ).dtype if self.training and self.gradient_checkpointing: def create_custom_forward(__A :Tuple ): def custom_forward(*__A :List[Any] ): return module(*__A ) return custom_forward if is_torch_version(""">=""" , """1.11.0""" ): # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , __A , use_reentrant=__A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(__A ) , __A , __A , use_reentrant=__A ) else: # middle SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint( create_custom_forward(self.mid_block ) , __A , __A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = torch.utils.checkpoint.checkpoint(create_custom_forward(__A ) , __A , __A ) else: # middle SCREAMING_SNAKE_CASE__ = self.mid_block(__A , __A ) SCREAMING_SNAKE_CASE__ = sample.to(__A ) # up for up_block in self.up_blocks: SCREAMING_SNAKE_CASE__ = up_block(__A , __A ) # post-process if latent_embeds is None: SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A ) else: SCREAMING_SNAKE_CASE__ = self.conv_norm_out(__A , __A ) SCREAMING_SNAKE_CASE__ = self.conv_act(__A ) SCREAMING_SNAKE_CASE__ = self.conv_out(__A ) return sample class UpperCamelCase_ ( nn.Module ): def __init__( self :Optional[int] , __A :Optional[Any] , __A :List[Any] , __A :str , __A :List[str]=None , __A :Optional[Any]="random" , __A :Optional[int]=False , __A :int=True ) -> Optional[int]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ = n_e SCREAMING_SNAKE_CASE__ = vq_embed_dim SCREAMING_SNAKE_CASE__ = beta SCREAMING_SNAKE_CASE__ = legacy SCREAMING_SNAKE_CASE__ = nn.Embedding(self.n_e , self.vq_embed_dim ) self.embedding.weight.data.uniform_(-1.0 / self.n_e , 1.0 / self.n_e ) SCREAMING_SNAKE_CASE__ = remap if self.remap is not None: self.register_buffer("""used""" , torch.tensor(np.load(self.remap ) ) ) SCREAMING_SNAKE_CASE__ = self.used.shape[0] SCREAMING_SNAKE_CASE__ = unknown_index # "random" or "extra" or integer if self.unknown_index == "extra": SCREAMING_SNAKE_CASE__ = self.re_embed SCREAMING_SNAKE_CASE__ = self.re_embed + 1 print( f'''Remapping {self.n_e} indices to {self.re_embed} indices. ''' f'''Using {self.unknown_index} for unknown indices.''' ) else: SCREAMING_SNAKE_CASE__ = n_e SCREAMING_SNAKE_CASE__ = sane_index_shape def _snake_case ( self :Tuple , __A :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ = inds.shape assert len(__A ) > 1 SCREAMING_SNAKE_CASE__ = inds.reshape(ishape[0] , -1 ) SCREAMING_SNAKE_CASE__ = self.used.to(__A ) SCREAMING_SNAKE_CASE__ = (inds[:, :, None] == used[None, None, ...]).long() SCREAMING_SNAKE_CASE__ = match.argmax(-1 ) SCREAMING_SNAKE_CASE__ = match.sum(2 ) < 1 if self.unknown_index == "random": SCREAMING_SNAKE_CASE__ = torch.randint(0 , self.re_embed , size=new[unknown].shape ).to(device=new.device ) else: SCREAMING_SNAKE_CASE__ = self.unknown_index return new.reshape(__A ) def _snake_case ( self :Dict , __A :Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = inds.shape assert len(__A ) > 1 SCREAMING_SNAKE_CASE__ = inds.reshape(ishape[0] , -1 ) SCREAMING_SNAKE_CASE__ = self.used.to(__A ) if self.re_embed > self.used.shape[0]: # extra token SCREAMING_SNAKE_CASE__ = 0 # simply set to zero SCREAMING_SNAKE_CASE__ = torch.gather(used[None, :][inds.shape[0] * [0], :] , 1 , __A ) return back.reshape(__A ) def _snake_case ( self :Optional[int] , __A :List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = z.permute(0 , 2 , 3 , 1 ).contiguous() SCREAMING_SNAKE_CASE__ = z.view(-1 , self.vq_embed_dim ) # distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z SCREAMING_SNAKE_CASE__ = torch.argmin(torch.cdist(__A , self.embedding.weight ) , dim=1 ) SCREAMING_SNAKE_CASE__ = self.embedding(__A ).view(z.shape ) SCREAMING_SNAKE_CASE__ = None SCREAMING_SNAKE_CASE__ = None # compute loss for embedding if not self.legacy: SCREAMING_SNAKE_CASE__ = self.beta * torch.mean((z_q.detach() - z) ** 2 ) + torch.mean((z_q - z.detach()) ** 2 ) else: SCREAMING_SNAKE_CASE__ = torch.mean((z_q.detach() - z) ** 2 ) + self.beta * torch.mean((z_q - z.detach()) ** 2 ) # preserve gradients SCREAMING_SNAKE_CASE__ = z + (z_q - z).detach() # reshape back to match original input shape SCREAMING_SNAKE_CASE__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() if self.remap is not None: SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(z.shape[0] , -1 ) # add batch axis SCREAMING_SNAKE_CASE__ = self.remap_to_used(__A ) SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(-1 , 1 ) # flatten if self.sane_index_shape: SCREAMING_SNAKE_CASE__ = min_encoding_indices.reshape(z_q.shape[0] , z_q.shape[2] , z_q.shape[3] ) return z_q, loss, (perplexity, min_encodings, min_encoding_indices) def _snake_case ( self :Union[str, Any] , __A :Dict , __A :Optional[Any] ) -> Dict: """simple docstring""" if self.remap is not None: SCREAMING_SNAKE_CASE__ = indices.reshape(shape[0] , -1 ) # add batch axis SCREAMING_SNAKE_CASE__ = self.unmap_to_all(__A ) SCREAMING_SNAKE_CASE__ = indices.reshape(-1 ) # flatten again # get quantized latent vectors SCREAMING_SNAKE_CASE__ = self.embedding(__A ) if shape is not None: SCREAMING_SNAKE_CASE__ = z_q.view(__A ) # reshape back to match original input shape SCREAMING_SNAKE_CASE__ = z_q.permute(0 , 3 , 1 , 2 ).contiguous() return z_q class UpperCamelCase_ ( UpperCamelCase__ ): def __init__( self :List[Any] , __A :List[str] , __A :Dict=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = parameters SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = torch.chunk(__A , 2 , dim=1 ) SCREAMING_SNAKE_CASE__ = torch.clamp(self.logvar , -3_0.0 , 2_0.0 ) SCREAMING_SNAKE_CASE__ = deterministic SCREAMING_SNAKE_CASE__ = torch.exp(0.5 * self.logvar ) SCREAMING_SNAKE_CASE__ = torch.exp(self.logvar ) if self.deterministic: SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = torch.zeros_like( self.mean , device=self.parameters.device , dtype=self.parameters.dtype ) def _snake_case ( self :Union[str, Any] , __A :Optional[torch.Generator] = None ) -> torch.FloatTensor: """simple docstring""" SCREAMING_SNAKE_CASE__ = randn_tensor( self.mean.shape , generator=__A , device=self.parameters.device , dtype=self.parameters.dtype ) SCREAMING_SNAKE_CASE__ = self.mean + self.std * sample return x def _snake_case ( self :str , __A :Any=None ) -> Union[str, Any]: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) else: if other is None: return 0.5 * torch.sum(torch.pow(self.mean , 2 ) + self.var - 1.0 - self.logvar , dim=[1, 2, 3] ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean , 2 ) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar , dim=[1, 2, 3] , ) def _snake_case ( self :str , __A :Optional[int] , __A :List[Any]=[1, 2, 3] ) -> Any: """simple docstring""" if self.deterministic: return torch.Tensor([0.0] ) SCREAMING_SNAKE_CASE__ = np.log(2.0 * np.pi ) return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean , 2 ) / self.var , dim=__A ) def _snake_case ( self :Any ) -> str: """simple docstring""" return self.mean
6
import argparse import os import transformers from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS from .utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) lowercase_ = {name: getattr(transformers, name + 'Fast') for name in SLOW_TO_FAST_CONVERTERS} def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES: raise ValueError(f'Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.' ) if tokenizer_name is None: __lowerCamelCase : Optional[int] = TOKENIZER_CLASSES else: __lowerCamelCase : Union[str, Any] = {tokenizer_name: getattr(SCREAMING_SNAKE_CASE__ , tokenizer_name + 'Fast' )} logger.info(f'Loading tokenizer classes: {tokenizer_names}' ) for tokenizer_name in tokenizer_names: __lowerCamelCase : int = TOKENIZER_CLASSES[tokenizer_name] __lowerCamelCase : Optional[int] = True if checkpoint_name is None: __lowerCamelCase : List[Any] = list(tokenizer_class.max_model_input_sizes.keys() ) else: __lowerCamelCase : Optional[Any] = [checkpoint_name] logger.info(f'For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}' ) for checkpoint in checkpoint_names: logger.info(f'Loading {tokenizer_class.__class__.__name__} {checkpoint}' ) # Load tokenizer __lowerCamelCase : Tuple = tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , force_download=SCREAMING_SNAKE_CASE__ ) # Save fast tokenizer logger.info(f'Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}' ) # For organization names we create sub-directories if "/" in checkpoint: __lowerCamelCase , __lowerCamelCase : Tuple = checkpoint.split('/' ) __lowerCamelCase : Tuple = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif add_prefix: __lowerCamelCase : Any = checkpoint __lowerCamelCase : Dict = dump_path else: __lowerCamelCase : List[str] = None __lowerCamelCase : Optional[int] = dump_path logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]: __lowerCamelCase : List[Any] = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint] __lowerCamelCase : int = file_path.split(SCREAMING_SNAKE_CASE__ )[-1][0] if next_char == "/": __lowerCamelCase : List[Any] = os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : int = None logger.info(f'=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}' ) __lowerCamelCase : Dict = tokenizer.save_pretrained( SCREAMING_SNAKE_CASE__ , legacy_format=SCREAMING_SNAKE_CASE__ , filename_prefix=SCREAMING_SNAKE_CASE__ ) logger.info(f'=> File names {file_names}' ) for file_name in file_names: if not file_name.endswith('tokenizer.json' ): os.remove(SCREAMING_SNAKE_CASE__ ) logger.info(f'=> removing {file_name}' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--dump_path', default=None, type=str, required=True, help='Path to output generated fast tokenizer files.' ) parser.add_argument( '--tokenizer_name', default=None, type=str, help=( F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """ 'download and convert all the checkpoints from AWS.' ), ) parser.add_argument( '--checkpoint_name', default=None, type=str, help='Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.', ) parser.add_argument( '--force_download', action='store_true', help='Re-download checkpoints.', ) lowercase_ = parser.parse_args() convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
669
0
"""simple docstring""" import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) a = logging.getLogger(__name__) @dataclass class lowercase_ : '''simple docstring''' UpperCAmelCase : str = field( metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''} ) UpperCAmelCase : Optional[str] = field( default=__lowerCAmelCase , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCAmelCase : Optional[str] = field( default=__lowerCAmelCase , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCAmelCase : Optional[str] = field( default=__lowerCAmelCase , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) UpperCAmelCase : bool = field(default=__lowerCAmelCase , metadata={'''help''': '''Whether tp freeze the encoder.'''} ) UpperCAmelCase : bool = field(default=__lowerCAmelCase , metadata={'''help''': '''Whether to freeze the embeddings.'''} ) @dataclass class lowercase_ : '''simple docstring''' UpperCAmelCase : str = field( metadata={'''help''': '''The input data dir. Should contain the .tsv files (or other data files) for the task.'''} ) UpperCAmelCase : Optional[str] = field( default='''summarization''' , metadata={'''help''': '''Task name, summarization (or summarization_{dataset} for pegasus) or translation'''} , ) UpperCAmelCase : Optional[int] = field( default=1024 , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCAmelCase : Optional[int] = field( default=128 , metadata={ '''help''': ( '''The maximum total sequence length for target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCAmelCase : Optional[int] = field( default=142 , metadata={ '''help''': ( '''The maximum total sequence length for validation target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded. ''' '''This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ''' '''during ``evaluate`` and ``predict``.''' ) } , ) UpperCAmelCase : Optional[int] = field( default=142 , metadata={ '''help''': ( '''The maximum total sequence length for test target text after tokenization. Sequences longer ''' '''than this will be truncated, sequences shorter will be padded.''' ) } , ) UpperCAmelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# training examples. -1 means use all.'''} ) UpperCAmelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# validation examples. -1 means use all.'''} ) UpperCAmelCase : Optional[int] = field(default=-1 , metadata={'''help''': '''# test examples. -1 means use all.'''} ) UpperCAmelCase : Optional[str] = field(default=__lowerCAmelCase , metadata={'''help''': '''Source language id for translation.'''} ) UpperCAmelCase : Optional[str] = field(default=__lowerCAmelCase , metadata={'''help''': '''Target language id for translation.'''} ) UpperCAmelCase : Optional[int] = field(default=__lowerCAmelCase , metadata={'''help''': '''# num_beams to use for evaluation.'''} ) UpperCAmelCase : bool = field( default=__lowerCAmelCase , metadata={'''help''': '''If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'''} , ) def _snake_case ( _snake_case : Optional[Any] , _snake_case : int , _snake_case : Optional[Any] ) -> str: '''simple docstring''' logger.info(F'''***** {split} metrics *****''' ) for key in sorted(metrics.keys() ): logger.info(F''' {key} = {metrics[key]}''' ) save_json(_snake_case , os.path.join(_snake_case , F'''{split}_results.json''' ) ) def _snake_case ( ) -> Tuple: '''simple docstring''' _A = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _A , _A , _A = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _A , _A , _A = parser.parse_args_into_dataclasses() check_output_dir(_snake_case ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('Training/evaluation parameters %s' , _snake_case ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _A = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _A = ('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout') for p in extra_model_params: if getattr(_snake_case , _snake_case , _snake_case ): assert hasattr(_snake_case , _snake_case ), F'''({config.__class__.__name__}) doesn\'t have a `{p}` attribute''' setattr(_snake_case , _snake_case , getattr(_snake_case , _snake_case ) ) _A = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) _A = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='.ckpt' in model_args.model_name_or_path , config=_snake_case , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(_snake_case , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: _A = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(_snake_case , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(_snake_case , _snake_case ): _A = tokenizer.lang_code_to_id[data_args.tgt_lang] else: _A = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(_snake_case ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) _A = SeqaSeqDataset # Get datasets _A = ( dataset_class( _snake_case , type_path='train' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_train else None ) _A = ( dataset_class( _snake_case , type_path='val' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) _A = ( dataset_class( _snake_case , type_path='test' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '' , ) if training_args.do_predict else None ) # Initialize our Trainer _A = ( build_compute_metrics_fn(data_args.task , _snake_case ) if training_args.predict_with_generate else None ) _A = SeqaSeqTrainer( model=_snake_case , args=_snake_case , data_args=_snake_case , train_dataset=_snake_case , eval_dataset=_snake_case , data_collator=SeqaSeqDataCollator( _snake_case , _snake_case , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=_snake_case , tokenizer=_snake_case , ) _A = {} # Training if training_args.do_train: logger.info('*** Train ***' ) _A = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) _A = train_result.metrics _A = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('train' , _snake_case , training_args.output_dir ) all_metrics.update(_snake_case ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , 'trainer_state.json' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('*** Evaluate ***' ) _A = trainer.evaluate(metric_key_prefix='val' ) _A = data_args.n_val _A = round(metrics['val_loss'] , 4 ) if trainer.is_world_process_zero(): handle_metrics('val' , _snake_case , training_args.output_dir ) all_metrics.update(_snake_case ) if training_args.do_predict: logger.info('*** Predict ***' ) _A = trainer.predict(test_dataset=_snake_case , metric_key_prefix='test' ) _A = test_output.metrics _A = data_args.n_test if trainer.is_world_process_zero(): _A = round(metrics['test_loss'] , 4 ) handle_metrics('test' , _snake_case , training_args.output_dir ) all_metrics.update(_snake_case ) if training_args.predict_with_generate: _A = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=_snake_case , clean_up_tokenization_spaces=_snake_case ) _A = lmap(str.strip , _snake_case ) write_txt_file(_snake_case , os.path.join(training_args.output_dir , 'test_generations.txt' ) ) if trainer.is_world_process_zero(): save_json(_snake_case , os.path.join(training_args.output_dir , 'all_results.json' ) ) return all_metrics def _snake_case ( _snake_case : List[Any] ) -> int: '''simple docstring''' main() if __name__ == "__main__": main()
7
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowercase_ = get_tests_dir('fixtures/test_sentencepiece_no_bos.model') @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: List[str] ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : List[str] = PegasusTokenizer(a ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[Any] ): return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def _snake_case ( self: Tuple , **a: List[Any] ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[Any] , a: int ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Dict = '</s>' __lowerCamelCase : List[str] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<pad>' ) self.assertEqual(vocab_keys[1] , '</s>' ) self.assertEqual(vocab_keys[-1] , 'v' ) self.assertEqual(len(a ) , 1103 ) def _snake_case ( self: Tuple ): self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : List[str] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important' ' </s> <pad> <pad> <pad>' ) __lowerCamelCase : Optional[Any] = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: int ): __lowerCamelCase : Union[str, Any] = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowerCamelCase : Tuple = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' __lowerCamelCase : Optional[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : Optional[Any] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) def _snake_case ( self: Dict ): __lowerCamelCase : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 __lowerCamelCase : int = 'To ensure a smooth flow of bank resolutions.' __lowerCamelCase : Union[str, Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] __lowerCamelCase : List[str] = tokenizer([raw_input_str] , return_tensors=a ).input_ids[0] self.assertListEqual(a , a ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def _snake_case ( self: str ): __lowerCamelCase : List[str] = ['This is going to be way too long.' * 150, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : Union[str, Any] = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : List[str] = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. @slow def _snake_case ( self: List[str] ): # fmt: off __lowerCamelCase : Tuple = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = PegasusTokenizer __snake_case = PegasusTokenizerFast __snake_case = True __snake_case = True def _snake_case ( self: str ): super().setUp() # We have a SentencePiece fixture for testing __lowerCamelCase : str = PegasusTokenizer(a , offset=0 , mask_token_sent=a , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def _snake_case ( self: List[str] ): return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def _snake_case ( self: Union[str, Any] , **a: Dict ): return PegasusTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: List[str] , a: Any ): return ("This is a test", "This is a test") def _snake_case ( self: Any ): __lowerCamelCase : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Optional[Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowerCamelCase : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) __lowerCamelCase : int = rust_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] __lowerCamelCase : str = py_tokenizer([raw_input_str] , return_tensors=a , add_special_tokens=a ).input_ids[0] self.assertListEqual(a , a ) @require_torch def _snake_case ( self: Union[str, Any] ): __lowerCamelCase : Union[str, Any] = ['This is going to be way too long.' * 1000, 'short example'] __lowerCamelCase : Tuple = ['not super long but more than 5 tokens', 'tiny'] __lowerCamelCase : str = self._large_tokenizer(a , padding=a , truncation=a , return_tensors='pt' ) __lowerCamelCase : Any = self._large_tokenizer( text_target=a , max_length=5 , padding=a , truncation=a , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a ) == 2 # input_ids, attention_mask. def _snake_case ( self: Any ): __lowerCamelCase : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) __lowerCamelCase : Dict = self._large_tokenizer(a ).input_ids self.assertListEqual( a , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
669
0
'''simple docstring''' lowercase__ : Tuple = { '''a''': '''AAAAA''', '''b''': '''AAAAB''', '''c''': '''AAABA''', '''d''': '''AAABB''', '''e''': '''AABAA''', '''f''': '''AABAB''', '''g''': '''AABBA''', '''h''': '''AABBB''', '''i''': '''ABAAA''', '''j''': '''BBBAA''', '''k''': '''ABAAB''', '''l''': '''ABABA''', '''m''': '''ABABB''', '''n''': '''ABBAA''', '''o''': '''ABBAB''', '''p''': '''ABBBA''', '''q''': '''ABBBB''', '''r''': '''BAAAA''', '''s''': '''BAAAB''', '''t''': '''BAABA''', '''u''': '''BAABB''', '''v''': '''BBBAB''', '''w''': '''BABAA''', '''x''': '''BABAB''', '''y''': '''BABBA''', '''z''': '''BABBB''', ''' ''': ''' ''', } lowercase__ : Union[str, Any] = {value: key for key, value in encode_dict.items()} def _lowerCAmelCase ( __snake_case : str ) -> str: __A : Optional[int] = '' for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception('encode() accepts only letters of the alphabet and spaces' ) return encoded def _lowerCAmelCase ( __snake_case : str ) -> str: if set(__snake_case ) - {"A", "B", " "} != set(): raise Exception('decode() accepts only \'A\', \'B\' and spaces' ) __A : str = '' for word in coded.split(): while len(__snake_case ) != 0: decoded += decode_dict[word[:5]] __A : Dict = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
8
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if density <= 0: raise ValueError('Impossible fluid density' ) if bulk_modulus <= 0: raise ValueError('Impossible bulk modulus' ) return (bulk_modulus / density) ** 0.5 if __name__ == "__main__": import doctest doctest.testmod()
669
0
import time from dataclasses import dataclass from multiprocessing import Pool from unittest import TestCase from unittest.mock import patch import multiprocess import numpy as np import pytest from datasets.utils.py_utils import ( NestedDataStructure, asdict, iflatmap_unordered, map_nested, temp_seed, temporary_assignment, zip_dict, ) from .utils import require_tf, require_torch def A ( __UpperCamelCase ) -> List[str]: # picklable for multiprocessing return x.sum() def A ( __UpperCamelCase ) -> Optional[Any]: # picklable for multiprocessing return i + 1 @dataclass class __lowerCAmelCase : """simple docstring""" A__ : int A__ : str class __lowerCAmelCase ( UpperCAmelCase_ ): """simple docstring""" def _a ( self : List[str] ): """simple docstring""" A__ = {} A__ = [] A__ = 1 A__ = [1, 2] A__ = {'a': 1, 'b': 2} A__ = {'a': [1, 2], 'b': [3, 4]} A__ = {'a': {'1': 1}, 'b': 2} A__ = {'a': 1, 'b': 2, 'c': 3, 'd': 4} A__ = {} A__ = [] A__ = 2 A__ = [2, 3] A__ = {'a': 2, 'b': 3} A__ = {'a': [2, 3], 'b': [4, 5]} A__ = {'a': {'1': 2}, 'b': 3} A__ = {'a': 2, 'b': 3, 'c': 4, 'd': 5} self.assertEqual(map_nested(_snake_case , _snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case ) , _snake_case ) A__ = 2 self.assertEqual(map_nested(_snake_case , _snake_case , num_proc=_snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case , num_proc=_snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case , num_proc=_snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case , num_proc=_snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case , num_proc=_snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case , num_proc=_snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case , num_proc=_snake_case ) , _snake_case ) self.assertEqual(map_nested(_snake_case , _snake_case , num_proc=_snake_case ) , _snake_case ) A__ = {'a': np.eye(2 ), 'b': np.zeros(3 ), 'c': np.ones(2 )} A__ = {'a': 2, 'b': 0, 'c': 2} A__ = { 'a': np.eye(2 ).astype(_snake_case ), 'b': np.zeros(3 ).astype(_snake_case ), 'c': np.ones(2 ).astype(_snake_case ), } self.assertEqual(map_nested(_snake_case , _snake_case , map_numpy=_snake_case ) , _snake_case ) self.assertEqual( {k: v.tolist() for k, v in map_nested(_snake_case , _snake_case , map_numpy=_snake_case ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) self.assertEqual(map_nested(_snake_case , _snake_case , map_numpy=_snake_case , num_proc=_snake_case ) , _snake_case ) self.assertEqual( {k: v.tolist() for k, v in map_nested(_snake_case , _snake_case , map_numpy=_snake_case , num_proc=_snake_case ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , ) with self.assertRaises(_snake_case ): # can't pickle a local lambda map_nested(lambda _snake_case : x + 1 , _snake_case , num_proc=_snake_case ) def _a ( self : Optional[int] ): """simple docstring""" A__ = {'a': 1, 'b': 2} A__ = {'a': 3, 'b': 4} A__ = {'a': 5, 'b': 6} A__ = sorted([('a', (1, 3, 5)), ('b', (2, 4, 6))] ) self.assertEqual(sorted(zip_dict(_snake_case , _snake_case , _snake_case ) ) , _snake_case ) def _a ( self : Tuple ): """simple docstring""" class __lowerCAmelCase : """simple docstring""" A__ : int = "bar" A__ = Foo() self.assertEqual(foo.my_attr , 'bar' ) with temporary_assignment(_snake_case , 'my_attr' , 'BAR' ): self.assertEqual(foo.my_attr , 'BAR' ) self.assertEqual(foo.my_attr , 'bar' ) @pytest.mark.parametrize( 'iterable_length, num_proc, expected_num_proc' , [ (1, None, 1), (1, 1, 1), (2, None, 1), (2, 1, 1), (2, 2, 1), (2, 3, 1), (3, 2, 1), (16, 16, 16), (16, 17, 16), (17, 16, 16), ] , ) def A ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) -> List[str]: with patch('datasets.utils.py_utils._single_map_nested' ) as mock_single_map_nested, patch( 'datasets.parallel.parallel.Pool' ) as mock_multiprocessing_pool: A__ = {f'''{i}''': i for i in range(__UpperCamelCase )} A__ = map_nested(lambda __UpperCamelCase : x + 10 , __UpperCamelCase , num_proc=__UpperCamelCase , parallel_min_length=16 ) if expected_num_proc == 1: assert mock_single_map_nested.called assert not mock_multiprocessing_pool.called else: assert not mock_single_map_nested.called assert mock_multiprocessing_pool.called assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc class __lowerCAmelCase ( UpperCAmelCase_ ): """simple docstring""" @require_tf def _a ( self : Optional[int] ): """simple docstring""" import tensorflow as tf from tensorflow.keras import layers A__ = layers.Dense(2 ) def gen_random_output(): A__ = tf.random.uniform((1, 3) ) return model(_snake_case ).numpy() with temp_seed(42 , set_tensorflow=_snake_case ): A__ = gen_random_output() with temp_seed(42 , set_tensorflow=_snake_case ): A__ = gen_random_output() A__ = gen_random_output() np.testing.assert_equal(_snake_case , _snake_case ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @require_torch def _a ( self : Optional[Any] ): """simple docstring""" import torch def gen_random_output(): A__ = torch.nn.Linear(3 , 2 ) A__ = torch.rand(1 , 3 ) return model(_snake_case ).detach().numpy() with temp_seed(42 , set_pytorch=_snake_case ): A__ = gen_random_output() with temp_seed(42 , set_pytorch=_snake_case ): A__ = gen_random_output() A__ = gen_random_output() np.testing.assert_equal(_snake_case , _snake_case ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) def _a ( self : List[Any] ): """simple docstring""" def gen_random_output(): return np.random.rand(1 , 3 ) with temp_seed(42 ): A__ = gen_random_output() with temp_seed(42 ): A__ = gen_random_output() A__ = gen_random_output() np.testing.assert_equal(_snake_case , _snake_case ) self.assertGreater(np.abs(outa - outa ).sum() , 0 ) @pytest.mark.parametrize('input_data' , [{}] ) def A ( __UpperCamelCase ) -> List[str]: A__ = NestedDataStructure(__UpperCamelCase ).data assert output_data == input_data @pytest.mark.parametrize( 'data, expected_output' , [ ({}, []), ([], []), ('foo', ['foo']), (['foo', 'bar'], ['foo', 'bar']), ([['foo', 'bar']], ['foo', 'bar']), ([[['foo'], ['bar']]], ['foo', 'bar']), ([[['foo'], 'bar']], ['foo', 'bar']), ({'a': 1, 'b': 2}, [1, 2]), ({'a': [1, 2], 'b': [3, 4]}, [1, 2, 3, 4]), ({'a': [[1, 2]], 'b': [[3, 4]]}, [1, 2, 3, 4]), ({'a': [[1, 2]], 'b': [3, 4]}, [1, 2, 3, 4]), ({'a': [[[1], [2]]], 'b': [[[3], [4]]]}, [1, 2, 3, 4]), ({'a': [[[1], [2]]], 'b': [[3, 4]]}, [1, 2, 3, 4]), ({'a': [[[1], [2]]], 'b': [3, 4]}, [1, 2, 3, 4]), ({'a': [[[1], [2]]], 'b': [3, [4]]}, [1, 2, 3, 4]), ({'a': {'1': 1}, 'b': 2}, [1, 2]), ({'a': {'1': [1]}, 'b': 2}, [1, 2]), ({'a': {'1': [1]}, 'b': [2]}, [1, 2]), ] , ) def A ( __UpperCamelCase , __UpperCamelCase ) -> str: A__ = NestedDataStructure(__UpperCamelCase ).flatten() assert output == expected_output def A ( ) -> Tuple: A__ = A(x=1 , y='foobar' ) A__ = {'x': 1, 'y': 'foobar'} assert asdict(__UpperCamelCase ) == expected_output A__ = {'a': {'b': A(x=10 , y='foo' )}, 'c': [A(x=20 , y='bar' )]} A__ = {'a': {'b': {'x': 10, 'y': 'foo'}}, 'c': [{'x': 20, 'y': 'bar'}]} assert asdict(__UpperCamelCase ) == expected_output with pytest.raises(__UpperCamelCase ): asdict([1, A(x=10 , y='foo' )] ) def A ( __UpperCamelCase ) -> str: return text.split() def A ( __UpperCamelCase ) -> Tuple: yield (time.time(), content) time.sleep(2 ) yield (time.time(), content) def A ( ) -> Any: with Pool(2 ) as pool: A__ = list(iflatmap_unordered(__UpperCamelCase , _split_text , kwargs_iterable=[{'text': 'hello there'}] * 10 ) ) assert out.count('hello' ) == 10 assert out.count('there' ) == 10 assert len(__UpperCamelCase ) == 20 # check multiprocess from pathos (uses dill for pickling) with multiprocess.Pool(2 ) as pool: A__ = list(iflatmap_unordered(__UpperCamelCase , _split_text , kwargs_iterable=[{'text': 'hello there'}] * 10 ) ) assert out.count('hello' ) == 10 assert out.count('there' ) == 10 assert len(__UpperCamelCase ) == 20 # check that we get items as fast as possible with Pool(2 ) as pool: A__ = [] for yield_time, content in iflatmap_unordered( __UpperCamelCase , _aseconds_generator_of_aitems_with_timing , kwargs_iterable=[{'content': 'a'}, {'content': 'b'}] ): assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded" out.append(__UpperCamelCase ) assert out.count('a' ) == 2 assert out.count('b' ) == 2 assert len(__UpperCamelCase ) == 4
9
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Dict = 1 __lowerCamelCase : str = 2 while i * i <= n: __lowerCamelCase : int = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def UpperCamelCase__ ( ): __lowerCamelCase : str = 1 __lowerCamelCase : List[str] = 1 while True: i += 1 t_num += i if count_divisors(SCREAMING_SNAKE_CASE__ ) > 500: break return t_num if __name__ == "__main__": print(solution())
669
0
import gc import unittest import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DDPMScheduler, PriorTransformer, StableUnCLIPPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class lowerCAmelCase_ ( __lowercase, __lowercase, __lowercase, unittest.TestCase ): UpperCAmelCase = StableUnCLIPPipeline UpperCAmelCase = TEXT_TO_IMAGE_PARAMS UpperCAmelCase = TEXT_TO_IMAGE_BATCH_PARAMS UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS UpperCAmelCase = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false UpperCAmelCase = False def UpperCamelCase_ ( self : Optional[int] ): _UpperCamelCase = 32 _UpperCamelCase = embedder_hidden_size # prior components torch.manual_seed(0 ) _UpperCamelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) _UpperCamelCase = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=_A , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) _UpperCamelCase = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=_A , num_layers=1 , ) torch.manual_seed(0 ) _UpperCamelCase = DDPMScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1000 , clip_sample=_A , clip_sample_range=5.0 , beta_schedule='''squaredcos_cap_v2''' , ) # regular denoising components torch.manual_seed(0 ) _UpperCamelCase = StableUnCLIPImageNormalizer(embedding_dim=_A ) _UpperCamelCase = DDPMScheduler(beta_schedule='''squaredcos_cap_v2''' ) torch.manual_seed(0 ) _UpperCamelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) torch.manual_seed(0 ) _UpperCamelCase = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=_A , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) _UpperCamelCase = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='''projection''' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=_A , layers_per_block=1 , upcast_attention=_A , use_linear_projection=_A , ) torch.manual_seed(0 ) _UpperCamelCase = DDIMScheduler( beta_schedule='''scaled_linear''' , beta_start=0.0_0085 , beta_end=0.012 , prediction_type='''v_prediction''' , set_alpha_to_one=_A , steps_offset=1 , ) torch.manual_seed(0 ) _UpperCamelCase = AutoencoderKL() _UpperCamelCase = { # prior components '''prior_tokenizer''': prior_tokenizer, '''prior_text_encoder''': prior_text_encoder, '''prior''': prior, '''prior_scheduler''': prior_scheduler, # image noising components '''image_normalizer''': image_normalizer, '''image_noising_scheduler''': image_noising_scheduler, # regular denoising components '''tokenizer''': tokenizer, '''text_encoder''': text_encoder, '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, } return components def UpperCamelCase_ ( self : Dict , _A : Tuple , _A : Dict=0 ): if str(_A ).startswith('''mps''' ): _UpperCamelCase = torch.manual_seed(_A ) else: _UpperCamelCase = torch.Generator(device=_A ).manual_seed(_A ) _UpperCamelCase = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''prior_num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def UpperCamelCase_ ( self : Dict ): _UpperCamelCase = torch_device == '''cpu''' self._test_attention_slicing_forward_pass(test_max_difference=_A ) def UpperCamelCase_ ( self : List[Any] ): _UpperCamelCase = torch_device in ['''cpu''', '''mps'''] self._test_inference_batch_single_identical(test_max_difference=_A ) @slow @require_torch_gpu class lowerCAmelCase_ ( unittest.TestCase ): def UpperCamelCase_ ( self : Optional[Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self : List[str] ): _UpperCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy''' ) _UpperCamelCase = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _UpperCamelCase = torch.Generator(device='''cpu''' ).manual_seed(0 ) _UpperCamelCase = pipe('''anime turle''' , generator=_A , output_type='''np''' ) _UpperCamelCase = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_A , _A ) def UpperCamelCase_ ( self : Optional[Any] ): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() _UpperCamelCase = StableUnCLIPPipeline.from_pretrained('''fusing/stable-unclip-2-1-l''' , torch_dtype=torch.floataa ) _UpperCamelCase = pipe.to(_A ) pipe.set_progress_bar_config(disable=_A ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() _UpperCamelCase = pipe( '''anime turtle''' , prior_num_inference_steps=2 , num_inference_steps=2 , output_type='''np''' , ) _UpperCamelCase = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
10
import numpy as np class A_ : '''simple docstring''' def __init__( self: Optional[int] ): __lowerCamelCase : int = (0, 0) __lowerCamelCase : List[str] = None __lowerCamelCase : int = 0 __lowerCamelCase : int = 0 __lowerCamelCase : Union[str, Any] = 0 def __eq__( self: Optional[int] , a: List[Any] ): return self.position == cell.position def _snake_case ( self: Any ): print(self.position ) class A_ : '''simple docstring''' def __init__( self: str , a: List[str]=(5, 5) ): __lowerCamelCase : Optional[Any] = np.zeros(a ) __lowerCamelCase : List[str] = world_size[0] __lowerCamelCase : Optional[int] = world_size[1] def _snake_case ( self: List[Any] ): print(self.w ) def _snake_case ( self: Optional[int] , a: str ): __lowerCamelCase : Tuple = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __lowerCamelCase : Optional[int] = cell.position[0] __lowerCamelCase : List[str] = cell.position[1] __lowerCamelCase : Dict = [] for n in neughbour_cord: __lowerCamelCase : Dict = current_x + n[0] __lowerCamelCase : Optional[Any] = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __lowerCamelCase : Optional[Any] = Cell() __lowerCamelCase : Any = (x, y) __lowerCamelCase : Dict = cell neighbours.append(a ) return neighbours def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = [] __lowerCamelCase : int = [] _open.append(SCREAMING_SNAKE_CASE__ ) while _open: __lowerCamelCase : Union[str, Any] = np.argmin([n.f for n in _open] ) __lowerCamelCase : int = _open[min_f] _closed.append(_open.pop(SCREAMING_SNAKE_CASE__ ) ) if current == goal: break for n in world.get_neigbours(SCREAMING_SNAKE_CASE__ ): for c in _closed: if c == n: continue __lowerCamelCase : Optional[int] = current.g + 1 __lowerCamelCase , __lowerCamelCase : int = n.position __lowerCamelCase , __lowerCamelCase : Tuple = goal.position __lowerCamelCase : Dict = (ya - ya) ** 2 + (xa - xa) ** 2 __lowerCamelCase : str = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase : Optional[int] = [] while current.parent is not None: path.append(current.position ) __lowerCamelCase : int = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": lowercase_ = Gridworld() # Start position and goal lowercase_ = Cell() lowercase_ = (0, 0) lowercase_ = Cell() lowercase_ = (4, 4) print(F"""path from {start.position} to {goal.position}""") lowercase_ = astar(world, start, goal) # Just for visual reasons. for i in s: lowercase_ = 1 print(world.w)
669
0
'''simple docstring''' from __future__ import annotations import math import numpy as np from numpy.linalg import norm def lowerCAmelCase (__A , __A): """simple docstring""" return math.sqrt(sum(pow(a - b , 2) for a, b in zip(__A , __A))) def lowerCAmelCase (__A , __A): """simple docstring""" if dataset.ndim != value_array.ndim: _a = ( '''Wrong input data\'s dimensions... ''' F'''dataset : {dataset.ndim}, value_array : {value_array.ndim}''' ) raise ValueError(__A) try: if dataset.shape[1] != value_array.shape[1]: _a = ( '''Wrong input data\'s shape... ''' F'''dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}''' ) raise ValueError(__A) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError('''Wrong shape''') if dataset.dtype != value_array.dtype: _a = ( '''Input data have different datatype... ''' F'''dataset : {dataset.dtype}, value_array : {value_array.dtype}''' ) raise TypeError(__A) _a = [] for value in value_array: _a = euclidean(__A , dataset[0]) _a = dataset[0].tolist() for dataset_value in dataset[1:]: _a = euclidean(__A , __A) if dist > temp_dist: _a = temp_dist _a = dataset_value.tolist() answer.append([vector, dist]) return answer def lowerCAmelCase (__A , __A): """simple docstring""" return np.dot(__A , __A) / (norm(__A) * norm(__A)) if __name__ == "__main__": import doctest doctest.testmod()
11
import math from datetime import datetime, timedelta def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : Tuple = year % 19 __lowerCamelCase : int = year % 4 __lowerCamelCase : Any = year % 7 __lowerCamelCase : Dict = math.floor(year / 100 ) __lowerCamelCase : str = math.floor((13 + 8 * leap_day_inhibits) / 25 ) __lowerCamelCase : Optional[int] = leap_day_inhibits / 4 __lowerCamelCase : str = ( 15 - lunar_orbit_correction + leap_day_inhibits - leap_day_reinstall_number ) % 30 __lowerCamelCase : Optional[Any] = (4 + leap_day_inhibits - leap_day_reinstall_number) % 7 # days to be added to March 21 __lowerCamelCase : Optional[int] = (19 * metonic_cycle + secular_moon_shift) % 30 # PHM -> Paschal Full Moon __lowerCamelCase : Tuple = ( 2 * julian_leap_year + 4 * non_leap_year + 6 * days_to_add + century_starting_point ) % 7 if days_to_add == 29 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 19 ) elif days_to_add == 28 and days_from_phm_to_sunday == 6: return datetime(SCREAMING_SNAKE_CASE__ , 4 , 18 ) else: return datetime(SCREAMING_SNAKE_CASE__ , 3 , 22 ) + timedelta( days=int(days_to_add + days_from_phm_to_sunday ) ) if __name__ == "__main__": for year in (1_9_9_4, 2_0_0_0, 2_0_1_0, 2_0_2_1, 2_0_2_3): lowercase_ = 'will be' if year > datetime.now().year else 'was' print(F"""Easter in {year} {tense} {gauss_easter(year)}""")
669
0
import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_=None ) -> Dict: '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'{torch_layer} layer.weight does not match' lowercase__ : List[str] = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'{torch_layer} layer.bias does not match' lowercase__ : List[Any] = nn.Parameter(lowercase_ ) def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ ) -> Union[str, Any]: '''simple docstring''' lowercase__ : int = np.asarray(weights[0] ) lowercase__ : Tuple = np.asarray(weights[1] ) lowercase__ : List[Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ ) -> Union[str, Any]: '''simple docstring''' lowercase__ : Optional[Any] = np.asarray(weights[0] ) lowercase__ : Optional[int] = np.asarray(weights[1] ) lowercase__ : Union[str, Any] = np.asarray(weights[2] ) lowercase__ : Any = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ ) -> Tuple: '''simple docstring''' lowercase__ : Any = weights[0][0][0] lowercase__ : Tuple = np.asarray(layer_norm_a[0] ) lowercase__ : Any = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output lowercase__ : List[Any] = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs lowercase__ : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: lowercase__ : Union[str, Any] = intermediate_weights[2] # layernorm 2 lowercase__ : Tuple = np.asarray(intermediate_weights[0][0] ) lowercase__ : int = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense lowercase__ : Optional[Any] = np.asarray(intermediate_weights[1][0] ) lowercase__ : Any = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out lowercase__ : List[Any] = np.asarray(intermediate_weights[4][0] ) lowercase__ : Optional[Any] = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ ) -> str: '''simple docstring''' lowercase__ : Dict = torch_model.reformer # word embeds lowercase__ : Any = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): lowercase__ : List[Any] = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): lowercase__ : List[str] = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'{position_embeddings[emb_idx]} emb does not match' lowercase__ : Union[str, Any] = nn.Parameter(torch.tensor(lowercase_ ) ) lowercase__ : Union[str, Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): lowercase__ : List[str] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm lowercase__ : int = np.asarray(weights[7][0] ) lowercase__ : str = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings lowercase__ : List[Any] = np.asarray(weights[9][0] ) lowercase__ : int = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def UpperCamelCase ( lowercase_ , lowercase_ , lowercase_ ) -> Optional[Any]: '''simple docstring''' lowercase__ : Union[str, Any] = ReformerConfig.from_json_file(lowercase_ ) print(F'Building PyTorch model from configuration: {config}' ) lowercase__ : Union[str, Any] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , """rb""" ) as f: lowercase__ : Tuple = pickle.load(lowercase_ )["""weights"""] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": lowerCamelCase__ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( """--trax_model_pkl_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained Reformer model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) lowerCamelCase__ : int = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
12
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch 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_ ( __UpperCamelCase , __UpperCamelCase ): '''simple docstring''' __snake_case = 1 @register_to_config def __init__( self: str , a: str=2000 , a: List[str]=0.1 , a: Any=20 , a: Dict=1e-3 ): __lowerCamelCase : Dict = None __lowerCamelCase : Any = None __lowerCamelCase : Optional[int] = None def _snake_case ( self: int , a: str , a: Union[str, torch.device] = None ): __lowerCamelCase : int = torch.linspace(1 , self.config.sampling_eps , a , device=a ) def _snake_case ( self: List[Any] , a: Union[str, Any] , a: Tuple , a: Optional[Any] , a: Dict=None ): if self.timesteps is None: raise ValueError( '`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler' ) # TODO(Patrick) better comments + non-PyTorch # postprocess model score __lowerCamelCase : Tuple = ( -0.2_5 * t**2 * (self.config.beta_max - self.config.beta_min) - 0.5 * t * self.config.beta_min ) __lowerCamelCase : Optional[int] = torch.sqrt(1.0 - torch.exp(2.0 * log_mean_coeff ) ) __lowerCamelCase : Optional[Any] = std.flatten() while len(std.shape ) < len(score.shape ): __lowerCamelCase : List[str] = std.unsqueeze(-1 ) __lowerCamelCase : Any = -score / std # compute __lowerCamelCase : List[Any] = -1.0 / len(self.timesteps ) __lowerCamelCase : Any = self.config.beta_min + t * (self.config.beta_max - self.config.beta_min) __lowerCamelCase : Dict = beta_t.flatten() while len(beta_t.shape ) < len(x.shape ): __lowerCamelCase : int = beta_t.unsqueeze(-1 ) __lowerCamelCase : Any = -0.5 * beta_t * x __lowerCamelCase : List[Any] = torch.sqrt(a ) __lowerCamelCase : Tuple = drift - diffusion**2 * score __lowerCamelCase : str = x + drift * dt # add noise __lowerCamelCase : Any = randn_tensor(x.shape , layout=x.layout , generator=a , device=x.device , dtype=x.dtype ) __lowerCamelCase : Any = x_mean + diffusion * math.sqrt(-dt ) * noise return x, x_mean def __len__( self: Optional[int] ): return self.config.num_train_timesteps
669
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 A__ : Optional[int] = logging.get_logger(__name__) @add_end_docstrings(_UpperCAmelCase ) class UpperCAmelCase_ (_UpperCAmelCase ): """simple docstring""" def __init__( self , **SCREAMING_SNAKE_CASE_ ) -> int: super().__init__(**SCREAMING_SNAKE_CASE_ ) 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 , SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: return super().__call__(SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) def lowercase_ ( self , **SCREAMING_SNAKE_CASE_ ) -> Optional[Any]: __lowerCamelCase : Dict = {} if "candidate_labels" in kwargs: __lowerCamelCase : List[str] = kwargs['candidate_labels'] if "hypothesis_template" in kwargs: __lowerCamelCase : Tuple = kwargs['hypothesis_template'] return preprocess_params, {}, {} def lowercase_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_="This is a photo of {}." ) -> Tuple: __lowerCamelCase : Union[str, Any] = load_image(SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : int = self.image_processor(images=[image] , return_tensors=self.framework ) __lowerCamelCase : Optional[Any] = candidate_labels __lowerCamelCase : int = [hypothesis_template.format(SCREAMING_SNAKE_CASE_ ) for x in candidate_labels] __lowerCamelCase : Union[str, Any] = self.tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors=self.framework , padding=SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : List[str] = [text_inputs] return inputs def lowercase_ ( self , SCREAMING_SNAKE_CASE_ ) -> Dict: __lowerCamelCase : Dict = model_inputs.pop('candidate_labels' ) __lowerCamelCase : int = model_inputs.pop('text_inputs' ) if isinstance(text_inputs[0] , SCREAMING_SNAKE_CASE_ ): __lowerCamelCase : List[Any] = text_inputs[0] else: # Batching case. __lowerCamelCase : Optional[Any] = text_inputs[0][0] __lowerCamelCase : Optional[int] = self.model(**SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) __lowerCamelCase : int = { 'candidate_labels': candidate_labels, 'logits': outputs.logits_per_image, } return model_outputs def lowercase_ ( self , SCREAMING_SNAKE_CASE_ ) -> Optional[int]: __lowerCamelCase : str = model_outputs.pop('candidate_labels' ) __lowerCamelCase : Union[str, Any] = model_outputs['logits'][0] if self.framework == "pt": __lowerCamelCase : List[Any] = logits.softmax(dim=-1 ).squeeze(-1 ) __lowerCamelCase : Dict = probs.tolist() if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): __lowerCamelCase : List[Any] = [scores] elif self.framework == "tf": __lowerCamelCase : Union[str, Any] = stable_softmax(SCREAMING_SNAKE_CASE_ , axis=-1 ) __lowerCamelCase : Optional[Any] = probs.numpy().tolist() else: raise ValueError(f'Unsupported framework: {self.framework}' ) __lowerCamelCase : Optional[Any] = [ {'score': score, 'label': candidate_label} for score, candidate_label in sorted(zip(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , key=lambda SCREAMING_SNAKE_CASE_ : -x[0] ) ] return result
13
def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): __lowerCamelCase : str = int(SCREAMING_SNAKE_CASE__ ) if n_element < 1: __lowerCamelCase : str = ValueError('a should be a positive number' ) raise my_error __lowerCamelCase : Tuple = [1] __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : List[Any] = (0, 0, 0) __lowerCamelCase : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": lowercase_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') lowercase_ = hamming(int(n)) print('-----------------------------------------------------') print(F"""The list with nth numbers is: {hamming_numbers}""") print('-----------------------------------------------------')
669
0
import os # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_doctest_list.py a__ = '''.''' if __name__ == "__main__": a__ = os.path.join(REPO_PATH, '''utils/documentation_tests.txt''') a__ = [] a__ = [] with open(doctest_file_path) as fp: for line in fp: a__ = line.strip() a__ = os.path.join(REPO_PATH, line) if not (os.path.isfile(path) or os.path.isdir(path)): non_existent_paths.append(line) all_paths.append(path) if len(non_existent_paths) > 0: a__ = '''\n'''.join(non_existent_paths) raise ValueError(f'''`utils/documentation_tests.txt` contains non-existent paths:\n{non_existent_paths}''') if all_paths != sorted(all_paths): raise ValueError('''Files in `utils/documentation_tests.txt` are not in alphabetical order.''')
14
import unittest from knapsack import greedy_knapsack as kp class A_ ( unittest.TestCase ): '''simple docstring''' def _snake_case ( self: List[Any] ): __lowerCamelCase : str = [10, 20, 30, 40, 50, 60] __lowerCamelCase : List[str] = [2, 4, 6, 8, 10, 12] __lowerCamelCase : Tuple = 100 self.assertEqual(kp.calc_profit(a , a , a ) , 210 ) def _snake_case ( self: str ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'Weight can not be negative.' ) def _snake_case ( self: Dict ): self.assertRaisesRegex(a , 'Profit can not be negative.' ) def _snake_case ( self: List[str] ): self.assertRaisesRegex(a , 'max_weight must greater than zero.' ) def _snake_case ( self: Any ): self.assertRaisesRegex( a , 'The length of profit and weight must be same.' ) if __name__ == "__main__": unittest.main()
669
0
A : Optional[Any] = [sum(int(c, 1_0) ** 2 for c in i.__str__()) for i in range(1_0_0_0_0_0)] def UpperCamelCase ( __magic_name__ : int ) -> int: """simple docstring""" lowercase__ = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 10_0000] number //= 10_0000 return sum_of_digits_squared # There are 2 Chains made, # One ends with 89 with the chain member 58 being the one which when declared first, # there will be the least number of iterations for all the members to be checked. # The other one ends with 1 and has only one element 1. # So 58 and 1 are chosen to be declared at the starting. # Changed dictionary to an array to quicken the solution A : list[bool | None] = [None] * 1_0_0_0_0_0_0_0 A : List[str] = True A : Union[str, Any] = False def UpperCamelCase ( __magic_name__ : int ) -> bool: """simple docstring""" if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore lowercase__ = chain(next_number(__magic_name__ ) ) lowercase__ = number_chain while number < 1000_0000: lowercase__ = number_chain number *= 10 return number_chain def UpperCamelCase ( __magic_name__ : int = 1000_0000 ) -> int: """simple docstring""" for i in range(1 , __magic_name__ ): if CHAINS[i] is None: chain(i + 1 ) return CHAINS[:number].count(__magic_name__ ) if __name__ == "__main__": import doctest doctest.testmod() print(F'{solution() = }')
15
from __future__ import annotations import copy import inspect import unittest import numpy as np from transformers import is_tf_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_tf, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST, TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING, LayoutLMvaConfig, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, TFLayoutLMvaModel, ) if is_vision_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class A_ : '''simple docstring''' def __init__( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any]=2 , a: str=3 , a: Any=4 , a: Union[str, Any]=2 , a: Tuple=7 , a: int=True , a: Tuple=True , a: List[str]=True , a: Union[str, Any]=True , a: str=99 , a: Tuple=36 , a: int=2 , a: Dict=4 , a: Union[str, Any]=37 , a: List[str]="gelu" , a: List[Any]=0.1 , a: Optional[int]=0.1 , a: Dict=512 , a: Union[str, Any]=16 , a: str=2 , a: int=0.0_2 , a: Optional[Any]=6 , a: Optional[int]=6 , a: Dict=3 , a: Optional[Any]=4 , a: Optional[Any]=None , a: Dict=1000 , ): __lowerCamelCase : List[str] = parent __lowerCamelCase : Optional[Any] = batch_size __lowerCamelCase : Optional[int] = num_channels __lowerCamelCase : str = image_size __lowerCamelCase : int = patch_size __lowerCamelCase : List[str] = is_training __lowerCamelCase : Dict = use_input_mask __lowerCamelCase : Any = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : str = vocab_size __lowerCamelCase : List[Any] = hidden_size __lowerCamelCase : List[Any] = num_hidden_layers __lowerCamelCase : Any = num_attention_heads __lowerCamelCase : List[Any] = intermediate_size __lowerCamelCase : List[Any] = hidden_act __lowerCamelCase : Any = hidden_dropout_prob __lowerCamelCase : Optional[int] = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : int = type_sequence_label_size __lowerCamelCase : List[str] = initializer_range __lowerCamelCase : List[str] = coordinate_size __lowerCamelCase : int = shape_size __lowerCamelCase : Union[str, Any] = num_labels __lowerCamelCase : int = num_choices __lowerCamelCase : int = scope __lowerCamelCase : Any = range_bbox # LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token) __lowerCamelCase : Any = text_seq_length __lowerCamelCase : Optional[Any] = (image_size // patch_size) ** 2 + 1 __lowerCamelCase : Any = self.text_seq_length + self.image_seq_length def _snake_case ( self: List[str] ): __lowerCamelCase : Any = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size ) __lowerCamelCase : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox ) __lowerCamelCase : int = bbox.numpy() # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: __lowerCamelCase : List[str] = bbox[i, j, 3] __lowerCamelCase : str = bbox[i, j, 1] __lowerCamelCase : Dict = tmp_coordinate if bbox[i, j, 2] < bbox[i, j, 0]: __lowerCamelCase : Tuple = bbox[i, j, 2] __lowerCamelCase : Any = bbox[i, j, 0] __lowerCamelCase : List[str] = tmp_coordinate __lowerCamelCase : str = tf.constant(a ) __lowerCamelCase : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase : Any = None if self.use_input_mask: __lowerCamelCase : int = random_attention_mask([self.batch_size, self.text_seq_length] ) __lowerCamelCase : Tuple = None if self.use_token_type_ids: __lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size ) __lowerCamelCase : Dict = None __lowerCamelCase : Union[str, Any] = None if self.use_labels: __lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels ) __lowerCamelCase : Dict = LayoutLMvaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , ) return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels def _snake_case ( self: Tuple , a: List[Any] , a: Any , a: List[str] , a: Dict , a: Optional[Any] , a: Dict ): __lowerCamelCase : Optional[Any] = TFLayoutLMvaModel(config=a ) # text + image __lowerCamelCase : Optional[Any] = model(a , pixel_values=a , training=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , training=a , ) __lowerCamelCase : List[Any] = model(a , bbox=a , pixel_values=a , training=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # text only __lowerCamelCase : List[Any] = model(a , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) ) # image only __lowerCamelCase : Optional[Any] = model({'pixel_values': pixel_values} , training=a ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) ) def _snake_case ( self: Dict , a: Dict , a: Optional[Any] , a: int , a: Optional[int] , a: List[str] , a: List[str] , a: List[str] ): __lowerCamelCase : List[str] = self.num_labels __lowerCamelCase : str = TFLayoutLMvaForSequenceClassification(config=a ) __lowerCamelCase : int = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self: Optional[int] , a: Union[str, Any] , a: Union[str, Any] , a: Dict , a: Optional[Any] , a: Tuple , a: Optional[Any] , a: List[Any] ): __lowerCamelCase : Union[str, Any] = self.num_labels __lowerCamelCase : Any = TFLayoutLMvaForTokenClassification(config=a ) __lowerCamelCase : Optional[Any] = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , labels=a , training=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) ) def _snake_case ( self: Dict , a: Optional[Any] , a: str , a: Dict , a: Union[str, Any] , a: List[Any] , a: Optional[int] , a: List[str] ): __lowerCamelCase : List[Any] = 2 __lowerCamelCase : Any = TFLayoutLMvaForQuestionAnswering(config=a ) __lowerCamelCase : Any = model( a , bbox=a , pixel_values=a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , training=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _snake_case ( self: List[Any] ): __lowerCamelCase : str = self.prepare_config_and_inputs() ((__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase) , (__lowerCamelCase)) : List[Any] = config_and_inputs __lowerCamelCase : Tuple = { 'input_ids': input_ids, 'bbox': bbox, 'pixel_values': pixel_values, 'token_type_ids': token_type_ids, 'attention_mask': input_mask, } return config, inputs_dict @require_tf class A_ ( __UpperCamelCase , __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = ( ( TFLayoutLMvaModel, TFLayoutLMvaForQuestionAnswering, TFLayoutLMvaForSequenceClassification, TFLayoutLMvaForTokenClassification, ) if is_tf_available() else () ) __snake_case = ( {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel} if is_tf_available() else {} ) __snake_case = False __snake_case = False __snake_case = False def _snake_case ( self: int , a: List[str] , a: Any , a: Optional[Any] , a: Tuple , a: Tuple ): return True def _snake_case ( self: str , a: Any , a: Any , a: Optional[int]=False ): __lowerCamelCase : List[str] = copy.deepcopy(a ) if model_class in get_values(a ): __lowerCamelCase : Tuple = { k: tf.tile(tf.expand_dims(a , 1 ) , (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) ) if isinstance(a , tf.Tensor ) and v.ndim > 0 else v for k, v in inputs_dict.items() } if return_labels: if model_class in get_values(a ): __lowerCamelCase : Any = tf.ones(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) __lowerCamelCase : Optional[Any] = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : str = tf.zeros(self.model_tester.batch_size , dtype=tf.intaa ) elif model_class in get_values(a ): __lowerCamelCase : Dict = tf.zeros( (self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=tf.intaa ) return inputs_dict def _snake_case ( self: Tuple ): __lowerCamelCase : int = TFLayoutLMvaModelTester(self ) __lowerCamelCase : str = ConfigTester(self , config_class=a , hidden_size=37 ) def _snake_case ( self: Union[str, Any] ): self.config_tester.run_common_tests() def _snake_case ( self: Union[str, Any] ): __lowerCamelCase , __lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase : int = model_class(a ) if getattr(a , 'hf_compute_loss' , a ): # The number of elements in the loss should be the same as the number of elements in the label __lowerCamelCase : Union[str, Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : int = prepared_for_class[ sorted(prepared_for_class.keys() - inputs_dict.keys() , reverse=a )[0] ] __lowerCamelCase : Dict = added_label.shape.as_list()[:1] # Test that model correctly compute the loss with kwargs __lowerCamelCase : Optional[int] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : Dict = prepared_for_class.pop('input_ids' ) __lowerCamelCase : str = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss when we mask some positions __lowerCamelCase : List[Any] = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : List[str] = prepared_for_class.pop('input_ids' ) if "labels" in prepared_for_class: __lowerCamelCase : int = prepared_for_class['labels'].numpy() if len(labels.shape ) > 1 and labels.shape[1] != 1: __lowerCamelCase : Tuple = -100 __lowerCamelCase : Tuple = tf.convert_to_tensor(a ) __lowerCamelCase : Tuple = model(a , **a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) self.assertTrue(not np.any(np.isnan(loss.numpy() ) ) ) # Test that model correctly compute the loss with a dict __lowerCamelCase : int = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) __lowerCamelCase : str = model(a )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) # Test that model correctly compute the loss with a tuple __lowerCamelCase : str = self._prepare_for_class(inputs_dict.copy() , a , return_labels=a ) # Get keys that were added with the _prepare_for_class function __lowerCamelCase : Optional[Any] = prepared_for_class.keys() - inputs_dict.keys() __lowerCamelCase : List[Any] = inspect.signature(model.call ).parameters __lowerCamelCase : List[str] = list(signature.keys() ) # Create a dictionary holding the location of the tensors in the tuple __lowerCamelCase : Optional[int] = {0: 'input_ids'} for label_key in label_keys: __lowerCamelCase : Dict = signature_names.index(a ) __lowerCamelCase : str = label_key __lowerCamelCase : List[str] = sorted(tuple_index_mapping.items() ) # Initialize a list with their default values, update the values and convert to a tuple __lowerCamelCase : Optional[int] = [] for name in signature_names: if name != "kwargs": list_input.append(signature[name].default ) for index, value in sorted_tuple_index_mapping: __lowerCamelCase : Optional[int] = prepared_for_class[value] __lowerCamelCase : Any = tuple(a ) # Send to model __lowerCamelCase : int = model(tuple_input[:-1] )[0] self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1] ) def _snake_case ( self: List[str] ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: int ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __lowerCamelCase : Union[str, Any] = type self.model_tester.create_and_check_model(a , a , a , a , a , a ) def _snake_case ( self: Dict ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification( a , a , a , a , a , a , a ) def _snake_case ( self: str ): ( ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ( __lowerCamelCase ) , ) : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering( a , a , a , a , a , a , a ) @slow def _snake_case ( self: int ): for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCamelCase : Dict = TFLayoutLMvaModel.from_pretrained(a ) self.assertIsNotNone(a ) def UpperCamelCase__ ( ): __lowerCamelCase : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def _snake_case ( self: Optional[int] ): return LayoutLMvaImageProcessor(apply_ocr=a ) if is_vision_available() else None @slow def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Tuple = TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ) __lowerCamelCase : Union[str, Any] = self.default_image_processor __lowerCamelCase : List[Any] = prepare_img() __lowerCamelCase : str = image_processor(images=a , return_tensors='tf' ).pixel_values __lowerCamelCase : Union[str, Any] = tf.constant([[1, 2]] ) __lowerCamelCase : str = tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]] ) , axis=0 ) # forward pass __lowerCamelCase : int = model(input_ids=a , bbox=a , pixel_values=a , training=a ) # verify the logits __lowerCamelCase : Optional[int] = (1, 199, 768) self.assertEqual(outputs.last_hidden_state.shape , a ) __lowerCamelCase : Any = tf.constant( [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]] ) self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3] , a , atol=1e-4 ) )
669
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __A : Optional[int] = { 'configuration_xlm': ['XLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XLMConfig', 'XLMOnnxConfig'], 'tokenization_xlm': ['XLMTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A : Any = [ '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: __A : List[Any] = [ '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 __A : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
16
import json import os import unittest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_ftfy, require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class A_ ( __UpperCamelCase , unittest.TestCase ): '''simple docstring''' __snake_case = CLIPTokenizer __snake_case = CLIPTokenizerFast __snake_case = True __snake_case = {} __snake_case = False def _snake_case ( self: Union[str, Any] ): super().setUp() # fmt: off __lowerCamelCase : Any = ['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 __lowerCamelCase : Tuple = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase : List[Any] = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>'] __lowerCamelCase : Tuple = {'unk_token': '<unk>'} __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) __lowerCamelCase : 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(a ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a ) ) def _snake_case ( self: Tuple , **a: Union[str, Any] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizer.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Union[str, Any] , **a: List[str] ): kwargs.update(self.special_tokens_map ) return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a ) def _snake_case ( self: Optional[int] , a: List[Any] ): __lowerCamelCase : Tuple = 'lower newer' __lowerCamelCase : Tuple = 'lower newer' return input_text, output_text def _snake_case ( self: List[str] ): __lowerCamelCase : List[Any] = CLIPTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase : Optional[Any] = 'lower newer' __lowerCamelCase : int = ['lo', 'w', 'er</w>', 'n', 'e', 'w', 'er</w>'] __lowerCamelCase : Optional[int] = tokenizer.tokenize(a ) self.assertListEqual(a , a ) __lowerCamelCase : int = tokens + [tokenizer.unk_token] __lowerCamelCase : int = [10, 2, 16, 9, 3, 2, 16, 20] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a ) @require_ftfy def _snake_case ( self: Union[str, Any] ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : List[Any] = self.tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : int = self.rust_tokenizer_class.from_pretrained(a , **a ) __lowerCamelCase : str = 'A\n\'ll 11p223RF☆ho!!to?\'d\'d\'\'d of a cat to-$\'\'d.' __lowerCamelCase : Optional[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[Any] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on an example containing a character (Latin Small Letter A # with Tilde) encoded in 2 different ways __lowerCamelCase : List[Any] = 'xa\u0303y' + ' ' + 'x\xe3y' __lowerCamelCase : Tuple = tokenizer_s.tokenize(a ) __lowerCamelCase : Any = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of space type __lowerCamelCase : List[Any] = [ '\u0009', # (horizontal tab, '\t') '\u000B', # (vertical tab) '\u000C', # (form feed) '\u0020', # (space, ' ') '\u200E', # (left-to-right mark):w '\u200F', # (right-to-left mark) ] for unicode_seq in spaces_unicodes: __lowerCamelCase : List[Any] = tokenizer_s.tokenize(a ) __lowerCamelCase : Optional[int] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) # Test that the tokenization is identical on unicode of line break type __lowerCamelCase : str = [ '\u000A', # (line feed, '\n') '\r\n', # (carriage return and line feed, '\r\n') '\u000D', # (carriage return, '\r') '\r', # (carriage return, '\r') '\u000D', # (carriage return, '\r') '\u2028', # (line separator) '\u2029', # (paragraph separator) # "\u0085", # (next line) ] # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a # space (and thus into an empty list). for unicode_seq in line_break_unicodes: __lowerCamelCase : Dict = tokenizer_s.tokenize(a ) __lowerCamelCase : List[str] = tokenizer_r.tokenize(a ) self.assertListEqual(a , a ) def _snake_case ( self: List[Any] ): # Test which aims to verify that the offsets are well adapted to the argument `add_prefix_space` for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): __lowerCamelCase : Optional[int] = 'hello' # `hello` is a token in the vocabulary of `pretrained_name` __lowerCamelCase : Optional[int] = F'{text_of_1_token} {text_of_1_token}' __lowerCamelCase : Dict = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (0, len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (len(a ) + 1, len(a ) + 1 + len(a )) , ) __lowerCamelCase : List[Any] = F' {text}' __lowerCamelCase : str = self.rust_tokenizer_class.from_pretrained( a , use_fast=a , ) __lowerCamelCase : Any = tokenizer_r(a , return_offsets_mapping=a , add_special_tokens=a ) self.assertEqual(encoding.offset_mapping[0] , (1, 1 + len(a )) ) self.assertEqual( encoding.offset_mapping[1] , (1 + len(a ) + 1, 1 + len(a ) + 1 + len(a )) , ) def _snake_case ( self: str ): # Test related to the breaking change introduced in transformers v4.17.0 # We need to check that an error in raised when the user try to load a previous version of the tokenizer. with self.assertRaises(a ) as context: self.rust_tokenizer_class.from_pretrained('robot-test/old-clip-tokenizer' ) self.assertTrue( context.exception.args[0].startswith( 'The `backend_tokenizer` provided does not match the expected format.' ) ) @require_ftfy def _snake_case ( self: Tuple ): super().test_tokenization_python_rust_equals() def _snake_case ( self: Tuple ): # CLIP always lower cases letters pass
669
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) UpperCAmelCase_ : Any = { '''configuration_roberta''': ['''ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''RobertaConfig''', '''RobertaOnnxConfig'''], '''tokenization_roberta''': ['''RobertaTokenizer'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : Union[str, Any] = ['''RobertaTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = [ '''ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''RobertaForCausalLM''', '''RobertaForMaskedLM''', '''RobertaForMultipleChoice''', '''RobertaForQuestionAnswering''', '''RobertaForSequenceClassification''', '''RobertaForTokenClassification''', '''RobertaModel''', '''RobertaPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = [ '''TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFRobertaForCausalLM''', '''TFRobertaForMaskedLM''', '''TFRobertaForMultipleChoice''', '''TFRobertaForQuestionAnswering''', '''TFRobertaForSequenceClassification''', '''TFRobertaForTokenClassification''', '''TFRobertaMainLayer''', '''TFRobertaModel''', '''TFRobertaPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : List[Any] = [ '''FlaxRobertaForCausalLM''', '''FlaxRobertaForMaskedLM''', '''FlaxRobertaForMultipleChoice''', '''FlaxRobertaForQuestionAnswering''', '''FlaxRobertaForSequenceClassification''', '''FlaxRobertaForTokenClassification''', '''FlaxRobertaModel''', '''FlaxRobertaPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_roberta import ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP, RobertaConfig, RobertaOnnxConfig from .tokenization_roberta import RobertaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roberta_fast import RobertaTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roberta import ( ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, RobertaForCausalLM, RobertaForMaskedLM, RobertaForMultipleChoice, RobertaForQuestionAnswering, RobertaForSequenceClassification, RobertaForTokenClassification, RobertaModel, RobertaPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roberta import ( TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST, TFRobertaForCausalLM, TFRobertaForMaskedLM, TFRobertaForMultipleChoice, TFRobertaForQuestionAnswering, TFRobertaForSequenceClassification, TFRobertaForTokenClassification, TFRobertaMainLayer, TFRobertaModel, TFRobertaPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roberta import ( FlaxRobertaForCausalLM, FlaxRobertaForMaskedLM, FlaxRobertaForMultipleChoice, FlaxRobertaForQuestionAnswering, FlaxRobertaForSequenceClassification, FlaxRobertaForTokenClassification, FlaxRobertaModel, FlaxRobertaPreTrainedModel, ) else: import sys UpperCAmelCase_ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
17
import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP lowercase_ = False try: lowercase_ = _is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class A_ : '''simple docstring''' def __init__( self: int , a: str = None , a: list = [] ): __lowerCamelCase : Dict = 0 __lowerCamelCase : Dict = choices __lowerCamelCase : Tuple = prompt if sys.platform == "win32": __lowerCamelCase : Union[str, Any] = '*' else: __lowerCamelCase : Any = '➔ ' def _snake_case ( self: Any , a: Tuple , a: str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , a ) else: forceWrite(self.choices[index] , a ) def _snake_case ( self: Tuple , a: int ): if index == self.position: forceWrite(F' {self.arrow_char} ' ) self.write_choice(a ) else: forceWrite(F' {self.choices[index]}' ) reset_cursor() def _snake_case ( self: Optional[int] , a: Direction , a: int = 1 ): __lowerCamelCase : str = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(a ) move_cursor(a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP['up'] ) def _snake_case ( self: Tuple ): self.move_direction(Direction.UP ) @input.mark(KEYMAP['down'] ) def _snake_case ( self: Optional[int] ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP['newline'] ) def _snake_case ( self: str ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) return self.position @input.mark(KEYMAP['interrupt'] ) def _snake_case ( self: Union[str, Any] ): move_cursor(len(self.choices ) - self.position , 'DOWN' ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(a )] for number in range(10 )] ) def _snake_case ( self: str ): __lowerCamelCase : List[Any] = int(chr(self.current_selection ) ) __lowerCamelCase : Any = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , a ) else: return else: return def _snake_case ( self: str , a: int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , '\n' ) if in_colab: forceWrite('Please input a choice index (starting from 0), and press enter' , '\n' ) else: forceWrite('Please select a choice using the arrow or number keys, and selecting with enter' , '\n' ) __lowerCamelCase : Dict = default_choice for i in range(len(self.choices ) ): self.print_choice(a ) forceWrite('\n' ) move_cursor(len(self.choices ) - self.position , 'UP' ) with cursor.hide(): while True: if in_colab: try: __lowerCamelCase : Any = int(builtins.input() ) except ValueError: __lowerCamelCase : str = default_choice else: __lowerCamelCase : Optional[int] = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , 'UP' ) clear_line() self.write_choice(a , '\n' ) return choice
669
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE = { # See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert } class lowerCAmelCase_ ( __magic_name__ ): __lowerCamelCase : Any = "megatron-bert" def __init__( self , _lowerCAmelCase=29056 , _lowerCAmelCase=1024 , _lowerCAmelCase=24 , _lowerCAmelCase=16 , _lowerCAmelCase=4096 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=512 , _lowerCAmelCase=2 , _lowerCAmelCase=0.02 , _lowerCAmelCase=1E-12 , _lowerCAmelCase=0 , _lowerCAmelCase="absolute" , _lowerCAmelCase=True , **_lowerCAmelCase , ) -> Optional[int]: super().__init__(pad_token_id=_lowerCAmelCase , **_lowerCAmelCase ) _lowerCAmelCase = vocab_size _lowerCAmelCase = hidden_size _lowerCAmelCase = num_hidden_layers _lowerCAmelCase = num_attention_heads _lowerCAmelCase = hidden_act _lowerCAmelCase = intermediate_size _lowerCAmelCase = hidden_dropout_prob _lowerCAmelCase = attention_probs_dropout_prob _lowerCAmelCase = max_position_embeddings _lowerCAmelCase = type_vocab_size _lowerCAmelCase = initializer_range _lowerCAmelCase = layer_norm_eps _lowerCAmelCase = position_embedding_type _lowerCAmelCase = use_cache
18
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class A_ ( __UpperCamelCase ): '''simple docstring''' __snake_case = (CMStochasticIterativeScheduler,) __snake_case = 10 def _snake_case ( self: Any , **a: Dict ): __lowerCamelCase : Optional[Any] = { 'num_train_timesteps': 201, 'sigma_min': 0.0_0_2, 'sigma_max': 8_0.0, } config.update(**a ) return config def _snake_case ( self: List[Any] ): __lowerCamelCase : Any = 10 __lowerCamelCase : Any = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = self.scheduler_classes[0](**a ) scheduler.set_timesteps(a ) __lowerCamelCase : Any = scheduler.timesteps[0] __lowerCamelCase : List[str] = scheduler.timesteps[1] __lowerCamelCase : Union[str, Any] = self.dummy_sample __lowerCamelCase : int = 0.1 * sample __lowerCamelCase : Optional[Any] = scheduler.step(a , a , a ).prev_sample __lowerCamelCase : List[str] = scheduler.step(a , a , a ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def _snake_case ( self: Optional[Any] ): for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a ) def _snake_case ( self: List[str] ): for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=a ) def _snake_case ( self: Tuple ): __lowerCamelCase : Tuple = self.scheduler_classes[0] __lowerCamelCase : Tuple = self.get_scheduler_config() __lowerCamelCase : Tuple = scheduler_class(**a ) __lowerCamelCase : int = 1 scheduler.set_timesteps(a ) __lowerCamelCase : Optional[int] = scheduler.timesteps __lowerCamelCase : List[str] = torch.manual_seed(0 ) __lowerCamelCase : Union[str, Any] = self.dummy_model() __lowerCamelCase : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(a ): # 1. scale model input __lowerCamelCase : List[str] = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Optional[int] = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : str = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : str = pred_prev_sample __lowerCamelCase : List[str] = torch.sum(torch.abs(a ) ) __lowerCamelCase : str = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 1_9_2.7_6_1_4 ) < 1e-2 assert abs(result_mean.item() - 0.2_5_1_0 ) < 1e-3 def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Optional[Any] = self.get_scheduler_config() __lowerCamelCase : int = scheduler_class(**a ) __lowerCamelCase : List[Any] = [106, 0] scheduler.set_timesteps(timesteps=a ) __lowerCamelCase : Dict = scheduler.timesteps __lowerCamelCase : int = torch.manual_seed(0 ) __lowerCamelCase : Any = self.dummy_model() __lowerCamelCase : Optional[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __lowerCamelCase : Tuple = scheduler.scale_model_input(a , a ) # 2. predict noise residual __lowerCamelCase : Tuple = model(a , a ) # 3. predict previous sample x_t-1 __lowerCamelCase : Any = scheduler.step(a , a , a , generator=a ).prev_sample __lowerCamelCase : Any = pred_prev_sample __lowerCamelCase : Dict = torch.sum(torch.abs(a ) ) __lowerCamelCase : Optional[Any] = torch.mean(torch.abs(a ) ) assert abs(result_sum.item() - 3_4_7.6_3_5_7 ) < 1e-2 assert abs(result_mean.item() - 0.4_5_2_7 ) < 1e-3 def _snake_case ( self: Tuple ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : int = self.get_scheduler_config() __lowerCamelCase : List[Any] = scheduler_class(**a ) __lowerCamelCase : Optional[Any] = [39, 30, 12, 15, 0] with self.assertRaises(a , msg='`timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=a ) def _snake_case ( self: int ): __lowerCamelCase : Any = self.scheduler_classes[0] __lowerCamelCase : Union[str, Any] = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [39, 30, 12, 1, 0] __lowerCamelCase : List[Any] = len(a ) with self.assertRaises(a , msg='Can only pass one of `num_inference_steps` or `timesteps`.' ): scheduler.set_timesteps(num_inference_steps=a , timesteps=a ) def _snake_case ( self: Optional[Any] ): __lowerCamelCase : Optional[int] = self.scheduler_classes[0] __lowerCamelCase : Dict = self.get_scheduler_config() __lowerCamelCase : Union[str, Any] = scheduler_class(**a ) __lowerCamelCase : Optional[int] = [scheduler.config.num_train_timesteps] with self.assertRaises( a , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=a )
669
0
"""simple docstring""" def lowerCamelCase__ ( __snake_case ) -> int: """simple docstring""" if a < 0: raise ValueError('''Input value must be a positive integer''' ) elif isinstance(__snake_case, __snake_case ): raise TypeError('''Input value must be a \'int\' type''' ) return bin(__snake_case ).count('''1''' ) if __name__ == "__main__": import doctest doctest.testmod()
19
from datetime import datetime import requests from bsa import BeautifulSoup if __name__ == "__main__": lowercase_ = input('Enter image url: ').strip() print(F"""Downloading image from {url} ...""") lowercase_ = BeautifulSoup(requests.get(url).content, 'html.parser') # The image URL is in the content field of the first meta tag with property og:image lowercase_ = soup.find('meta', {'property': 'og:image'})['content'] lowercase_ = requests.get(image_url).content lowercase_ = F"""{datetime.now():%Y-%m-%d_%H:%M:%S}.jpg""" with open(file_name, 'wb') as fp: fp.write(image_data) print(F"""Done. Image saved to disk as {file_name}.""")
669
0