code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
"""simple docstring""" import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() _a = logging.get_logger(__name__) _a = { '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', 'encoder.layer_norm_for_extract': 'layer_norm_for_extract', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'label_embs_concat': 'label_embeddings_concat', 'mask_emb': 'masked_spec_embed', 'spk_proj': 'speaker_proj', } _a = [ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', 'label_embeddings_concat', 'speaker_proj', 'layer_norm_for_extract', ] def _A ( UpperCamelCase_ : int, UpperCamelCase_ : Any, UpperCamelCase_ : int, UpperCamelCase_ : Union[str, Any], UpperCamelCase_ : Any) -> List[Any]: '''simple docstring''' for attribute in key.split("."): __lowercase = getattr(__a, __a) if weight_type is not None: __lowercase = getattr(__a, __a).shape else: __lowercase = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""") if weight_type == "weight": __lowercase = value elif weight_type == "weight_g": __lowercase = value elif weight_type == "weight_v": __lowercase = value elif weight_type == "bias": __lowercase = value else: __lowercase = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""") def _A ( UpperCamelCase_ : int, UpperCamelCase_ : Tuple) -> Union[str, Any]: '''simple docstring''' __lowercase = [] __lowercase = fairseq_model.state_dict() __lowercase = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): __lowercase = False if "conv_layers" in name: load_conv_layer( __a, __a, __a, __a, hf_model.config.feat_extract_norm == "group", ) __lowercase = True else: for key, mapped_key in MAPPING.items(): __lowercase = '''unispeech_sat.''' + 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]: if "layer_norm_for_extract" in name and (".".join(name.split(".")[:-1]) != key): # special case since naming is very similar continue __lowercase = True if "*" in mapped_key: __lowercase = name.split(__a)[0].split(".")[-2] __lowercase = mapped_key.replace("*", __a) if "weight_g" in name: __lowercase = '''weight_g''' elif "weight_v" in name: __lowercase = '''weight_v''' elif "bias" in name: __lowercase = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowercase = '''weight''' else: __lowercase = None set_recursively(__a, __a, __a, __a, __a) continue if not is_used: unused_weights.append(__a) logger.warning(F"""Unused weights: {unused_weights}""") def _A ( UpperCamelCase_ : Any, UpperCamelCase_ : str, UpperCamelCase_ : List[Any], UpperCamelCase_ : List[str], UpperCamelCase_ : str) -> List[Any]: '''simple docstring''' __lowercase = full_name.split("conv_layers.")[-1] __lowercase = name.split(".") __lowercase = int(items[0]) __lowercase = int(items[1]) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""") __lowercase = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""") elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""") __lowercase = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""") elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""") __lowercase = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""") elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""") __lowercase = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""") else: unused_weights.append(__a) @torch.no_grad() def _A ( UpperCamelCase_ : Optional[int], UpperCamelCase_ : List[str], UpperCamelCase_ : Dict=None, UpperCamelCase_ : Any=None, UpperCamelCase_ : Union[str, Any]=True) -> str: '''simple docstring''' if config_path is not None: __lowercase = UniSpeechSatConfig.from_pretrained(__a) else: __lowercase = UniSpeechSatConfig() __lowercase = '''''' if is_finetuned: __lowercase = UniSpeechSatForCTC(__a) else: __lowercase = UniSpeechSatForPreTraining(__a) __lowercase = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={"data": "/".join(dict_path.split("/")[:-1])}) __lowercase = model[0].eval() recursively_load_weights(__a, __a) hf_wavavec.save_pretrained(__a) if __name__ == "__main__": _a = 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' ) _a = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
17
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging a__ = logging.get_logger(__name__) a__ = { '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json''', '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json''', '''junnyu/roformer_chinese_char_small''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json''' ), '''junnyu/roformer_chinese_char_base''': ( '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json''' ), '''junnyu/roformer_small_discriminator''': ( '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json''' ), '''junnyu/roformer_small_generator''': ( '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json''' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = "roformer" def __init__( self , _a=5_0_0_0_0 , _a=None , _a=7_6_8 , _a=1_2 , _a=1_2 , _a=3_0_7_2 , _a="gelu" , _a=0.1 , _a=0.1 , _a=1_5_3_6 , _a=2 , _a=0.02 , _a=1e-1_2 , _a=0 , _a=False , _a=True , **_a , ) -> List[str]: super().__init__(pad_token_id=_a , **_a ) _a : Tuple = vocab_size _a : List[Any] = hidden_size if embedding_size is None else embedding_size _a : Any = hidden_size _a : Any = num_hidden_layers _a : List[Any] = num_attention_heads _a : str = hidden_act _a : Any = intermediate_size _a : Dict = hidden_dropout_prob _a : Optional[Any] = attention_probs_dropout_prob _a : str = max_position_embeddings _a : Dict = type_vocab_size _a : List[Any] = initializer_range _a : Dict = layer_norm_eps _a : Dict = rotary_value _a : Dict = use_cache class UpperCAmelCase_ ( __lowercase ): """simple docstring""" @property def __lowercase ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _a : Dict = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _a : List[Any] = {0: '''batch''', 1: '''sequence'''} _a : Union[str, Any] = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
235
0
"""simple docstring""" # HF Trainer benchmarking tool # # This tool can be used to run and compare multiple dimensions of the HF Trainers args. # # It then prints a report once in github format with all the information that needs to be shared # with others and second time in a console-friendly format, so it's easier to use for tuning things up. # # The main idea is: # # ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \ # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \ # --target-metric-key train_samples_per_second # # The variations can be any command line argument that you want to compare and not just dtype as in # the example. # # --variations allows you to compare variations in multiple dimensions. # # as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6 # times adding one of: # # 1. --tf32 0 --fp16 0 # 2. --tf32 0 --fp16 1 # 3. --tf32 0 --bf16 1 # 4. --tf32 1 --fp16 0 # 5. --tf32 1 --fp16 1 # 6. --tf32 1 --bf16 1 # # and print the results. This is just a cartesian product - and more than 2 dimensions can be used. # # If you want to rely on defaults, this: # --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' # is identical to this: # --variations '--tf32 0|--tf32 1' '|--fp16|--bf16' # # the leading empty variation in the 2nd dimension is a valid variation. # # So here we get the following 6 variations: # # 1. --tf32 0 # 2. --tf32 0 --fp16 # 3. --tf32 0 --bf16 # 4. --tf32 1 # 5. --tf32 1 --fp16 # 6. --tf32 1 --bf16 # # In this particular case we don't know what the default tf32 setting is as it's normally # pytorch-version dependent). That's why it's best to do an explicit setting of each variation: # `--tf32 0|--tf32 1` # # Here is a full example of a train: # # CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \ # --base-cmd \ # ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \ # --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \ # --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \ # --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \ # --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \ # --source_prefix "translate English to Romanian: " --warmup_steps 50 \ # --max_train_samples 20000 --dataloader_num_workers 2 ' \ # --target-metric-key train_samples_per_second --repeat-times 1 --variations \ # '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \ # --repeat-times 1 --base-variation '--tf32 0' # # and here is a possible output: # # # | Variation | Train | Diff | Train | # | | samples | % | loss | # | | per | | | # | | second | | | # |:----------------|----------:|-------:|--------:| # | --tf32 0 | 285.11 | 0 | 2.51 | # | --tf32 1 | 342.09 | 20 | 2.51 | # | --fp16 --tf32 0 | 423.49 | 49 | 2.51 | # | --fp16 --tf32 1 | 423.13 | 48 | 2.51 | # | --bf16 --tf32 0 | 416.80 | 46 | 2.52 | # | --bf16 --tf32 1 | 415.87 | 46 | 2.52 | # # # So you can quickly compare the different outcomes. # # Typically running each experiment once is enough, but if the environment is unstable you can # re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results. # # By default it'll use the lowest result as the base line to use as 100% and then compare the rest to # it as can be seen from the table above, but you can also specify which combination is the one to use as # the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0' # # --target-metric-key is there to tell the program which metrics to compare - the different metric keys are # inside output_dir/all_results.json. e.g., to measure eval performance instead of train use: # --target-metric-key eval_samples_per_second # but of course you will need to adjust the --base-cmd value in the example to perform evaluation as # well (as currently it doesn't) # import argparse import datetime import io import itertools import json import math import os import platform import re import shlex import subprocess import sys from pathlib import Path from statistics import fmean import pandas as pd import torch from tqdm import tqdm import transformers lowercase_ = float("""nan""") class SCREAMING_SNAKE_CASE : def __init__( self : List[Any] , a : int )-> Any: """simple docstring""" lowercase__ = sys.stdout lowercase__ = open(SCREAMING_SNAKE_CASE_ , 'a' ) def __getattr__( self : List[str] , a : List[str] )-> Dict: """simple docstring""" return getattr(self.stdout , SCREAMING_SNAKE_CASE_ ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] , a : List[str] )-> Tuple: """simple docstring""" self.stdout.write(SCREAMING_SNAKE_CASE_ ) # strip tqdm codes self.file.write(re.sub(R'^.*\r' , '' , SCREAMING_SNAKE_CASE_ , 0 , re.M ) ) def __UpperCamelCase (_SCREAMING_SNAKE_CASE=80 , _SCREAMING_SNAKE_CASE=False ) -> Any: lowercase__ = [] # deal with critical env vars lowercase__ = ['CUDA_VISIBLE_DEVICES'] for key in env_keys: lowercase__ = os.environ.get(snake_case__ , snake_case__ ) if val is not None: cmd.append(F"""{key}={val}""" ) # python executable (not always needed if the script is executable) lowercase__ = sys.executable if full_python_path else sys.executable.split('/' )[-1] cmd.append(snake_case__ ) # now the normal args cmd += list(map(shlex.quote , sys.argv ) ) # split up into up to MAX_WIDTH lines with shell multi-line escapes lowercase__ = [] lowercase__ = '' while len(snake_case__ ) > 0: current_line += F"""{cmd.pop(0 )} """ if len(snake_case__ ) == 0 or len(snake_case__ ) + len(cmd[0] ) + 1 > max_width - 1: lines.append(snake_case__ ) lowercase__ = '' return "\\\n".join(snake_case__ ) def __UpperCamelCase (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> str: # unwrap multi-line input lowercase__ = re.sub(R'[\\\n]+' , ' ' , args.base_cmd ) # remove --output_dir if any and set our own lowercase__ = re.sub('--output_dir\s+[^\s]+' , '' , args.base_cmd ) args.base_cmd += F""" --output_dir {output_dir}""" # ensure we have --overwrite_output_dir lowercase__ = re.sub('--overwrite_output_dir\s+' , '' , args.base_cmd ) args.base_cmd += " --overwrite_output_dir" return [sys.executable] + shlex.split(args.base_cmd ) def __UpperCamelCase (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Optional[Any]: # Enable to debug everything but the run itself, to do it fast and see the progress. # This is useful for debugging the output formatting quickly - we can remove it later once # everybody is happy with the output if 0: import random from time import sleep sleep(0 ) return dict( {k: random.uniform(0 , 100 ) for k in metric_keys} , **{target_metric_key: random.choice([nan, 1_0.3_1, 1_0_0.2, 5_5.6_6_6_6, 2_2_2.2_2_2_2_2_2_2_2] )} , ) lowercase__ = subprocess.run(snake_case__ , capture_output=snake_case__ , text=snake_case__ ) if verbose: print('STDOUT' , result.stdout ) print('STDERR' , result.stderr ) # save the streams lowercase__ = variation.replace(' ' , '-' ) with open(Path(snake_case__ ) / F"""log.{prefix}.stdout.txt""" , 'w' ) as f: f.write(result.stdout ) with open(Path(snake_case__ ) / F"""log.{prefix}.stderr.txt""" , 'w' ) as f: f.write(result.stderr ) if result.returncode != 0: if verbose: print('failed' ) return {target_metric_key: nan} with io.open(F"""{output_dir}/all_results.json""" , 'r' , encoding='utf-8' ) as f: lowercase__ = json.load(snake_case__ ) # filter out just the keys we want return {k: v for k, v in metrics.items() if k in metric_keys} 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 , _SCREAMING_SNAKE_CASE , ) -> str: lowercase__ = [] lowercase__ = [] lowercase__ = F"""{id}: {variation:<{longest_variation_len}}""" lowercase__ = F"""{preamble}: """ lowercase__ = set(report_metric_keys + [target_metric_key] ) for i in tqdm(range(snake_case__ ) , desc=snake_case__ , leave=snake_case__ ): lowercase__ = process_run_single( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ) lowercase__ = single_run_metrics[target_metric_key] if not math.isnan(snake_case__ ): metrics.append(snake_case__ ) results.append(snake_case__ ) outcome += "✓" else: outcome += "✘" lowercase__ = F"""\33[2K\r{outcome}""" if len(snake_case__ ) > 0: lowercase__ = {k: fmean([x[k] for x in metrics] ) for k in metrics[0].keys()} lowercase__ = round(mean_metrics[target_metric_key] , 2 ) lowercase__ = F"""{outcome} {mean_target}""" if len(snake_case__ ) > 1: results_str += F""" {tuple(round(snake_case__ , 2 ) for x in results )}""" print(snake_case__ ) lowercase__ = variation return mean_metrics else: print(snake_case__ ) return {variation_key: variation, target_metric_key: nan} def __UpperCamelCase () -> str: lowercase__ = torch.cuda.get_device_properties(torch.device('cuda' ) ) return F""" Datetime : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S" )} Software: transformers: {transformers.__version__} torch : {torch.__version__} cuda : {torch.version.cuda} python : {platform.python_version()} Hardware: {torch.cuda.device_count()} GPUs : {properties.name}, {properties.total_memory/2**30:0.2f}GB """ def __UpperCamelCase (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: lowercase__ = pd.DataFrame(snake_case__ ) lowercase__ = 'variation' lowercase__ = 'diff_%' lowercase__ = nan if base_variation is not None and len(df[df[variation_key] == base_variation] ): # this may still return nan lowercase__ = df.loc[df[variation_key] == base_variation][target_metric_key].item() if math.isnan(snake_case__ ): # as a fallback, use the minimal value as the sentinel lowercase__ = df.loc[df[target_metric_key] != nan][target_metric_key].min() # create diff column if possible if not math.isnan(snake_case__ ): lowercase__ = df.apply( lambda _SCREAMING_SNAKE_CASE : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value ) if not math.isnan(r[target_metric_key] ) else 0 , axis='columns' , ) # re-order columns lowercase__ = [variation_key, target_metric_key, diff_key, *report_metric_keys] lowercase__ = df.reindex(snake_case__ , axis='columns' ) # reorder cols # capitalize lowercase__ = df.rename(str.capitalize , axis='columns' ) # make the cols as narrow as possible lowercase__ = df.rename(lambda _SCREAMING_SNAKE_CASE : c.replace('_' , '<br>' ) , axis='columns' ) lowercase__ = df.rename(lambda _SCREAMING_SNAKE_CASE : c.replace('_' , '\n' ) , axis='columns' ) lowercase__ = ['', 'Copy between the cut-here-lines and paste as is to github or a forum'] report += ["----------8<-----------------8<--------"] report += ["*** Results:", df_github.to_markdown(index=snake_case__ , floatfmt='.2f' )] report += ["```"] report += ["*** Setup:", get_versions()] report += ["*** The benchmark command line was:", get_original_command()] report += ["```"] report += ["----------8<-----------------8<--------"] report += ["*** Results (console):", df_console.to_markdown(index=snake_case__ , floatfmt='.2f' )] print('\n\n'.join(snake_case__ ) ) def __UpperCamelCase () -> Any: lowercase__ = argparse.ArgumentParser() parser.add_argument( '--base-cmd' , default=snake_case__ , type=snake_case__ , required=snake_case__ , help='Base cmd' , ) parser.add_argument( '--variations' , default=snake_case__ , type=snake_case__ , nargs='+' , required=snake_case__ , help='Multi-dimensional variations, example: \'|--fp16|--bf16\' \'|--tf32\'' , ) parser.add_argument( '--base-variation' , default=snake_case__ , type=snake_case__ , help='Baseline variation to compare to. if None the minimal target value will be used to compare against' , ) parser.add_argument( '--target-metric-key' , default=snake_case__ , type=snake_case__ , required=snake_case__ , help='Target metric key in output_dir/all_results.json, e.g., train_samples_per_second' , ) parser.add_argument( '--report-metric-keys' , default='' , type=snake_case__ , help='Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., \'train_loss train_samples' , ) parser.add_argument( '--repeat-times' , default=1 , type=snake_case__ , help='How many times to re-run each variation - an average will be reported' , ) parser.add_argument( '--output_dir' , default='output_benchmark' , type=snake_case__ , help='The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked' , ) parser.add_argument( '--verbose' , default=snake_case__ , action='store_true' , help='Whether to show the outputs of each run or just the benchmark progress' , ) lowercase__ = parser.parse_args() lowercase__ = args.output_dir Path(snake_case__ ).mkdir(exist_ok=snake_case__ ) lowercase__ = get_base_command(snake_case__ , snake_case__ ) # split each dimension into its --foo variations lowercase__ = [list(map(str.strip , re.split(R'\|' , snake_case__ ) ) ) for x in args.variations] # build a cartesian product of dimensions and convert those back into cmd-line arg strings, # while stripping white space for inputs that were empty lowercase__ = list(map(str.strip , map(' '.join , itertools.product(*snake_case__ ) ) ) ) lowercase__ = max(len(snake_case__ ) for x in variations ) # split wanted keys lowercase__ = args.report_metric_keys.split() # capture prints into a log file for convenience lowercase__ = F"""benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S" )}.txt""" print(F"""\nNote: each run's output is also logged under {output_dir}/log.*.std*.txt""" ) print(F"""and this script's output is also piped into {report_fn}""" ) lowercase__ = Tee(snake_case__ ) print(F"""\n*** Running {len(snake_case__ )} benchmarks:""" ) print(F"""Base command: {" ".join(snake_case__ )}""" ) lowercase__ = 'variation' lowercase__ = [] for id, variation in enumerate(tqdm(snake_case__ , desc='Total completion: ' , leave=snake_case__ ) ): lowercase__ = base_cmd + variation.split() results.append( process_run( id + 1 , snake_case__ , snake_case__ , snake_case__ , snake_case__ , args.target_metric_key , snake_case__ , args.repeat_times , snake_case__ , args.verbose , ) ) process_results(snake_case__ , args.target_metric_key , snake_case__ , args.base_variation , snake_case__ ) if __name__ == "__main__": main()
365
from typing import Callable, Optional from .. import Features from ..packaged_modules.generator.generator import Generator from .abc import AbstractDatasetInputStream class SCREAMING_SNAKE_CASE (UpperCAmelCase ): def __init__( self : List[str] , a : Callable , a : Optional[Features] = None , a : str = None , a : bool = False , a : bool = False , a : Optional[dict] = None , a : Optional[int] = None , **a : str , )-> Tuple: """simple docstring""" super().__init__( features=a , cache_dir=a , keep_in_memory=a , streaming=a , num_proc=a , **a , ) lowercase__ = Generator( cache_dir=a , features=a , generator=a , gen_kwargs=a , **a , ) def SCREAMING_SNAKE_CASE_ ( self : Any )-> Dict: """simple docstring""" if self.streaming: lowercase__ = self.builder.as_streaming_dataset(split='train' ) # Build regular (map-style) dataset else: lowercase__ = None lowercase__ = None lowercase__ = None lowercase__ = None self.builder.download_and_prepare( download_config=a , download_mode=a , verification_mode=a , base_path=a , num_proc=self.num_proc , ) lowercase__ = self.builder.as_dataset( split='train' , verification_mode=a , in_memory=self.keep_in_memory ) return dataset
269
0
"""simple docstring""" import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE = logging.get_logger(__name__) SCREAMING_SNAKE_CASE = { 'xlnet-base-cased': 'https://huggingface.co/xlnet-base-cased/resolve/main/config.json', 'xlnet-large-cased': 'https://huggingface.co/xlnet-large-cased/resolve/main/config.json', } class UpperCAmelCase_ ( A__ ): lowercase__ = '''xlnet''' lowercase__ = ['''mems'''] lowercase__ = { '''n_token''': '''vocab_size''', # Backward compatibility '''hidden_size''': '''d_model''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self : List[str] , snake_case_ : Union[str, Any]=32_000 , snake_case_ : Any=1_024 , snake_case_ : Dict=24 , snake_case_ : Optional[Any]=16 , snake_case_ : List[str]=4_096 , snake_case_ : int="gelu" , snake_case_ : Tuple=True , snake_case_ : Union[str, Any]="bi" , snake_case_ : Any=0.02 , snake_case_ : Optional[Any]=1e-12 , snake_case_ : Optional[Any]=0.1 , snake_case_ : Optional[int]=512 , snake_case_ : Tuple=None , snake_case_ : Optional[Any]=True , snake_case_ : Optional[int]=False , snake_case_ : List[Any]=False , snake_case_ : int=-1 , snake_case_ : int=False , snake_case_ : Union[str, Any]="last" , snake_case_ : Any=True , snake_case_ : List[str]="tanh" , snake_case_ : Optional[int]=0.1 , snake_case_ : Optional[int]=5 , snake_case_ : str=5 , snake_case_ : List[str]=5 , snake_case_ : Any=1 , snake_case_ : List[Any]=2 , **snake_case_ : Optional[Any] , ) -> List[Any]: '''simple docstring''' A__ = vocab_size A__ = d_model A__ = n_layer A__ = n_head if d_model % n_head != 0: raise ValueError(F"""'d_model % n_head' ({d_model % n_head}) should be equal to 0""" ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( F"""`d_head` ({kwargs["d_head"]}) should be equal to `d_model // n_head` ({d_model // n_head})""" ) A__ = d_model // n_head A__ = ff_activation A__ = d_inner A__ = untie_r A__ = attn_type A__ = initializer_range A__ = layer_norm_eps A__ = dropout A__ = mem_len A__ = reuse_len A__ = bi_data A__ = clamp_len A__ = same_length A__ = summary_type A__ = summary_use_proj A__ = summary_activation A__ = summary_last_dropout A__ = start_n_top A__ = end_n_top A__ = bos_token_id A__ = pad_token_id A__ = eos_token_id if "use_cache" in kwargs: warnings.warn( "The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`" " instead." , snake_case_ , ) A__ = kwargs["use_cache"] A__ = use_mems_eval A__ = use_mems_train super().__init__(pad_token_id=snake_case_ , bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ ) @property def __magic_name__ ( self : Optional[Any] ) -> Any: '''simple docstring''' logger.info(F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" ) return -1 @max_position_embeddings.setter def __magic_name__ ( self : Optional[int] , snake_case_ : Dict ) -> Optional[Any]: '''simple docstring''' raise NotImplementedError( F"""The model {self.model_type} is one of the few models that has no sequence length limit.""" )
247
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer A__ : List[Any] = logging.get_logger(__name__) A__ : str = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} A__ : int = { 'vocab_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt' ), 'distilbert-base-german-cased': 'https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt', 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'distilbert-base-uncased': 'https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json', 'distilbert-base-uncased-distilled-squad': ( 'https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-cased': 'https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json', 'distilbert-base-cased-distilled-squad': ( 'https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json' ), 'distilbert-base-german-cased': ( 'https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json' ), 'distilbert-base-multilingual-cased': ( 'https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json' ), }, } A__ : Optional[Any] = { 'distilbert-base-uncased': 5_12, 'distilbert-base-uncased-distilled-squad': 5_12, 'distilbert-base-cased': 5_12, 'distilbert-base-cased-distilled-squad': 5_12, 'distilbert-base-german-cased': 5_12, 'distilbert-base-multilingual-cased': 5_12, } A__ : List[str] = { 'distilbert-base-uncased': {'do_lower_case': True}, 'distilbert-base-uncased-distilled-squad': {'do_lower_case': True}, 'distilbert-base-cased': {'do_lower_case': False}, 'distilbert-base-cased-distilled-squad': {'do_lower_case': False}, 'distilbert-base-german-cased': {'do_lower_case': False}, 'distilbert-base-multilingual-cased': {'do_lower_case': False}, } class _UpperCAmelCase ( A__ ): """simple docstring""" lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = PRETRAINED_INIT_CONFIGURATION lowercase__ = ["""input_ids""", """attention_mask"""] lowercase__ = DistilBertTokenizer def __init__( self : List[Any], lowerCamelCase : List[Any]=None, lowerCamelCase : Dict=None, lowerCamelCase : str=True, lowerCamelCase : Optional[int]="[UNK]", lowerCamelCase : Optional[Any]="[SEP]", lowerCamelCase : List[Any]="[PAD]", lowerCamelCase : Any="[CLS]", lowerCamelCase : Union[str, Any]="[MASK]", lowerCamelCase : str=True, lowerCamelCase : int=None, **lowerCamelCase : Union[str, Any], ): '''simple docstring''' super().__init__( lowerCamelCase, tokenizer_file=lowerCamelCase, do_lower_case=lowerCamelCase, unk_token=lowerCamelCase, sep_token=lowerCamelCase, pad_token=lowerCamelCase, cls_token=lowerCamelCase, mask_token=lowerCamelCase, tokenize_chinese_chars=lowerCamelCase, strip_accents=lowerCamelCase, **lowerCamelCase, ) lowercase__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''', lowerCamelCase ) != do_lower_case or normalizer_state.get('''strip_accents''', lowerCamelCase ) != strip_accents or normalizer_state.get('''handle_chinese_chars''', lowerCamelCase ) != tokenize_chinese_chars ): lowercase__ = getattr(lowerCamelCase, normalizer_state.pop('''type''' ) ) lowercase__ = do_lower_case lowercase__ = strip_accents lowercase__ = tokenize_chinese_chars lowercase__ = normalizer_class(**lowerCamelCase ) lowercase__ = do_lower_case def lowercase__ ( self : str, lowerCamelCase : Optional[Any], lowerCamelCase : List[Any]=None ): '''simple docstring''' lowercase__ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowercase__ ( self : Union[str, Any], lowerCamelCase : List[int], lowerCamelCase : Optional[List[int]] = None ): '''simple docstring''' lowercase__ = [self.sep_token_id] lowercase__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowercase__ ( self : str, lowerCamelCase : str, lowerCamelCase : Optional[str] = None ): '''simple docstring''' lowercase__ = self._tokenizer.model.save(lowerCamelCase, name=lowerCamelCase ) return tuple(lowerCamelCase )
207
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCamelCase_ : str = {"""configuration_yolos""": ["""YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """YolosConfig""", """YolosOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Union[str, Any] = ["""YolosFeatureExtractor"""] lowerCamelCase_ : Dict = ["""YolosImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase_ : Dict = [ """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 lowerCamelCase_ : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
215
"""simple docstring""" import itertools import os import random import tempfile import unittest import numpy as np from datasets import load_dataset from transformers import is_speech_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import WhisperFeatureExtractor if is_torch_available(): import torch lowerCamelCase_ : Any = random.Random() def _A ( lowercase , lowercase=1.0 , lowercase=None , lowercase=None ): """simple docstring""" if rng is None: a =global_rng a =[] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __A ( unittest.TestCase ): """simple docstring""" def __init__( self , __A , __A=7 , __A=400 , __A=2000 , __A=10 , __A=160 , __A=8 , __A=0.0 , __A=4000 , __A=False , __A=True , ) -> Optional[Any]: a =parent a =batch_size a =min_seq_length a =max_seq_length a =(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) a =padding_value a =sampling_rate a =return_attention_mask a =do_normalize a =feature_size a =chunk_length a =hop_length def SCREAMING_SNAKE_CASE ( self ) -> str: return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def SCREAMING_SNAKE_CASE ( self , __A=False , __A=False ) -> str: def _flatten(__A ): return list(itertools.chain(*__A ) ) if equal_length: a =[floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size a =[ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: a =[np.asarray(__A ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = WhisperFeatureExtractor if is_speech_available() else None def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =WhisperFeatureExtractionTester(self ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: a =feat_extract_first.save_pretrained(__A )[0] check_json_file_has_correct_format(__A ) a =self.feature_extraction_class.from_pretrained(__A ) a =feat_extract_first.to_dict() a =feat_extract_second.to_dict() a =feat_extract_first.mel_filters a =feat_extract_second.mel_filters self.assertTrue(np.allclose(__A , __A ) ) self.assertEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> str: a =self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: a =os.path.join(__A , '''feat_extract.json''' ) feat_extract_first.to_json_file(__A ) a =self.feature_extraction_class.from_json_file(__A ) a =feat_extract_first.to_dict() a =feat_extract_second.to_dict() a =feat_extract_first.mel_filters a =feat_extract_second.mel_filters self.assertTrue(np.allclose(__A , __A ) ) self.assertEqual(__A , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: # Tests that all call wrap to encode_plus and batch_encode_plus a =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 a =[floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] a =[np.asarray(__A ) for speech_input in speech_inputs] # Test feature size a =feature_extractor(__A , padding='''max_length''' , return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames ) self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size ) # Test not batched input a =feature_extractor(speech_inputs[0] , return_tensors='''np''' ).input_features a =feature_extractor(np_speech_inputs[0] , return_tensors='''np''' ).input_features self.assertTrue(np.allclose(__A , __A , atol=1E-3 ) ) # Test batched a =feature_extractor(__A , return_tensors='''np''' ).input_features a =feature_extractor(__A , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__A , __A ): self.assertTrue(np.allclose(__A , __A , atol=1E-3 ) ) # Test 2-D numpy arrays are batched. a =[floats_list((1, x) )[0] for x in (800, 800, 800)] a =np.asarray(__A ) a =feature_extractor(__A , return_tensors='''np''' ).input_features a =feature_extractor(__A , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__A , __A ): self.assertTrue(np.allclose(__A , __A , atol=1E-3 ) ) # Test truncation required a =[floats_list((1, x) )[0] for x in range(200 , (feature_extractor.n_samples + 500) , 200 )] a =[np.asarray(__A ) for speech_input in speech_inputs] a =[x[: feature_extractor.n_samples] for x in speech_inputs] a =[np.asarray(__A ) for speech_input in speech_inputs_truncated] a =feature_extractor(__A , return_tensors='''np''' ).input_features a =feature_extractor(__A , return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(__A , __A ): self.assertTrue(np.allclose(__A , __A , atol=1E-3 ) ) def SCREAMING_SNAKE_CASE ( self ) -> Tuple: import torch a =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) a =np.random.rand(100 , 32 ).astype(np.floataa ) a =np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: a =feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) a =feature_extractor.pad([{'''input_features''': inputs}] , return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Dict: a =load_dataset('''hf-internal-testing/librispeech_asr_dummy''' , '''clean''' , split='''validation''' ) # automatic decoding with librispeech a =ds.sort('''id''' ).select(range(__A ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def SCREAMING_SNAKE_CASE ( self ) -> Any: # fmt: off a =torch.tensor( [ 0.1_193, -0.0_946, -0.1_098, -0.0_196, 0.0_225, -0.0_690, -0.1_736, 0.0_951, 0.0_971, -0.0_817, -0.0_702, 0.0_162, 0.0_260, 0.0_017, -0.0_192, -0.1_678, 0.0_709, -0.1_867, -0.0_655, -0.0_274, -0.0_234, -0.1_884, -0.0_516, -0.0_554, -0.0_274, -0.1_425, -0.1_423, 0.0_837, 0.0_377, -0.0_854 ] ) # fmt: on a =self._load_datasamples(1 ) a =WhisperFeatureExtractor() a =feature_extractor(__A , return_tensors='''pt''' ).input_features self.assertEqual(input_features.shape , (1, 80, 3000) ) self.assertTrue(torch.allclose(input_features[0, 0, :30] , __A , atol=1E-4 ) ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) a =self._load_datasamples(1 )[0] a =((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535 # Rescale to [0, 65535] to show issue a =feat_extract.zero_mean_unit_var_norm([audio] , attention_mask=__A )[0] self.assertTrue(np.all(np.mean(__A ) < 1E-3 ) ) self.assertTrue(np.all(np.abs(np.var(__A ) - 1 ) < 1E-3 ) )
215
1
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.testing_utils import require_tensorflow_text, require_tf, slow if is_tf_available(): import tensorflow as tf if is_tensorflow_text_available(): from transformers.models.bert import TFBertTokenizer a = ['bert-base-uncased', 'bert-base-cased'] a = 'hf-internal-testing/tiny-bert-tf-only' if is_tf_available(): class SCREAMING_SNAKE_CASE__ ( tf.keras.Model ): def __init__( self : Optional[Any] , lowerCAmelCase : Union[str, Any] ): super().__init__() lowerCAmelCase = tokenizer lowerCAmelCase = AutoConfig.from_pretrained(lowerCAmelCase ) lowerCAmelCase = TFAutoModel.from_config(lowerCAmelCase ) def __lowercase ( self : List[str] , lowerCAmelCase : Optional[int] ): lowerCAmelCase = self.tokenizer(lowerCAmelCase ) lowerCAmelCase = self.bert(**lowerCAmelCase ) return out["pooler_output"] @require_tf @require_tensorflow_text class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def __lowercase ( self : Optional[Any] ): super().setUp() lowerCAmelCase = [ BertTokenizer.from_pretrained(lowerCAmelCase ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2) ] # repeat for when fast_bert_tokenizer=false lowerCAmelCase = [TFBertTokenizer.from_pretrained(lowerCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS] + [ TFBertTokenizer.from_pretrained(lowerCAmelCase , use_fast_bert_tokenizer=lowerCAmelCase ) for checkpoint in TOKENIZER_CHECKPOINTS ] assert len(self.tokenizers ) == len(self.tf_tokenizers ) lowerCAmelCase = [ """This is a straightforward English test sentence.""", """This one has some weird characters\rto\nsee\r\nif those\u00E9break things.""", """Now we're going to add some Chinese: 一 二 三 一二三""", """And some much more rare Chinese: 齉 堃 齉堃""", """Je vais aussi écrire en français pour tester les accents""", """Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ""", ] lowerCAmelCase = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def __lowercase ( self : Optional[int] ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in (self.test_sentences, self.paired_sentences): lowerCAmelCase = tokenizer(lowerCAmelCase , return_tensors="""tf""" , padding="""longest""" ) lowerCAmelCase = tf_tokenizer(lowerCAmelCase ) for key in python_outputs.keys(): self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape ) ) self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa ) == tf_outputs[key] ) ) @slow def __lowercase ( self : List[str] ): for tf_tokenizer in self.tf_tokenizers: lowerCAmelCase = tf_tokenizer(self.paired_sentences ) lowerCAmelCase = tf_tokenizer( text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , ) for key in merged_outputs.keys(): self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa ) == separated_outputs[key] ) ) @slow def __lowercase ( self : str ): for tf_tokenizer in self.tf_tokenizers: lowerCAmelCase = tf.function(lowerCAmelCase ) for test_inputs in (self.test_sentences, self.paired_sentences): lowerCAmelCase = tf.constant(lowerCAmelCase ) lowerCAmelCase = compiled_tokenizer(lowerCAmelCase ) lowerCAmelCase = tf_tokenizer(lowerCAmelCase ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def __lowercase ( self : List[str] ): for tf_tokenizer in self.tf_tokenizers: lowerCAmelCase = ModelToSave(tokenizer=lowerCAmelCase ) lowerCAmelCase = tf.convert_to_tensor(self.test_sentences ) lowerCAmelCase = model(lowerCAmelCase ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: lowerCAmelCase = Path(lowerCAmelCase ) / """saved.model""" model.save(lowerCAmelCase ) lowerCAmelCase = tf.keras.models.load_model(lowerCAmelCase ) lowerCAmelCase = loaded_model(lowerCAmelCase ) # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output ) ) , 1e-5 )
155
"""simple docstring""" from typing import List, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging a = logging.get_logger(__name__) a = { 'huggingface/time-series-transformer-tourism-monthly': ( 'https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json' ), # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer } class SCREAMING_SNAKE_CASE__ ( _a ): _a = 'time_series_transformer' _a = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', 'num_hidden_layers': 'encoder_layers', } def __init__( self : Optional[Any] , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : Optional[int] = None , lowerCAmelCase : str = "student_t" , lowerCAmelCase : str = "nll" , lowerCAmelCase : int = 1 , lowerCAmelCase : List[int] = [1, 2, 3, 4, 5, 6, 7] , lowerCAmelCase : Optional[Union[str, bool]] = "mean" , lowerCAmelCase : int = 0 , lowerCAmelCase : int = 0 , lowerCAmelCase : int = 0 , lowerCAmelCase : int = 0 , lowerCAmelCase : Optional[List[int]] = None , lowerCAmelCase : Optional[List[int]] = None , lowerCAmelCase : int = 32 , lowerCAmelCase : int = 32 , lowerCAmelCase : int = 2 , lowerCAmelCase : int = 2 , lowerCAmelCase : int = 2 , lowerCAmelCase : int = 2 , lowerCAmelCase : bool = True , lowerCAmelCase : str = "gelu" , lowerCAmelCase : int = 64 , lowerCAmelCase : float = 0.1 , lowerCAmelCase : float = 0.1 , lowerCAmelCase : float = 0.1 , lowerCAmelCase : float = 0.1 , lowerCAmelCase : float = 0.1 , lowerCAmelCase : int = 100 , lowerCAmelCase : float = 0.02 , lowerCAmelCase : List[Any]=True , **lowerCAmelCase : List[str] , ): # time series specific configuration lowerCAmelCase = prediction_length lowerCAmelCase = context_length or prediction_length lowerCAmelCase = distribution_output lowerCAmelCase = loss lowerCAmelCase = input_size lowerCAmelCase = num_time_features lowerCAmelCase = lags_sequence lowerCAmelCase = scaling lowerCAmelCase = num_dynamic_real_features lowerCAmelCase = num_static_real_features lowerCAmelCase = num_static_categorical_features if cardinality and num_static_categorical_features > 0: if len(lowerCAmelCase ) != num_static_categorical_features: raise ValueError( """The cardinality should be a list of the same length as `num_static_categorical_features`""" ) lowerCAmelCase = cardinality else: lowerCAmelCase = [0] if embedding_dimension and num_static_categorical_features > 0: if len(lowerCAmelCase ) != num_static_categorical_features: raise ValueError( """The embedding dimension should be a list of the same length as `num_static_categorical_features`""" ) lowerCAmelCase = embedding_dimension else: lowerCAmelCase = [min(50 , (cat + 1) // 2 ) for cat in self.cardinality] lowerCAmelCase = num_parallel_samples # Transformer architecture configuration lowerCAmelCase = input_size * len(lowerCAmelCase ) + self._number_of_features lowerCAmelCase = d_model lowerCAmelCase = encoder_attention_heads lowerCAmelCase = decoder_attention_heads lowerCAmelCase = encoder_ffn_dim lowerCAmelCase = decoder_ffn_dim lowerCAmelCase = encoder_layers lowerCAmelCase = decoder_layers lowerCAmelCase = dropout lowerCAmelCase = attention_dropout lowerCAmelCase = activation_dropout lowerCAmelCase = encoder_layerdrop lowerCAmelCase = decoder_layerdrop lowerCAmelCase = activation_function lowerCAmelCase = init_std lowerCAmelCase = use_cache super().__init__(is_encoder_decoder=lowerCAmelCase , **lowerCAmelCase ) @property def __lowercase ( self : List[Any] ): return ( sum(self.embedding_dimension ) + self.num_dynamic_real_features + self.num_time_features + self.num_static_real_features + self.input_size * 2 # the log1p(abs(loc)) and log(scale) features )
155
1
import unittest from transformers import BertGenerationConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import BertGenerationDecoder, BertGenerationEncoder class UpperCamelCase__ : '''simple docstring''' def __init__( self : List[str] ,lowerCamelCase__ : Any ,lowerCamelCase__ : Union[str, Any]=13 ,lowerCamelCase__ : Tuple=7 ,lowerCamelCase__ : List[str]=True ,lowerCamelCase__ : Dict=True ,lowerCamelCase__ : Dict=99 ,lowerCamelCase__ : List[Any]=32 ,lowerCamelCase__ : Union[str, Any]=5 ,lowerCamelCase__ : Tuple=4 ,lowerCamelCase__ : Optional[Any]=37 ,lowerCamelCase__ : int="gelu" ,lowerCamelCase__ : int=0.1 ,lowerCamelCase__ : Optional[Any]=0.1 ,lowerCamelCase__ : Any=50 ,lowerCamelCase__ : int=0.02 ,lowerCamelCase__ : Any=True ,lowerCamelCase__ : Optional[int]=None ,) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = seq_length SCREAMING_SNAKE_CASE = is_training SCREAMING_SNAKE_CASE = use_input_mask SCREAMING_SNAKE_CASE = vocab_size SCREAMING_SNAKE_CASE = hidden_size SCREAMING_SNAKE_CASE = num_hidden_layers SCREAMING_SNAKE_CASE = num_attention_heads SCREAMING_SNAKE_CASE = intermediate_size SCREAMING_SNAKE_CASE = hidden_act SCREAMING_SNAKE_CASE = hidden_dropout_prob SCREAMING_SNAKE_CASE = attention_probs_dropout_prob SCREAMING_SNAKE_CASE = max_position_embeddings SCREAMING_SNAKE_CASE = initializer_range SCREAMING_SNAKE_CASE = use_labels SCREAMING_SNAKE_CASE = scope def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) SCREAMING_SNAKE_CASE = None if self.use_input_mask: SCREAMING_SNAKE_CASE = random_attention_mask([self.batch_size, self.seq_length] ) if self.use_labels: SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) SCREAMING_SNAKE_CASE = self.get_config() return config, input_ids, input_mask, token_labels def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Dict: '''simple docstring''' return BertGenerationConfig( 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 ,is_decoder=lowerCamelCase__ ,initializer_range=self.initializer_range ,) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ) -> Tuple: '''simple docstring''' ( SCREAMING_SNAKE_CASE ) = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) SCREAMING_SNAKE_CASE = ids_tensor([self.batch_size, self.seq_length] ,vocab_size=2 ) return ( config, input_ids, input_mask, token_labels, encoder_hidden_states, encoder_attention_mask, ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Dict ,**lowerCamelCase__ : Optional[Any] ,) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = BertGenerationEncoder(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ) SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : int ,lowerCamelCase__ : str ,lowerCamelCase__ : Union[str, Any] ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : List[Any] ,**lowerCamelCase__ : Optional[int] ,) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = BertGenerationEncoder(config=lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,encoder_hidden_states=lowerCamelCase__ ,encoder_attention_mask=lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = model( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,encoder_hidden_states=lowerCamelCase__ ,) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : Tuple ,lowerCamelCase__ : Optional[Any] ,lowerCamelCase__ : Dict ,lowerCamelCase__ : List[Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : Optional[Any] ,**lowerCamelCase__ : Dict ,) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = BertGenerationDecoder(config=lowerCamelCase__ ).to(lowerCamelCase__ ).eval() # first forward pass SCREAMING_SNAKE_CASE = model( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,encoder_hidden_states=lowerCamelCase__ ,encoder_attention_mask=lowerCamelCase__ ,use_cache=lowerCamelCase__ ,) SCREAMING_SNAKE_CASE = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) ,config.vocab_size ) SCREAMING_SNAKE_CASE = ids_tensor((self.batch_size, 3) ,vocab_size=2 ) # append to next input_ids and SCREAMING_SNAKE_CASE = torch.cat([input_ids, next_tokens] ,dim=-1 ) SCREAMING_SNAKE_CASE = torch.cat([input_mask, next_mask] ,dim=-1 ) SCREAMING_SNAKE_CASE = model( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,encoder_hidden_states=lowerCamelCase__ ,encoder_attention_mask=lowerCamelCase__ ,output_hidden_states=lowerCamelCase__ ,)['''hidden_states'''][0] SCREAMING_SNAKE_CASE = model( lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,encoder_hidden_states=lowerCamelCase__ ,encoder_attention_mask=lowerCamelCase__ ,past_key_values=lowerCamelCase__ ,output_hidden_states=lowerCamelCase__ ,)['''hidden_states'''][0] # select random slice SCREAMING_SNAKE_CASE = ids_tensor((1,) ,output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase__ ,lowerCamelCase__ ,atol=1e-3 ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ,lowerCamelCase__ : Any ,lowerCamelCase__ : Optional[int] ,lowerCamelCase__ : List[str] ,lowerCamelCase__ : List[str] ,*lowerCamelCase__ : Union[str, Any] ,) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = BertGenerationDecoder(lowerCamelCase__ ) model.to(lowerCamelCase__ ) model.eval() SCREAMING_SNAKE_CASE = model(lowerCamelCase__ ,attention_mask=lowerCamelCase__ ,labels=lowerCamelCase__ ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class UpperCamelCase__ ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , unittest.TestCase ): '''simple docstring''' __snake_case : Dict = (BertGenerationEncoder, BertGenerationDecoder) if is_torch_available() else () __snake_case : Optional[Any] = (BertGenerationDecoder,) if is_torch_available() else () __snake_case : Any = ( {"feature-extraction": BertGenerationEncoder, "text-generation": BertGenerationDecoder} if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = BertGenerationEncoderTester(self ) SCREAMING_SNAKE_CASE = ConfigTester(self ,config_class=lowerCamelCase__ ,hidden_size=37 ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__ ( self : str ) -> List[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE = '''bert''' self.model_tester.create_and_check_model(lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : int ) -> Dict: '''simple docstring''' ( SCREAMING_SNAKE_CASE ) = self.model_tester.prepare_config_and_inputs_for_decoder() SCREAMING_SNAKE_CASE = None self.model_tester.create_and_check_model_as_decoder( lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,lowerCamelCase__ ,) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*lowerCamelCase__ ) @slow def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" ) self.assertIsNotNone(lowerCamelCase__ ) @require_torch class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = BertGenerationEncoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" ) SCREAMING_SNAKE_CASE = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = torch.Size([1, 8, 1024] ) self.assertEqual(output.shape ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.tensor( [[[0.1775, 0.0083, -0.0321], [1.6002, 0.1287, 0.3912], [2.1473, 0.5791, 0.6066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,lowerCamelCase__ ,atol=1e-4 ) ) @require_torch class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' @slow def SCREAMING_SNAKE_CASE__ ( self : Dict ) -> int: '''simple docstring''' SCREAMING_SNAKE_CASE = BertGenerationDecoder.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" ) SCREAMING_SNAKE_CASE = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE = model(lowerCamelCase__ )[0] SCREAMING_SNAKE_CASE = torch.Size([1, 8, 50358] ) self.assertEqual(output.shape ,lowerCamelCase__ ) SCREAMING_SNAKE_CASE = torch.tensor( [[[-0.5788, -2.5994, -3.7054], [0.0438, 4.7997, 1.8795], [1.5862, 6.6409, 4.4638]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] ,lowerCamelCase__ ,atol=1e-4 ) )
357
class UpperCamelCase__ : '''simple docstring''' def __init__( self : int ) -> str: '''simple docstring''' SCREAMING_SNAKE_CASE = {} def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> None: '''simple docstring''' print(self.vertex ) for i in self.vertex: print(lowerCamelCase__ ,""" -> """ ,""" -> """.join([str(lowerCamelCase__ ) for j in self.vertex[i]] ) ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ,lowerCamelCase__ : int ,lowerCamelCase__ : int ) -> None: '''simple docstring''' if from_vertex in self.vertex: self.vertex[from_vertex].append(lowerCamelCase__ ) else: # else make a new vertex SCREAMING_SNAKE_CASE = [to_vertex] def SCREAMING_SNAKE_CASE__ ( self : str ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE = [False] * len(self.vertex ) # call the recursive helper function for i in range(len(self.vertex ) ): if not visited[i]: self.dfs_recursive(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : int ,lowerCamelCase__ : list ) -> None: '''simple docstring''' SCREAMING_SNAKE_CASE = True print(lowerCamelCase__ ,end=""" """ ) # Recur for all the vertices that are adjacent to this node for i in self.vertex: if not visited[i]: self.dfs_recursive(lowerCamelCase__ ,lowerCamelCase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_ = Graph() g.add_edge(0, 1) g.add_edge(0, 2) g.add_edge(1, 2) g.add_edge(2, 0) g.add_edge(2, 3) g.add_edge(3, 3) g.print_graph() print("""DFS:""") g.dfs() # OUTPUT: # 0 -> 1 -> 2 # 1 -> 2 # 2 -> 0 -> 3 # 3 -> 3 # DFS: # 0 1 2 3
193
0
"""simple docstring""" import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a :List[str] = logging.get_logger(__name__) a :str = "▁" a :List[str] = {"vocab_file": "sentencepiece.bpe.model", "monolingual_vocab_file": "dict.txt"} a :str = { "vocab_file": { "vinai/bartpho-syllable": "https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model", }, "monolingual_vocab_file": { "vinai/bartpho-syllable": "https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt", }, } a :Optional[int] = {"vinai/bartpho-syllable": 1_024} class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :Union[str, Any] = VOCAB_FILES_NAMES _SCREAMING_SNAKE_CASE :Optional[Any] = PRETRAINED_VOCAB_FILES_MAP _SCREAMING_SNAKE_CASE :Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _SCREAMING_SNAKE_CASE :Optional[int] = ["""input_ids""", """attention_mask"""] def __init__( self , _a , _a , _a="<s>" , _a="</s>" , _a="</s>" , _a="<s>" , _a="<unk>" , _a="<pad>" , _a="<mask>" , _a = None , **_a , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = AddedToken(_a , lstrip=_a , rstrip=_a ) if isinstance(_a , _a ) else mask_token SCREAMING_SNAKE_CASE__ : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=_a , eos_token=_a , unk_token=_a , sep_token=_a , cls_token=_a , pad_token=_a , mask_token=_a , sp_model_kwargs=self.sp_model_kwargs , **_a , ) SCREAMING_SNAKE_CASE__ : int = vocab_file SCREAMING_SNAKE_CASE__ : Optional[Any] = monolingual_vocab_file SCREAMING_SNAKE_CASE__ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(_a ) ) # Load the reduced vocab # Keep order of special tokens for backward compatibility SCREAMING_SNAKE_CASE__ : Any = {} SCREAMING_SNAKE_CASE__ : str = 0 for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]: if str(_a ) not in self.fairseq_tokens_to_ids: SCREAMING_SNAKE_CASE__ : Optional[int] = cnt cnt += 1 with open(_a , """r""" , encoding="""utf-8""" ) as f: for line in f.readlines(): SCREAMING_SNAKE_CASE__ : Any = line.strip().split()[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(self.fairseq_tokens_to_ids ) if str(_a ) not in self.fairseq_tokens_to_ids: SCREAMING_SNAKE_CASE__ : str = len(self.fairseq_tokens_to_ids ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def __getstate__( self ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.__dict__.copy() SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = self.sp_model.serialized_model_proto() return state def __setstate__( self , _a ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): SCREAMING_SNAKE_CASE__ : List[str] = {} SCREAMING_SNAKE_CASE__ : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Tuple = [self.cls_token_id] SCREAMING_SNAKE_CASE__ : List[Any] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def _a ( self , _a , _a = None , _a = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_a , token_ids_a=_a , already_has_special_tokens=_a ) if token_ids_a is None: return [1] + ([0] * len(_a )) + [1] return [1] + ([0] * len(_a )) + [1, 1] + ([0] * len(_a )) + [1] def _a ( self , _a , _a = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : List[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def _a ( self ) -> Any: """simple docstring""" return len(self.fairseq_ids_to_tokens ) def _a ( self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = {self.convert_ids_to_tokens(_a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _a ( self , _a ) -> List[str]: """simple docstring""" return self.sp_model.encode(_a , out_type=_a ) def _a ( self , _a ) -> Optional[Any]: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] else: return self.unk_token_id def _a ( self , _a ) -> Optional[int]: """simple docstring""" return self.fairseq_ids_to_tokens[index] def _a ( self , _a ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = """""".join(_a ).replace(_a , """ """ ).strip() return out_string def _a ( self , _a , _a = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(_a ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : int = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join( _a , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""monolingual_vocab_file"""] , ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _a ) elif not os.path.isfile(self.vocab_file ): with open(_a , """wb""" ) as fi: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(_a ) if os.path.abspath(self.monolingual_vocab_file ) != os.path.abspath( _a ) and os.path.isfile(self.monolingual_vocab_file ): copyfile(self.monolingual_vocab_file , _a ) elif not os.path.isfile(self.monolingual_vocab_file ): with open(_a , """w""" , encoding="""utf-8""" ) as fp: for token in self.fairseq_tokens_to_ids: if token not in self.all_special_tokens: fp.write(f'''{str(_a )} \n''' ) return out_vocab_file, out_monolingual_vocab_file
132
"""simple docstring""" import os import sys a :Union[str, Any] = os.path.join(os.path.dirname(__file__), "src") sys.path.append(SRC_DIR) from transformers import ( AutoConfig, AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForQuestionAnswering, AutoModelForSequenceClassification, AutoTokenizer, add_start_docstrings, ) a :int = [ "torch", "numpy", "tokenizers", "filelock", "requests", "tqdm", "regex", "sentencepiece", "sacremoses", "importlib_metadata", "huggingface_hub", ] @add_start_docstrings(AutoConfig.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> Optional[Any]: return AutoConfig.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoTokenizer.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> Union[str, Any]: return AutoTokenizer.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoModel.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> Dict: return AutoModel.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoModelForCausalLM.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> Optional[int]: return AutoModelForCausalLM.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoModelForMaskedLM.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> List[str]: return AutoModelForMaskedLM.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoModelForSequenceClassification.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> str: return AutoModelForSequenceClassification.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase ) @add_start_docstrings(AutoModelForQuestionAnswering.__doc__ ) def _lowercase ( *__lowerCAmelCase , **__lowerCAmelCase ) -> int: return AutoModelForQuestionAnswering.from_pretrained(*__lowerCAmelCase , **__lowerCAmelCase )
132
1
"""simple docstring""" from typing import TYPE_CHECKING from ..utils import _LazyModule A__ : List[str] = { 'config': [ 'EXTERNAL_DATA_FORMAT_SIZE_LIMIT', 'OnnxConfig', 'OnnxConfigWithPast', 'OnnxSeq2SeqConfigWithPast', 'PatchingSpec', ], 'convert': ['export', 'validate_model_outputs'], 'features': ['FeaturesManager'], 'utils': ['ParameterFormat', 'compute_serialized_parameters_size'], } if TYPE_CHECKING: from .config import ( EXTERNAL_DATA_FORMAT_SIZE_LIMIT, OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast, PatchingSpec, ) from .convert import export, validate_model_outputs from .features import FeaturesManager from .utils import ParameterFormat, compute_serialized_parameters_size else: import sys A__ : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
209
"""simple docstring""" import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def _snake_case ( lowerCamelCase__ : Any ) -> Union[str, Any]: # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def _snake_case ( ) -> List[Any]: with parallel_backend("spark" ): assert ParallelBackendConfig.backend_name == "spark" lowerCamelCase_ : Optional[Any] =[1, 2, 3] with pytest.raises(lowerCamelCase__ ): with parallel_backend("unsupported backend" ): map_nested(lowerCamelCase__ , lowerCamelCase__ , num_proc=2 ) with pytest.raises(lowerCamelCase__ ): with parallel_backend("unsupported backend" ): map_nested(lowerCamelCase__ , lowerCamelCase__ , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize("num_proc" , [2, -1] ) def _snake_case ( lowerCamelCase__ : Tuple ) -> Optional[Any]: lowerCamelCase_ : str =[1, 2] lowerCamelCase_ : List[str] ={"a": 1, "b": 2} lowerCamelCase_ : List[str] ={"a": [1, 2], "b": [3, 4]} lowerCamelCase_ : Optional[int] ={"a": {"1": 1}, "b": 2} lowerCamelCase_ : int ={"a": 1, "b": 2, "c": 3, "d": 4} lowerCamelCase_ : Optional[int] =[2, 3] lowerCamelCase_ : List[Any] ={"a": 2, "b": 3} lowerCamelCase_ : int ={"a": [2, 3], "b": [4, 5]} lowerCamelCase_ : str ={"a": {"1": 2}, "b": 3} lowerCamelCase_ : Dict ={"a": 2, "b": 3, "c": 4, "d": 5} with parallel_backend("spark" ): assert map_nested(lowerCamelCase__ , lowerCamelCase__ , num_proc=lowerCamelCase__ ) == expected_map_nested_sa assert map_nested(lowerCamelCase__ , lowerCamelCase__ , num_proc=lowerCamelCase__ ) == expected_map_nested_sa assert map_nested(lowerCamelCase__ , lowerCamelCase__ , num_proc=lowerCamelCase__ ) == expected_map_nested_sa assert map_nested(lowerCamelCase__ , lowerCamelCase__ , num_proc=lowerCamelCase__ ) == expected_map_nested_sa assert map_nested(lowerCamelCase__ , lowerCamelCase__ , num_proc=lowerCamelCase__ ) == expected_map_nested_sa
209
1
'''simple docstring''' from queue import PriorityQueue from typing import Any import numpy as np def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ) -> float | int: """simple docstring""" for nxt, d in graph[v]: if nxt in visited_forward: continue A_ : Optional[int] = cst_fwd.get(a_ , np.inf ) A_ : Dict = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) A_ : str = new_cost_f A_ : List[Any] = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: A_ : List[str] = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> int: """simple docstring""" A_ : Tuple = -1 A_ : Union[str, Any] = set() A_ : Tuple = set() A_ : List[str] = {source: 0} A_ : Union[str, Any] = {destination: 0} A_ : Optional[Any] = {source: None} A_ : Any = {destination: None} A_ : PriorityQueue[Any] = PriorityQueue() A_ : PriorityQueue[Any] = PriorityQueue() A_ : 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(): A_ , A_ : Dict = queue_forward.get() visited_forward.add(a_ ) A_ , A_ : Optional[Any] = queue_backward.get() visited_backward.add(a_ ) A_ : int = pass_and_relaxation( a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ) A_ : Any = pass_and_relaxation( a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: A_ : Optional[int] = shortest_distance return shortest_path_distance UpperCamelCase__ : int = { 'B': [['C', 1]], 'C': [['D', 1]], 'D': [['F', 1]], 'E': [['B', 1], ['G', 2]], 'F': [], 'G': [['F', 1]], } UpperCamelCase__ : Optional[int] = { '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()
344
'''simple docstring''' import datasets from .evaluate import evaluate UpperCamelCase__ : int = '\\n@inproceedings{Rajpurkar2016SQuAD10,\n title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n booktitle={EMNLP},\n year={2016}\n}\n' UpperCamelCase__ : Any = '\nThis metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n' UpperCamelCase__ : Optional[Any] = '\nComputes SQuAD scores (F1 and EM).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair as given in the references (see below)\n - \'prediction_text\': the text of the answer\n references: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair (see above),\n - \'answers\': a Dict in the SQuAD dataset format\n {\n \'text\': list of possible texts for the answer, as a list of strings\n \'answer_start\': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n \'f1\': The F-score of predicted tokens versus the gold answer\nExamples:\n\n >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\'}]\n >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]\n >>> squad_metric = datasets.load_metric("squad")\n >>> results = squad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 100.0, \'f1\': 100.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class _lowerCAmelCase ( datasets.Metric ): """simple docstring""" def UpperCAmelCase_ ( self ) -> str: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": {"""id""": datasets.Value("""string""" ), """prediction_text""": datasets.Value("""string""" )}, """references""": { """id""": datasets.Value("""string""" ), """answers""": datasets.features.Sequence( { """text""": datasets.Value("""string""" ), """answer_start""": datasets.Value("""int32""" ), } ), }, } ) , codebase_urls=["""https://rajpurkar.github.io/SQuAD-explorer/"""] , reference_urls=["""https://rajpurkar.github.io/SQuAD-explorer/"""] , ) def UpperCAmelCase_ ( self , _lowerCamelCase , _lowerCamelCase ) -> List[Any]: A_ : Optional[Any] = {prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions} A_ : List[Any] = [ { """paragraphs""": [ { """qas""": [ { """answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]], """id""": ref["""id"""], } for ref in references ] } ] } ] A_ : int = evaluate(dataset=_lowerCamelCase , predictions=_lowerCamelCase ) return score
344
1
"""simple docstring""" import logging import os import threading import time try: import warnings except ImportError: snake_case_ = None try: import msvcrt except ImportError: snake_case_ = None try: import fcntl except ImportError: snake_case_ = None # Backward compatibility # ------------------------------------------------ try: TimeoutError except NameError: snake_case_ = OSError # Data # ------------------------------------------------ snake_case_ = [ """Timeout""", """BaseFileLock""", """WindowsFileLock""", """UnixFileLock""", """SoftFileLock""", """FileLock""", ] snake_case_ = """3.0.12""" snake_case_ = None def _lowerCAmelCase ( ): global _logger UpperCAmelCase = _logger or logging.getLogger(__name__ ) return _logger class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self :int , lowercase_ :List[Any] ) -> Optional[int]: UpperCAmelCase = lock_file return None def __str__( self :Dict ) -> Optional[int]: UpperCAmelCase = f"""The file lock '{self.lock_file}' could not be acquired.""" return temp class A_ : """simple docstring""" def __init__( self :List[Any] , lowercase_ :Dict ) -> Dict: UpperCAmelCase = lock return None def __enter__( self :Optional[int] ) -> Optional[int]: return self.lock def __exit__( self :Optional[int] , lowercase_ :Tuple , lowercase_ :Any , lowercase_ :Union[str, Any] ) -> List[Any]: self.lock.release() return None class A_ : """simple docstring""" def __init__( self :List[str] , lowercase_ :str , lowercase_ :str=-1 , lowercase_ :List[Any]=None ) -> Dict: UpperCAmelCase = max_filename_length if max_filename_length is not None else 2_55 # Hash the filename if it's too long UpperCAmelCase = self.hash_filename_if_too_long(lowercase_ , lowercase_ ) # The path to the lock file. UpperCAmelCase = lock_file # The file descriptor for the *_lock_file* as it is returned by the # os.open() function. # This file lock is only NOT None, if the object currently holds the # lock. UpperCAmelCase = None # The default timeout value. UpperCAmelCase = timeout # We use this lock primarily for the lock counter. UpperCAmelCase = threading.Lock() # The lock counter is used for implementing the nested locking # mechanism. Whenever the lock is acquired, the counter is increased and # the lock is only released, when this value is 0 again. UpperCAmelCase = 0 return None @property def UpperCAmelCase__ ( self :Optional[Any] ) -> int: return self._lock_file @property def UpperCAmelCase__ ( self :Union[str, Any] ) -> Any: return self._timeout @timeout.setter def UpperCAmelCase__ ( self :Union[str, Any] , lowercase_ :Any ) -> Tuple: UpperCAmelCase = float(lowercase_ ) return None def UpperCAmelCase__ ( self :Any ) -> List[str]: raise NotImplementedError() def UpperCAmelCase__ ( self :Union[str, Any] ) -> List[str]: raise NotImplementedError() @property def UpperCAmelCase__ ( self :Optional[Any] ) -> Union[str, Any]: return self._lock_file_fd is not None def UpperCAmelCase__ ( self :Union[str, Any] , lowercase_ :Dict=None , lowercase_ :int=0.05 ) -> Union[str, Any]: # Use the default timeout, if no timeout is provided. if timeout is None: UpperCAmelCase = self.timeout # Increment the number right at the beginning. # We can still undo it, if something fails. with self._thread_lock: self._lock_counter += 1 UpperCAmelCase = id(self ) UpperCAmelCase = self._lock_file UpperCAmelCase = time.time() try: while True: with self._thread_lock: if not self.is_locked: logger().debug(f"""Attempting to acquire lock {lock_id} on {lock_filename}""" ) self._acquire() if self.is_locked: logger().debug(f"""Lock {lock_id} acquired on {lock_filename}""" ) break elif timeout >= 0 and time.time() - start_time > timeout: logger().debug(f"""Timeout on acquiring lock {lock_id} on {lock_filename}""" ) raise Timeout(self._lock_file ) else: logger().debug( f"""Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...""" ) time.sleep(lowercase_ ) except: # noqa # Something did go wrong, so decrement the counter. with self._thread_lock: UpperCAmelCase = max(0 , self._lock_counter - 1 ) raise return _Acquire_ReturnProxy(lock=self ) def UpperCAmelCase__ ( self :Optional[int] , lowercase_ :List[str]=False ) -> int: with self._thread_lock: if self.is_locked: self._lock_counter -= 1 if self._lock_counter == 0 or force: UpperCAmelCase = id(self ) UpperCAmelCase = self._lock_file logger().debug(f"""Attempting to release lock {lock_id} on {lock_filename}""" ) self._release() UpperCAmelCase = 0 logger().debug(f"""Lock {lock_id} released on {lock_filename}""" ) return None def __enter__( self :Any ) -> Tuple: self.acquire() return self def __exit__( self :Dict , lowercase_ :Optional[int] , lowercase_ :Union[str, Any] , lowercase_ :Union[str, Any] ) -> Any: self.release() return None def __del__( self :Any ) -> int: self.release(force=lowercase_ ) return None def UpperCAmelCase__ ( self :List[str] , lowercase_ :str , lowercase_ :int ) -> str: UpperCAmelCase = os.path.basename(lowercase_ ) if len(lowercase_ ) > max_length and max_length > 0: UpperCAmelCase = os.path.dirname(lowercase_ ) UpperCAmelCase = str(hash(lowercase_ ) ) UpperCAmelCase = filename[: max_length - len(lowercase_ ) - 8] + '...' + hashed_filename + '.lock' return os.path.join(lowercase_ , lowercase_ ) else: return path class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self :Tuple , lowercase_ :Tuple , lowercase_ :List[Any]=-1 , lowercase_ :Union[str, Any]=None ) -> Optional[Any]: from .file_utils import relative_to_absolute_path super().__init__(lowercase_ , timeout=lowercase_ , max_filename_length=lowercase_ ) UpperCAmelCase = '\\\\?\\' + relative_to_absolute_path(self.lock_file ) def UpperCAmelCase__ ( self :List[str] ) -> str: UpperCAmelCase = os.O_RDWR | os.O_CREAT | os.O_TRUNC try: UpperCAmelCase = os.open(self._lock_file , lowercase_ ) except OSError: pass else: try: msvcrt.locking(lowercase_ , msvcrt.LK_NBLCK , 1 ) except OSError: os.close(lowercase_ ) else: UpperCAmelCase = fd return None def UpperCAmelCase__ ( self :int ) -> Union[str, Any]: UpperCAmelCase = self._lock_file_fd UpperCAmelCase = None msvcrt.locking(lowercase_ , msvcrt.LK_UNLCK , 1 ) os.close(lowercase_ ) try: os.remove(self._lock_file ) # Probably another instance of the application # that acquired the file lock. except OSError: pass return None class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self :Optional[Any] , lowercase_ :str , lowercase_ :List[str]=-1 , lowercase_ :str=None ) -> str: UpperCAmelCase = os.statvfs(os.path.dirname(lowercase_ ) ).f_namemax super().__init__(lowercase_ , timeout=lowercase_ , max_filename_length=lowercase_ ) def UpperCAmelCase__ ( self :str ) -> Dict: UpperCAmelCase = os.O_RDWR | os.O_CREAT | os.O_TRUNC UpperCAmelCase = os.open(self._lock_file , lowercase_ ) try: fcntl.flock(lowercase_ , fcntl.LOCK_EX | fcntl.LOCK_NB ) except OSError: os.close(lowercase_ ) else: UpperCAmelCase = fd return None def UpperCAmelCase__ ( self :List[Any] ) -> List[Any]: # Do not remove the lockfile: # # https://github.com/benediktschmitt/py-filelock/issues/31 # https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition UpperCAmelCase = self._lock_file_fd UpperCAmelCase = None fcntl.flock(lowercase_ , fcntl.LOCK_UN ) os.close(lowercase_ ) return None class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def UpperCAmelCase__ ( self :List[Any] ) -> List[str]: UpperCAmelCase = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC try: UpperCAmelCase = os.open(self._lock_file , lowercase_ ) except OSError: pass else: UpperCAmelCase = fd return None def UpperCAmelCase__ ( self :Optional[int] ) -> List[Any]: os.close(self._lock_file_fd ) UpperCAmelCase = None try: os.remove(self._lock_file ) # The file is already deleted and that's what we want. except OSError: pass return None snake_case_ = None if msvcrt: snake_case_ = WindowsFileLock elif fcntl: snake_case_ = UnixFileLock else: snake_case_ = SoftFileLock if warnings is not None: warnings.warn("""only soft file lock is available""")
355
"""simple docstring""" import math def _lowerCAmelCase ( lowercase_ ): assert isinstance(lowercase_ , lowercase_ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False UpperCAmelCase = range(3 , int(math.sqrt(lowercase_ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _lowerCAmelCase ( lowercase_ , lowercase_=1 , **lowercase_ ): UpperCAmelCase = factor * value UpperCAmelCase = value while not is_prime(lowercase_ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase_ ) return value
181
0
"""simple docstring""" import numpy as np def __a ( __lowerCamelCase ): return 1 / (1 + np.exp(-vector )) def __a ( __lowerCamelCase ): return vector * sigmoid(__lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
61
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class A_ (lowercase__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = (DDIMParallelScheduler,) SCREAMING_SNAKE_CASE__ : Optional[Any] = (("""eta""", 0.0), ("""num_inference_steps""", 50)) def UpperCamelCase__ ( self , **lowercase_ ): """simple docstring""" UpperCAmelCase_ : int = { "num_train_timesteps": 1000, "beta_start": 0.00_01, "beta_end": 0.02, "beta_schedule": "linear", "clip_sample": True, } config.update(**lowercase_ ) return config def UpperCamelCase__ ( self , **lowercase_ ): """simple docstring""" UpperCAmelCase_ : Dict = self.scheduler_classes[0] UpperCAmelCase_ : Union[str, Any] = self.get_scheduler_config(**lowercase_ ) UpperCAmelCase_ : int = scheduler_class(**lowercase_ ) UpperCAmelCase_ , UpperCAmelCase_ : str = 10, 0.0 UpperCAmelCase_ : Optional[int] = self.dummy_model() UpperCAmelCase_ : str = self.dummy_sample_deter scheduler.set_timesteps(lowercase_ ) for t in scheduler.timesteps: UpperCAmelCase_ : Dict = model(lowercase_ , lowercase_ ) UpperCAmelCase_ : Dict = scheduler.step(lowercase_ , lowercase_ , lowercase_ , lowercase_ ).prev_sample return sample def UpperCamelCase__ ( self ): """simple docstring""" for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for steps_offset in [0, 1]: self.check_over_configs(steps_offset=lowercase_ ) UpperCAmelCase_ : str = self.scheduler_classes[0] UpperCAmelCase_ : List[str] = self.get_scheduler_config(steps_offset=1 ) UpperCAmelCase_ : List[str] = scheduler_class(**lowercase_ ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def UpperCamelCase__ ( self ): """simple docstring""" for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=lowercase_ , beta_end=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for clip_sample in [True, False]: self.check_over_configs(clip_sample=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" self.check_over_configs(thresholding=lowercase_ ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=lowercase_ , prediction_type=lowercase_ , sample_max_value=lowercase_ , ) def UpperCamelCase__ ( self ): """simple docstring""" for t in [1, 10, 49]: self.check_over_forward(time_step=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=lowercase_ , num_inference_steps=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=lowercase_ , eta=lowercase_ ) def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.scheduler_classes[0] UpperCAmelCase_ : List[str] = self.get_scheduler_config() UpperCAmelCase_ : List[str] = scheduler_class(**lowercase_ ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.1_47_71 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.3_24_60 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.0_09_79 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1E-5 def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Tuple = self.scheduler_classes[0] UpperCAmelCase_ : Optional[int] = self.get_scheduler_config() UpperCAmelCase_ : List[str] = scheduler_class(**lowercase_ ) UpperCAmelCase_ , UpperCAmelCase_ : Tuple = 10, 0.0 scheduler.set_timesteps(lowercase_ ) UpperCAmelCase_ : Union[str, Any] = self.dummy_model() UpperCAmelCase_ : List[str] = self.dummy_sample_deter UpperCAmelCase_ : Any = self.dummy_sample_deter + 0.1 UpperCAmelCase_ : int = self.dummy_sample_deter - 0.1 UpperCAmelCase_ : List[Any] = samplea.shape[0] UpperCAmelCase_ : int = torch.stack([samplea, samplea, samplea] , dim=0 ) UpperCAmelCase_ : int = torch.arange(lowercase_ )[0:3, None].repeat(1 , lowercase_ ) UpperCAmelCase_ : int = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) UpperCAmelCase_ : Optional[Any] = scheduler.batch_step_no_noise(lowercase_ , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , lowercase_ ) UpperCAmelCase_ : List[Any] = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase_ : str = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 11_47.79_04 ) < 1E-2 assert abs(result_mean.item() - 0.49_82 ) < 1E-3 def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : Tuple = self.full_loop() UpperCAmelCase_ : int = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase_ : List[str] = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_72.00_67 ) < 1E-2 assert abs(result_mean.item() - 0.22_39_67 ) < 1E-3 def UpperCamelCase__ ( self ): """simple docstring""" UpperCAmelCase_ : List[str] = self.full_loop(prediction_type="v_prediction" ) UpperCAmelCase_ : str = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase_ : Dict = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 52.53_02 ) < 1E-2 assert abs(result_mean.item() - 0.06_84 ) < 1E-3 def UpperCamelCase__ ( self ): """simple docstring""" # We specify different beta, so that the first alpha is 0.99 UpperCAmelCase_ : List[str] = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01 ) UpperCAmelCase_ : Dict = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase_ : Tuple = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_49.82_95 ) < 1E-2 assert abs(result_mean.item() - 0.19_51 ) < 1E-3 def UpperCamelCase__ ( self ): """simple docstring""" # We specify different beta, so that the first alpha is 0.99 UpperCAmelCase_ : int = self.full_loop(set_alpha_to_one=lowercase_ , beta_start=0.01 ) UpperCAmelCase_ : List[Any] = torch.sum(torch.abs(lowercase_ ) ) UpperCAmelCase_ : Dict = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_sum.item() - 1_49.07_84 ) < 1E-2 assert abs(result_mean.item() - 0.19_41 ) < 1E-3
61
1
"""simple docstring""" from __future__ import annotations def __lowerCAmelCase ( lowercase : float , lowercase : float , lowercase : float ) -> str: """simple docstring""" if (voltage, current, resistance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance < 0: raise ValueError("Resistance cannot be negative" ) if voltage == 0: return {"voltage": float(current * resistance )} elif current == 0: return {"current": voltage / resistance} elif resistance == 0: return {"resistance": voltage / current} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
370
"""simple docstring""" import argparse import logging import pickle from collections import Counter logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO ) __snake_case = logging.getLogger(__name__) if __name__ == "__main__": __snake_case = argparse.ArgumentParser( description="""Token Counts for smoothing the masking probabilities in MLM (cf XLM/word2vec)""" ) parser.add_argument( """--data_file""", type=str, default="""data/dump.bert-base-uncased.pickle""", help="""The binarized dataset.""" ) parser.add_argument( """--token_counts_dump""", type=str, default="""data/token_counts.bert-base-uncased.pickle""", help="""The dump file.""" ) parser.add_argument("""--vocab_size""", default=30522, type=int) __snake_case = parser.parse_args() logger.info(F'''Loading data from {args.data_file}''') with open(args.data_file, """rb""") as fp: __snake_case = pickle.load(fp) logger.info("""Counting occurrences for MLM.""") __snake_case = Counter() for tk_ids in data: counter.update(tk_ids) __snake_case = [0] * args.vocab_size for k, v in counter.items(): __snake_case = v logger.info(F'''Dump to {args.token_counts_dump}''') with open(args.token_counts_dump, """wb""") as handle: pickle.dump(counts, handle, protocol=pickle.HIGHEST_PROTOCOL)
112
0
from collections.abc import Callable from math import pi, sqrt from random import uniform from statistics import mean def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int ) -> Optional[int]: # A local function to see if a dot lands in the circle. def is_in_circle(SCREAMING_SNAKE_CASE : float , SCREAMING_SNAKE_CASE : float ) -> bool: __lowercase = sqrt((x**2) + (y**2) ) # Our circle has a radius of 1, so a distance # greater than 1 would land outside the circle. return distance_from_centre <= 1 # The proportion of guesses that landed in the circle __lowercase = mean( int(is_in_circle(uniform(-1.0 , 1.0 ) , uniform(-1.0 , 1.0 ) ) ) for _ in range(SCREAMING_SNAKE_CASE ) ) # The ratio of the area for circle to square is pi/4. __lowercase = proportion * 4 print(F"""The estimated value of pi is {pi_estimate}""" ) print(F"""The numpy value of pi is {pi}""" ) print(F"""The total error is {abs(pi - pi_estimate )}""" ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : Callable[[float], float] , SCREAMING_SNAKE_CASE : float = 0.0 , SCREAMING_SNAKE_CASE : float = 1.0 , ) -> float: return mean( function_to_integrate(uniform(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) ) for _ in range(SCREAMING_SNAKE_CASE ) ) * (max_value - min_value) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : float = 0.0 , SCREAMING_SNAKE_CASE : float = 1.0 ) -> None: def identity_function(SCREAMING_SNAKE_CASE : float ) -> float: return x __lowercase = area_under_curve_estimator( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) __lowercase = (max_value * max_value - min_value * min_value) / 2 print('******************' ) print(F"""Estimating area under y=x where x varies from {min_value} to {max_value}""" ) print(F"""Estimated value is {estimated_value}""" ) print(F"""Expected value is {expected_value}""" ) print(F"""Total error is {abs(estimated_value - expected_value )}""" ) print('******************' ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : int ) -> None: def function_to_integrate(SCREAMING_SNAKE_CASE : float ) -> float: return sqrt(4.0 - x * x ) __lowercase = area_under_curve_estimator( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , 0.0 , 2.0 ) print('******************' ) print('Estimating pi using area_under_curve_estimator' ) print(F"""Estimated value is {estimated_value}""" ) print(F"""Expected value is {pi}""" ) print(F"""Total error is {abs(estimated_value - pi )}""" ) print('******************' ) if __name__ == "__main__": import doctest doctest.testmod()
325
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger SCREAMING_SNAKE_CASE__ = get_logger(__name__) class A__ ( enum.Enum ): lowerCAmelCase__ : Dict = "all_checks" lowerCAmelCase__ : List[Any] = "basic_checks" lowerCAmelCase__ : Dict = "no_checks" class A__ ( lowerCAmelCase__ ): pass class A__ ( lowerCAmelCase__ ): pass class A__ ( lowerCAmelCase__ ): pass class A__ ( lowerCAmelCase__ ): pass def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[dict] , SCREAMING_SNAKE_CASE : dict , SCREAMING_SNAKE_CASE : Optional[Any]=None ) -> Optional[Any]: if expected_checksums is None: logger.info('Unable to verify checksums.' ) return if len(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) ) if len(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) > 0: raise UnexpectedDownloadedFile(str(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) ) __lowercase = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] __lowercase = ' for ' + verification_name if verification_name is not None else '' if len(SCREAMING_SNAKE_CASE ) > 0: raise NonMatchingChecksumError( F"""Checksums didn't match{for_verification_name}:\n""" F"""{bad_urls}\n""" 'Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error' ) logger.info('All the checksums matched successfully' + for_verification_name ) class A__ ( lowerCAmelCase__ ): pass class A__ ( lowerCAmelCase__ ): pass class A__ ( lowerCAmelCase__ ): pass class A__ ( lowerCAmelCase__ ): pass def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[dict] , SCREAMING_SNAKE_CASE : dict ) -> Optional[int]: if expected_splits is None: logger.info('Unable to verify splits sizes.' ) return if len(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) > 0: raise ExpectedMoreSplits(str(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) ) if len(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) > 0: raise UnexpectedSplits(str(set(SCREAMING_SNAKE_CASE ) - set(SCREAMING_SNAKE_CASE ) ) ) __lowercase = [ {'expected': expected_splits[name], 'recorded': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(SCREAMING_SNAKE_CASE ) > 0: raise NonMatchingSplitsSizesError(str(SCREAMING_SNAKE_CASE ) ) logger.info('All the splits matched successfully.' ) def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : bool = True ) -> dict: if record_checksum: __lowercase = shaaaa() with open(SCREAMING_SNAKE_CASE , 'rb' ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , b'' ): m.update(SCREAMING_SNAKE_CASE ) __lowercase = m.hexdigest() else: __lowercase = None return {"num_bytes": os.path.getsize(SCREAMING_SNAKE_CASE ), "checksum": checksum} def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[int] ) -> Dict: if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
325
1
'''simple docstring''' import math from collections.abc import Callable def SCREAMING_SNAKE_CASE__( _UpperCamelCase : Callable[[float], float] , _UpperCamelCase : float , _UpperCamelCase : float ) -> float: '''simple docstring''' UpperCamelCase__ = xa UpperCamelCase__ = xa while True: if x_n == x_na or function(_UpperCamelCase ) == function(_UpperCamelCase ): raise ZeroDivisionError("float division by zero, could not find root" ) UpperCamelCase__ = x_na - ( function(_UpperCamelCase ) / ((function(_UpperCamelCase ) - function(_UpperCamelCase )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na UpperCamelCase__ = x_na UpperCamelCase__ = x_na def SCREAMING_SNAKE_CASE__( _UpperCamelCase : float ) -> float: '''simple docstring''' return math.pow(_UpperCamelCase , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
31
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE__( _UpperCamelCase : float , _UpperCamelCase : float , _UpperCamelCase : float , ) -> tuple: '''simple docstring''' if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError("You cannot supply more or less than 2 values" ) elif electron_conc < 0: raise ValueError("Electron concentration cannot be negative in a semiconductor" ) elif hole_conc < 0: raise ValueError("Hole concentration cannot be negative in a semiconductor" ) elif intrinsic_conc < 0: raise ValueError( "Intrinsic concentration cannot be negative in a semiconductor" ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
31
1
import collections import inspect import unittest from transformers import SwinvaConfig 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A : """simple docstring""" def __init__( self : Any,lowercase_ : List[str],lowercase_ : Any=1_3,lowercase_ : Union[str, Any]=3_2,lowercase_ : Dict=2,lowercase_ : str=3,lowercase_ : List[str]=1_6,lowercase_ : Optional[Any]=[1, 2, 1],lowercase_ : List[str]=[2, 2, 4],lowercase_ : Optional[int]=2,lowercase_ : str=2.0,lowercase_ : Optional[int]=True,lowercase_ : Any=0.0,lowercase_ : Optional[int]=0.0,lowercase_ : Union[str, Any]=0.1,lowercase_ : int="gelu",lowercase_ : List[Any]=False,lowercase_ : Any=True,lowercase_ : Any=0.02,lowercase_ : str=1E-5,lowercase_ : Tuple=True,lowercase_ : Dict=None,lowercase_ : int=True,lowercase_ : Union[str, Any]=1_0,lowercase_ : Tuple=8,)-> List[Any]: '''simple docstring''' A__ = parent A__ = batch_size A__ = image_size A__ = patch_size A__ = num_channels A__ = embed_dim A__ = depths A__ = num_heads A__ = window_size A__ = mlp_ratio A__ = qkv_bias A__ = hidden_dropout_prob A__ = attention_probs_dropout_prob A__ = drop_path_rate A__ = hidden_act A__ = use_absolute_embeddings A__ = patch_norm A__ = layer_norm_eps A__ = initializer_range A__ = is_training A__ = scope A__ = use_labels A__ = type_sequence_label_size A__ = encoder_stride def snake_case__ ( self : Dict )-> Any: '''simple docstring''' A__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) A__ = None if self.use_labels: A__ = ids_tensor([self.batch_size],self.type_sequence_label_size ) A__ = self.get_config() return config, pixel_values, labels def snake_case__ ( self : Union[str, Any] )-> Tuple: '''simple docstring''' return SwinvaConfig( image_size=self.image_size,patch_size=self.patch_size,num_channels=self.num_channels,embed_dim=self.embed_dim,depths=self.depths,num_heads=self.num_heads,window_size=self.window_size,mlp_ratio=self.mlp_ratio,qkv_bias=self.qkv_bias,hidden_dropout_prob=self.hidden_dropout_prob,attention_probs_dropout_prob=self.attention_probs_dropout_prob,drop_path_rate=self.drop_path_rate,hidden_act=self.hidden_act,use_absolute_embeddings=self.use_absolute_embeddings,path_norm=self.patch_norm,layer_norm_eps=self.layer_norm_eps,initializer_range=self.initializer_range,encoder_stride=self.encoder_stride,) def snake_case__ ( self : str,lowercase_ : str,lowercase_ : Any,lowercase_ : int )-> Dict: '''simple docstring''' A__ = SwinvaModel(config=lowercase_ ) model.to(lowercase_ ) model.eval() A__ = model(lowercase_ ) A__ = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) A__ = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape,(self.batch_size, expected_seq_len, expected_dim) ) def snake_case__ ( self : Tuple,lowercase_ : int,lowercase_ : Dict,lowercase_ : List[str] )-> Optional[int]: '''simple docstring''' A__ = SwinvaForMaskedImageModeling(config=lowercase_ ) model.to(lowercase_ ) model.eval() A__ = model(lowercase_ ) self.parent.assertEqual( result.logits.shape,(self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images A__ = 1 A__ = SwinvaForMaskedImageModeling(lowercase_ ) model.to(lowercase_ ) model.eval() A__ = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) A__ = model(lowercase_ ) self.parent.assertEqual(result.logits.shape,(self.batch_size, 1, self.image_size, self.image_size) ) def snake_case__ ( self : List[Any],lowercase_ : str,lowercase_ : Tuple,lowercase_ : Dict )-> Tuple: '''simple docstring''' A__ = self.type_sequence_label_size A__ = SwinvaForImageClassification(lowercase_ ) model.to(lowercase_ ) model.eval() A__ = model(lowercase_,labels=lowercase_ ) self.parent.assertEqual(result.logits.shape,(self.batch_size, self.type_sequence_label_size) ) def snake_case__ ( self : int )-> str: '''simple docstring''' A__ = self.prepare_config_and_inputs() A__ , A__ , A__ = config_and_inputs A__ = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class A ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCamelCase = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) lowerCamelCase = ( {'feature-extraction': SwinvaModel, 'image-classification': SwinvaForImageClassification} if is_torch_available() else {} ) lowerCamelCase = False lowerCamelCase = False lowerCamelCase = False lowerCamelCase = False def snake_case__ ( self : Tuple )-> Tuple: '''simple docstring''' A__ = SwinvaModelTester(self ) A__ = ConfigTester(self,config_class=lowercase_,embed_dim=3_7 ) def snake_case__ ( self : Dict )-> Tuple: '''simple docstring''' self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def snake_case__ ( self : int )-> Optional[Any]: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase_ ) @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.' ) def snake_case__ ( self : int )-> Optional[int]: '''simple docstring''' pass @unittest.skip(reason='Swinv2 does not use inputs_embeds' ) def snake_case__ ( self : Any )-> Dict: '''simple docstring''' pass def snake_case__ ( self : int )-> List[Any]: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(lowercase_ ) self.assertIsInstance(model.get_input_embeddings(),(nn.Module) ) A__ = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase_,nn.Linear ) ) def snake_case__ ( self : Any )-> int: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(lowercase_ ) A__ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic A__ = [*signature.parameters.keys()] A__ = ['pixel_values'] self.assertListEqual(arg_names[:1],lowercase_ ) def snake_case__ ( self : List[str] )-> Tuple: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = True for model_class in self.all_model_classes: A__ = True A__ = False A__ = True A__ = model_class(lowercase_ ) model.to(lowercase_ ) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(lowercase_,lowercase_ ) ) A__ = outputs.attentions A__ = len(self.model_tester.depths ) self.assertEqual(len(lowercase_ ),lowercase_ ) # check that output_attentions also work using config del inputs_dict["output_attentions"] A__ = True A__ = config.window_size**2 A__ = model_class(lowercase_ ) model.to(lowercase_ ) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(lowercase_,lowercase_ ) ) A__ = outputs.attentions self.assertEqual(len(lowercase_ ),lowercase_ ) self.assertListEqual( list(attentions[0].shape[-3:] ),[self.model_tester.num_heads[0], window_size_squared, window_size_squared],) A__ = len(lowercase_ ) # Check attention is always last and order is fine A__ = True A__ = True A__ = model_class(lowercase_ ) model.to(lowercase_ ) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(lowercase_,lowercase_ ) ) if hasattr(self.model_tester,'num_hidden_states_types' ): A__ = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states A__ = 2 self.assertEqual(out_len + added_hidden_states,len(lowercase_ ) ) A__ = outputs.attentions self.assertEqual(len(lowercase_ ),lowercase_ ) self.assertListEqual( list(self_attentions[0].shape[-3:] ),[self.model_tester.num_heads[0], window_size_squared, window_size_squared],) def snake_case__ ( self : Dict,lowercase_ : Tuple,lowercase_ : Optional[Any],lowercase_ : Optional[int],lowercase_ : Dict )-> List[Any]: '''simple docstring''' A__ = model_class(lowercase_ ) model.to(lowercase_ ) model.eval() with torch.no_grad(): A__ = model(**self._prepare_for_class(lowercase_,lowercase_ ) ) A__ = outputs.hidden_states A__ = getattr( self.model_tester,'expected_num_hidden_layers',len(self.model_tester.depths ) + 1 ) self.assertEqual(len(lowercase_ ),lowercase_ ) # Swinv2 has a different seq_length A__ = ( config.patch_size if isinstance(config.patch_size,collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A__ = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ),[num_patches, self.model_tester.embed_dim],) A__ = outputs.reshaped_hidden_states self.assertEqual(len(lowercase_ ),lowercase_ ) A__ , A__ , A__ , A__ = reshaped_hidden_states[0].shape A__ = ( reshaped_hidden_states[0].view(lowercase_,lowercase_,height * width ).permute(0,2,1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ),[num_patches, self.model_tester.embed_dim],) def snake_case__ ( self : int )-> List[Any]: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size,collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: A__ = True self.check_hidden_states_output(lowercase_,lowercase_,lowercase_,lowercase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A__ = True self.check_hidden_states_output(lowercase_,lowercase_,lowercase_,lowercase_ ) def snake_case__ ( self : Union[str, Any] )-> Dict: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = 3 A__ = ( self.model_tester.image_size if isinstance(self.model_tester.image_size,collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) A__ = ( config.patch_size if isinstance(config.patch_size,collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) A__ = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) A__ = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: A__ = True self.check_hidden_states_output(lowercase_,lowercase_,lowercase_,(padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] A__ = True self.check_hidden_states_output(lowercase_,lowercase_,lowercase_,(padded_height, padded_width) ) def snake_case__ ( self : Optional[Any] )-> int: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_ ) def snake_case__ ( self : Optional[int] )-> Tuple: '''simple docstring''' A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase_ ) @slow def snake_case__ ( self : str )-> Any: '''simple docstring''' for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: A__ = SwinvaModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) def snake_case__ ( self : Union[str, Any] )-> Tuple: '''simple docstring''' A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() A__ = _config_zero_init(lowercase_ ) for model_class in self.all_model_classes: A__ = model_class(config=lowercase_ ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item(),[0.0, 1.0],msg=F'Parameter {name} of model {model_class} seems not properly initialized',) @require_vision @require_torch class A ( unittest.TestCase ): """simple docstring""" @cached_property def snake_case__ ( self : int )-> Dict: '''simple docstring''' return ( AutoImageProcessor.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ) if is_vision_available() else None ) @slow def snake_case__ ( self : List[Any] )-> Any: '''simple docstring''' A__ = SwinvaForImageClassification.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ).to( lowercase_ ) A__ = self.default_image_processor A__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) A__ = image_processor(images=lowercase_,return_tensors='pt' ).to(lowercase_ ) # forward pass with torch.no_grad(): A__ = model(**lowercase_ ) # verify the logits A__ = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape,lowercase_ ) A__ = torch.tensor([-0.3_947, -0.4_306, 0.0_026] ).to(lowercase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3],lowercase_,atol=1E-4 ) )
7
import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home _UpperCAmelCase : Optional[int] = HUGGINGFACE_HUB_CACHE _UpperCAmelCase : List[str] = "config.json" _UpperCAmelCase : Union[str, Any] = "diffusion_pytorch_model.bin" _UpperCAmelCase : List[Any] = "diffusion_flax_model.msgpack" _UpperCAmelCase : Optional[Any] = "model.onnx" _UpperCAmelCase : int = "diffusion_pytorch_model.safetensors" _UpperCAmelCase : Optional[Any] = "weights.pb" _UpperCAmelCase : Tuple = "https://huggingface.co" _UpperCAmelCase : Union[str, Any] = default_cache_path _UpperCAmelCase : Optional[Any] = "diffusers_modules" _UpperCAmelCase : List[Any] = os.getenv("HF_MODULES_CACHE", os.path.join(hf_cache_home, "modules")) _UpperCAmelCase : Tuple = ["fp16", "non-ema"] _UpperCAmelCase : Any = ".self_attn"
222
0
def UpperCamelCase ( snake_case__ : int ) -> int: if n == 1 or not isinstance(snake_case__ , snake_case__ ): return 0 elif n == 2: return 1 else: UpperCamelCase : Optional[Any] = [0, 1] for i in range(2 , n + 1 ): sequence.append(sequence[i - 1] + sequence[i - 2] ) return sequence[n] def UpperCamelCase ( snake_case__ : int ) -> int: UpperCamelCase : Union[str, Any] = 0 UpperCamelCase : str = 2 while digits < n: index += 1 UpperCamelCase : str = len(str(fibonacci(snake_case__ ) ) ) return index def UpperCamelCase ( snake_case__ : int = 1000 ) -> int: return fibonacci_digits_index(snake_case__ ) if __name__ == "__main__": print(solution(int(str(input()).strip())))
103
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=13, SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_=224, SCREAMING_SNAKE_CASE_=30, SCREAMING_SNAKE_CASE_=400, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5], SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5], ) -> List[str]: UpperCamelCase : Optional[int] = size if size is not None else {'height': 18, 'width': 18} UpperCamelCase : List[Any] = parent UpperCamelCase : List[Any] = batch_size UpperCamelCase : int = num_channels UpperCamelCase : int = image_size UpperCamelCase : List[Any] = min_resolution UpperCamelCase : int = max_resolution UpperCamelCase : Any = do_resize UpperCamelCase : Optional[int] = size UpperCamelCase : List[str] = do_normalize UpperCamelCase : Optional[Any] = image_mean UpperCamelCase : Tuple = image_std def snake_case_ ( self ) -> List[Any]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class lowerCAmelCase_ ( a__ , unittest.TestCase ): UpperCAmelCase__ : Optional[Any] = ViTImageProcessor if is_vision_available() else None def snake_case_ ( self ) -> Any: UpperCamelCase : Dict = EfficientFormerImageProcessorTester(self ) @property def snake_case_ ( self ) -> List[Any]: return self.image_proc_tester.prepare_image_processor_dict() def snake_case_ ( self ) -> Optional[int]: UpperCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'image_mean' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'image_std' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'do_normalize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'do_resize' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_, 'size' ) ) def snake_case_ ( self ) -> Any: pass def snake_case_ ( self ) -> int: # Initialize image_processor UpperCamelCase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCamelCase : List[str] = prepare_image_inputs(self.image_proc_tester, equal_resolution=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_, Image.Image ) # Test not batched input UpperCamelCase : str = image_processor(image_inputs[0], return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), ) # Test batched UpperCamelCase : Optional[Any] = image_processor(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), ) def snake_case_ ( self ) -> str: # Initialize image_processor UpperCamelCase : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCamelCase : Union[str, Any] = prepare_image_inputs(self.image_proc_tester, equal_resolution=SCREAMING_SNAKE_CASE_, numpify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_, np.ndarray ) # Test not batched input UpperCamelCase : Dict = image_processor(image_inputs[0], return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), ) # Test batched UpperCamelCase : Dict = image_processor(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), ) def snake_case_ ( self ) -> Tuple: # Initialize image_processor UpperCamelCase : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCamelCase : int = prepare_image_inputs(self.image_proc_tester, equal_resolution=SCREAMING_SNAKE_CASE_, torchify=SCREAMING_SNAKE_CASE_ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE_, torch.Tensor ) # Test not batched input UpperCamelCase : Optional[int] = image_processor(image_inputs[0], return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), ) # Test batched UpperCamelCase : int = image_processor(SCREAMING_SNAKE_CASE_, return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape, ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size['height'], self.image_proc_tester.size['width'], ), )
103
1
'''simple docstring''' # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys A =subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') A =subprocess.check_output(f"""git diff --name-only {fork_point_sha}""".split()).decode('utf-8').split() A ='|'.join(sys.argv[1:]) A =re.compile(rf"""^({joined_dirs}).*?\.py$""") A =[x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
34
'''simple docstring''' import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) A =logging.getLogger(__name__) A ='Hello world! cécé herlolip' A =namedtuple( 'BertAbsConfig', [ 'temp_dir', 'large', 'use_bert_emb', 'finetune_bert', 'encoder', 'share_emb', 'max_pos', 'enc_layers', 'enc_hidden_size', 'enc_heads', 'enc_ff_size', 'enc_dropout', 'dec_layers', 'dec_hidden_size', 'dec_heads', 'dec_ff_size', 'dec_dropout', ], ) def snake_case_ (_a : List[Any] , _a : Any ): UpperCAmelCase = BertAbsConfig( temp_dir='''.''' , finetune_bert=_a , large=_a , share_emb=_a , use_bert_emb=_a , encoder='''bert''' , max_pos=5_1_2 , enc_layers=6 , enc_hidden_size=5_1_2 , enc_heads=8 , enc_ff_size=5_1_2 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_6_8 , dec_heads=8 , dec_ff_size=2_0_4_8 , dec_dropout=0.2 , ) UpperCAmelCase = torch.load(_a , lambda _a , _a : storage ) UpperCAmelCase = AbsSummarizer(_a , torch.device('''cpu''' ) , _a ) original.eval() UpperCAmelCase = BertAbsSummarizer(_a , torch.device('''cpu''' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('''convert the model''' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('''Make sure that the models\' outputs are identical''' ) UpperCAmelCase = BertTokenizer.from_pretrained('''bert-base-uncased''' ) # prepare the model inputs UpperCAmelCase = tokenizer.encode('''This is sample éàalj\'-.''' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(_a )) ) UpperCAmelCase = torch.tensor(_a ).unsqueeze(0 ) UpperCAmelCase = tokenizer.encode('''This is sample 3 éàalj\'-.''' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_1_2 - len(_a )) ) UpperCAmelCase = torch.tensor(_a ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass UpperCAmelCase = encoder_input_ids UpperCAmelCase = decoder_input_ids UpperCAmelCase = UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = UpperCAmelCase = None UpperCAmelCase = UpperCAmelCase = None UpperCAmelCase = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical UpperCAmelCase = original(_a , _a , _a , _a , _a , _a , _a )[0] UpperCAmelCase = original.generator(_a ) UpperCAmelCase = new_model( _a , _a , _a , _a , _a )[0] UpperCAmelCase = new_model.generator(_a ) UpperCAmelCase = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('''Maximum absolute difference beween weights: {:.2f}'''.format(_a ) ) UpperCAmelCase = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('''Maximum absolute difference beween weights: {:.2f}'''.format(_a ) ) UpperCAmelCase = torch.allclose(_a , _a , atol=1E-3 ) if are_identical: logging.info('''all weights are equal up to 1e-3''' ) else: raise ValueError('''the weights are different. The new model is likely different from the original one.''' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('''saving the model\'s state dictionary''' ) torch.save( new_model.state_dict() , '''./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin''' ) if __name__ == "__main__": A =argparse.ArgumentParser() parser.add_argument( '--bertabs_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.', ) A =parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
34
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 _A = 'bart' _A = True @st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( ): if LOAD_DENSE_INDEX: __UpperCamelCase =AutoTokenizer.from_pretrained('yjernite/retribert-base-uncased' ) __UpperCamelCase =AutoModel.from_pretrained('yjernite/retribert-base-uncased' ).to('cuda:0' ) __UpperCamelCase =qar_model.eval() else: __UpperCamelCase , __UpperCamelCase =(None, None) if MODEL_TYPE == "bart": __UpperCamelCase =AutoTokenizer.from_pretrained('yjernite/bart_eli5' ) __UpperCamelCase =AutoModelForSeqaSeqLM.from_pretrained('yjernite/bart_eli5' ).to('cuda:0' ) __UpperCamelCase =torch.load('seq2seq_models/eli5_bart_model_blm_2.pth' ) sas_model.load_state_dict(save_dict['model'] ) __UpperCamelCase =sas_model.eval() else: __UpperCamelCase , __UpperCamelCase =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: __UpperCamelCase =faiss.StandardGpuResources() __UpperCamelCase =datasets.load_dataset(path='wiki_snippets' , name='wiki40b_en_100_0' )['train'] __UpperCamelCase =np.memmap( 'wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat' , dtype='float32' , mode='r' , shape=(wikiaab_passages.num_rows, 1_28) , ) __UpperCamelCase =faiss.IndexFlatIP(1_28 ) __UpperCamelCase =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: __UpperCamelCase , __UpperCamelCase =(None, None) __UpperCamelCase =Elasticsearch([{'host': 'localhost', 'port': '9200'}] ) return (wikiaab_passages, wikiaab_gpu_index_flat, es_client) @st.cache(allow_output_mutation=SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( ): __UpperCamelCase =datasets.load_dataset('eli5' , name='LFQA_reddit' ) __UpperCamelCase =elia['train_eli5'] __UpperCamelCase =np.memmap( 'eli5_questions_reps.dat' , dtype='float32' , mode='r' , shape=(elia_train.num_rows, 1_28) ) __UpperCamelCase =faiss.IndexFlatIP(1_28 ) eli5_train_q_index.add(SCREAMING_SNAKE_CASE__ ) return (elia_train, eli5_train_q_index) _A , _A , _A = load_indexes() _A , _A , _A , _A = load_models() _A , _A = load_train_data() def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=10 ): __UpperCamelCase =embed_questions_for_retrieval([question] , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase , __UpperCamelCase =eli5_train_q_index.search(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =[elia_train[int(SCREAMING_SNAKE_CASE__ )] for i in I[0]] return nn_examples def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]="wiki40b" , SCREAMING_SNAKE_CASE__ : Optional[int]="dense" , SCREAMING_SNAKE_CASE__ : Optional[Any]=10 ): if source == "none": __UpperCamelCase , __UpperCamelCase =(' <P> '.join(['' for _ in range(11 )] ).strip(), []) else: if method == "dense": __UpperCamelCase , __UpperCamelCase =query_qa_dense_index( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: __UpperCamelCase , __UpperCamelCase =query_es_index( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , index_name='english_wiki40b_snippets_100w' , n_results=SCREAMING_SNAKE_CASE__ , ) __UpperCamelCase =[ (res['article_title'], res['section_title'].strip(), res['score'], res['passage_text']) for res in hit_lst ] __UpperCamelCase ='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__ : List[str] , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : str=64 , SCREAMING_SNAKE_CASE__ : Dict=2_56 , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : Any=0.95 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0.8 ): with torch.no_grad(): __UpperCamelCase =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=10_24 , device='cuda:0' , )[0] return (answer, support_list) st.title('Long Form Question Answering with ELI5') # Start sidebar _A = '<img src=\'https://huggingface.co/front/assets/huggingface_logo.svg\'>' _A = '\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 _A = '\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) _A = [ 'Answer the question', 'View the retrieved document only', 'View the most similar ELI5 question and answer', 'Show me everything, please!', ] _A = st.sidebar.checkbox('Demo options') if demo_options: _A = st.sidebar.selectbox( '', action_list, index=3, ) _A = action_list.index(action_st) _A = st.sidebar.selectbox( '', ['Show full text of passages', 'Show passage section titles'], index=0, ) _A = show_type == 'Show full text of passages' else: _A = 3 _A = True _A = st.sidebar.checkbox('Retrieval options') if retrieval_options: _A = '\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) _A = st.sidebar.selectbox('Which Wikipedia format should the model use?', ['wiki40b', 'none']) _A = st.sidebar.selectbox('Which Wikipedia indexer should the model use?', ['dense', 'sparse', 'mixed']) else: _A = 'wiki40b' _A = 'dense' _A = 'beam' _A = 2 _A = 64 _A = 256 _A = None _A = None _A = st.sidebar.checkbox('Generation options') if generate_options: _A = '\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) _A = st.sidebar.selectbox('Would you like to use beam search or sample an answer?', ['beam', 'sampled']) _A = st.sidebar.slider( 'Minimum generation length', min_value=8, max_value=256, value=64, step=8, format=None, key=None ) _A = st.sidebar.slider( 'Maximum generation length', min_value=64, max_value=512, value=256, step=16, format=None, key=None ) if sampled == "beam": _A = st.sidebar.slider('Beam size', min_value=1, max_value=8, value=2, step=None, format=None, key=None) else: _A = st.sidebar.slider( 'Nucleus sampling p', min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None ) _A = st.sidebar.slider( 'Temperature', min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None ) _A = None # start main text _A = [ '<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?', ] _A = 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>": _A = st.text_input('Enter your question here:', '') else: _A = question_s if st.button('Show me!'): if action in [0, 1, 3]: if index_type == "mixed": _A , _A = make_support(question, source=wiki_source, method='dense', n_results=10) _A , _A = make_support(question, source=wiki_source, method='sparse', n_results=10) _A = [] 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)] _A = support_list[:10] _A = '<P> ' + ' <P> '.join([res[-1] for res in support_list]) else: _A , _A = make_support(question, source=wiki_source, method=index_type, n_results=10) if action in [0, 3]: _A , _A = 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): _A = 'https://en.wikipedia.org/wiki/{}'.format(res[0].replace(' ', '_')) _A = res[1].strip() if sec_titles == "": _A = '[{}]({})'.format(res[0], wiki_url) else: _A = sec_titles.split(' & ') _A = ' & '.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]: _A = find_nearest_training(question) _A = nn_train_list[0] st.markdown( '--- \n ### The most similar question in the ELI5 training set was: \n\n {}'.format(train_exple['title']) ) _A = [ '{}. {}'.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))) _A = '\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)
350
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, is_vision_available, ) _A = {'configuration_vit': ['VIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTConfig', 'ViTOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = ['ViTFeatureExtractor'] _A = ['ViTImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'VIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTForImageClassification', 'ViTForMaskedImageModeling', 'ViTModel', 'ViTPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'TFViTForImageClassification', 'TFViTModel', 'TFViTPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _A = [ 'FlaxViTForImageClassification', 'FlaxViTModel', 'FlaxViTPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_vit import ViTFeatureExtractor from .image_processing_vit import ViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit import ( VIT_PRETRAINED_MODEL_ARCHIVE_LIST, ViTForImageClassification, ViTForMaskedImageModeling, ViTModel, ViTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel else: import sys _A = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
117
0
"""simple docstring""" import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class A__ ( unittest.TestCase ): '''simple docstring''' @slow def _SCREAMING_SNAKE_CASE ( self: Union[str, Any]) -> str: """simple docstring""" __lowerCAmelCase : Optional[Any] = FlaxMTaForConditionalGeneration.from_pretrained("google/mt5-small") __lowerCAmelCase : Optional[Any] = AutoTokenizer.from_pretrained("google/mt5-small") __lowerCAmelCase : Tuple = tokenizer("Hello there" , return_tensors="np").input_ids __lowerCAmelCase : Dict = tokenizer("Hi I am" , return_tensors="np").input_ids __lowerCAmelCase : str = shift_tokens_right(_SCREAMING_SNAKE_CASE , model.config.pad_token_id , model.config.decoder_start_token_id) __lowerCAmelCase : Optional[int] = model(_SCREAMING_SNAKE_CASE , decoder_input_ids=_SCREAMING_SNAKE_CASE).logits __lowerCAmelCase : int = optax.softmax_cross_entropy(_SCREAMING_SNAKE_CASE , onehot(_SCREAMING_SNAKE_CASE , logits.shape[-1])).mean() __lowerCAmelCase : List[str] = -(labels.shape[-1] * loss.item()) __lowerCAmelCase : str = -84.9127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4)
269
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self: Optional[int] , _SCREAMING_SNAKE_CASE: str) -> Dict: """simple docstring""" with open(_SCREAMING_SNAKE_CASE , encoding="utf-8") as input_file: __lowerCAmelCase : List[str] = re.compile(r"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)") __lowerCAmelCase : List[Any] = input_file.read() __lowerCAmelCase : Any = regexp.search(_SCREAMING_SNAKE_CASE) return match def _SCREAMING_SNAKE_CASE ( self: List[Any] , _SCREAMING_SNAKE_CASE: str) -> Optional[Any]: """simple docstring""" with open(_SCREAMING_SNAKE_CASE , encoding="utf-8") as input_file: __lowerCAmelCase : Any = re.compile(r"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL) __lowerCAmelCase : Optional[int] = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` __lowerCAmelCase : int = regexp.finditer(_SCREAMING_SNAKE_CASE) __lowerCAmelCase : Union[str, Any] = [match for match in matches if match is not None and match.group(1) is not None] return matches[0] if matches else None def _SCREAMING_SNAKE_CASE ( self: str) -> List[Any]: """simple docstring""" __lowerCAmelCase : Optional[Any] = Path("./datasets") __lowerCAmelCase : Optional[int] = list(dataset_paths.absolute().glob("**/*.py")) for dataset in dataset_files: if self._no_encoding_on_file_open(str(_SCREAMING_SNAKE_CASE)): raise AssertionError(F"""open(...) must use utf-8 encoding in {dataset}""") def _SCREAMING_SNAKE_CASE ( self: Optional[Any]) -> Optional[int]: """simple docstring""" __lowerCAmelCase : Dict = Path("./datasets") __lowerCAmelCase : Union[str, Any] = list(dataset_paths.absolute().glob("**/*.py")) for dataset in dataset_files: if self._no_print_statements(str(_SCREAMING_SNAKE_CASE)): raise AssertionError(F"""print statement found in {dataset}. Use datasets.logger/logging instead.""")
269
1
from __future__ import annotations from math import pow, sqrt def _UpperCamelCase ( UpperCamelCase_ : float , UpperCamelCase_ : float , UpperCamelCase_ : float ) -> dict[str, float]: """simple docstring""" if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if resistance == 0: return {"resistance": sqrt(pow(lowercase__ , 2 ) - pow(lowercase__ , 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(lowercase__ , 2 ) - pow(lowercase__ , 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(lowercase__ , 2 ) + pow(lowercase__ , 2 ) )} else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
351
from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup __snake_case : Any = """https://www.indeed.co.in/jobs?q=mobile+app+development&l=""" def _UpperCamelCase ( UpperCamelCase_ : str = "mumbai" ) -> Generator[tuple[str, str], None, None]: """simple docstring""" lowerCAmelCase__ = 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__ = job.find('a' , attrs={'data-tn-element': 'jobTitle'} ).text.strip() lowerCAmelCase__ = 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]}')
122
0
from __future__ import annotations class _UpperCamelCase : '''simple docstring''' def __init__( self : Optional[Any] , a : int = 0 ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = key def __UpperCamelCase ( self : Optional[int] , a : str , a : int ) -> list[str]: """simple docstring""" assert isinstance(a , a ) and isinstance(a , a ) SCREAMING_SNAKE_CASE : Optional[int] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(a ) ^ key ) for ch in content] def __UpperCamelCase ( self : List[Any] , a : str , a : int ) -> list[str]: """simple docstring""" assert isinstance(a , a ) and isinstance(a , a ) SCREAMING_SNAKE_CASE : Optional[int] = key or self.__key or 1 # make sure key is an appropriate size key %= 255 return [chr(ord(a ) ^ key ) for ch in content] def __UpperCamelCase ( self : Optional[Any] , a : str , a : int = 0 ) -> str: """simple docstring""" assert isinstance(a , a ) and isinstance(a , a ) SCREAMING_SNAKE_CASE : Dict = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE : Optional[Any] = "" for ch in content: ans += chr(ord(a ) ^ key ) return ans def __UpperCamelCase ( self : int , a : str , a : int = 0 ) -> str: """simple docstring""" assert isinstance(a , a ) and isinstance(a , a ) SCREAMING_SNAKE_CASE : str = key or self.__key or 1 # make sure key can be any size while key > 255: key -= 255 # This will be returned SCREAMING_SNAKE_CASE : int = "" for ch in content: ans += chr(ord(a ) ^ key ) return ans def __UpperCamelCase ( self : str , a : str , a : int = 0 ) -> bool: """simple docstring""" assert isinstance(a , a ) and isinstance(a , a ) try: with open(a ) as fin, open("encrypt.out" , "w+" ) as fout: # actual encrypt-process for line in fin: fout.write(self.encrypt_string(a , a ) ) except OSError: return False return True def __UpperCamelCase ( self : Optional[int] , a : str , a : int ) -> bool: """simple docstring""" assert isinstance(a , a ) and isinstance(a , a ) try: with open(a ) as fin, open("decrypt.out" , "w+" ) as fout: # actual encrypt-process for line in fin: fout.write(self.decrypt_string(a , a ) ) except OSError: return False return True # Tests # crypt = XORCipher() # key = 67 # # test encrypt # print(crypt.encrypt("hallo welt",key)) # # test decrypt # print(crypt.decrypt(crypt.encrypt("hallo welt",key), key)) # # test encrypt_string # print(crypt.encrypt_string("hallo welt",key)) # # test decrypt_string # print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key)) # if (crypt.encrypt_file("test.txt",key)): # print("encrypt successful") # else: # print("encrypt unsuccessful") # if (crypt.decrypt_file("encrypt.out",key)): # print("decrypt successful") # else: # print("decrypt unsuccessful")
76
'''simple docstring''' def __UpperCAmelCase ( A : int ) -> list: # bit count represents no. of bits in the gray code if bit_count < 0: raise ValueError('''The given input must be positive''' ) # get the generated string sequence UpperCAmelCase_ : int = gray_code_sequence_string(A ) # # convert them to integers for i in range(len(A ) ): UpperCAmelCase_ : List[str] = int(sequence[i] , 2 ) return sequence def __UpperCAmelCase ( A : int ) -> list: # The approach is a recursive one # Base case achieved when either n = 0 or n=1 if bit_count == 0: return ["0"] if bit_count == 1: return ["0", "1"] UpperCAmelCase_ : Tuple = 1 << bit_count # defines the length of the sequence # 1<< n is equivalent to 2^n # recursive answer will generate answer for n-1 bits UpperCAmelCase_ : List[str] = gray_code_sequence_string(bit_count - 1 ) UpperCAmelCase_ : int = [] # append 0 to first half of the smaller sequence generated for i in range(seq_len // 2 ): UpperCAmelCase_ : Union[str, Any] = '''0''' + smaller_sequence[i] sequence.append(A ) # append 1 to second half ... start from the end of the list for i in reversed(range(seq_len // 2 ) ): UpperCAmelCase_ : Dict = '''1''' + smaller_sequence[i] sequence.append(A ) return sequence if __name__ == "__main__": import doctest doctest.testmod()
304
0
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case__ ( __SCREAMING_SNAKE_CASE ): """simple docstring""" def __init__( self : Dict , UpperCamelCase__ : VQModel , UpperCamelCase__ : UNetaDModel , UpperCamelCase__ : DDIMScheduler ) -> str: """simple docstring""" super().__init__() self.register_modules(vqvae=UpperCamelCase__ , unet=UpperCamelCase__ , scheduler=UpperCamelCase__ ) @torch.no_grad() def __call__( self : Tuple , UpperCamelCase__ : int = 1 , UpperCamelCase__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , UpperCamelCase__ : float = 0.0 , UpperCamelCase__ : int = 50 , UpperCamelCase__ : Optional[str] = "pil" , UpperCamelCase__ : bool = True , **UpperCamelCase__ : Union[str, Any] , ) -> Union[Tuple, ImagePipelineOutput]: """simple docstring""" snake_case : Optional[Any] = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=UpperCamelCase__ , ) snake_case : List[Any] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler snake_case : Optional[Any] = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(UpperCamelCase__ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature snake_case : str = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) snake_case : Optional[int] = {} if accepts_eta: snake_case : Optional[int] = eta for t in self.progress_bar(self.scheduler.timesteps ): snake_case : Dict = self.scheduler.scale_model_input(UpperCamelCase__ , UpperCamelCase__ ) # predict the noise residual snake_case : Union[str, Any] = self.unet(UpperCamelCase__ , UpperCamelCase__ ).sample # compute the previous noisy sample x_t -> x_t-1 snake_case : Optional[int] = self.scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample # decode the image latents with the VAE snake_case : Optional[Any] = self.vqvae.decode(UpperCamelCase__ ).sample snake_case : Union[str, Any] = (image / 2 + 0.5).clamp(0 , 1 ) snake_case : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": snake_case : Optional[int] = self.numpy_to_pil(UpperCamelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=UpperCamelCase__ )
352
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS enable_full_determinism() class snake_case__ ( unittest.TestCase ): """simple docstring""" lowerCamelCase = StableDiffusionLDMaDPipeline lowerCamelCase = TEXT_TO_IMAGE_PARAMS lowerCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS lowerCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS def lowerCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) snake_case : str = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) snake_case : Dict = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=UpperCamelCase__ , set_alpha_to_one=UpperCamelCase__ , ) torch.manual_seed(0 ) snake_case : int = AutoencoderKL( block_out_channels=[32, 64] , in_channels=6 , out_channels=6 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) snake_case : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) snake_case : int = CLIPTextModel(UpperCamelCase__ ) snake_case : Tuple = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) snake_case : str = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def lowerCAmelCase ( self : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str=0 ) -> Optional[int]: """simple docstring""" if str(UpperCamelCase__ ).startswith('''mps''' ): snake_case : Optional[int] = torch.manual_seed(UpperCamelCase__ ) else: snake_case : Optional[int] = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) snake_case : Tuple = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def lowerCAmelCase ( self : Any ) -> str: """simple docstring""" snake_case : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case : List[Any] = self.get_dummy_components() snake_case : str = StableDiffusionLDMaDPipeline(**UpperCamelCase__ ) snake_case : Union[str, Any] = ldmad_pipe.to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : List[str] = self.get_dummy_inputs(UpperCamelCase__ ) snake_case : Tuple = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : int = output.rgb, output.depth snake_case : str = rgb[0, -3:, -3:, -1] snake_case : Union[str, Any] = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) snake_case : int = np.array( [0.37_338_176, 0.70_247, 0.74_203_193, 0.51_643_604, 0.58_256_793, 0.60_932_136, 0.4_181_095, 0.48_355_877, 0.46_535_262] ) snake_case : str = np.array([103.46_727, 85.812_004, 87.849_236] ) assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1e-2 assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1e-2 def lowerCAmelCase ( self : Dict ) -> int: """simple docstring""" snake_case : int = self.get_dummy_components() snake_case : Any = StableDiffusionLDMaDPipeline(**UpperCamelCase__ ) snake_case : Optional[Any] = ldmad_pipe.to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : int = self.get_dummy_inputs(UpperCamelCase__ ) snake_case : str = 3 * [inputs['''prompt''']] # forward snake_case : Union[str, Any] = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : Union[str, Any] = output.rgb, output.depth snake_case : Tuple = rgb_slice_a[0, -3:, -3:, -1] snake_case : List[str] = depth_slice_a[0, -3:, -1] snake_case : int = self.get_dummy_inputs(UpperCamelCase__ ) snake_case : Optional[int] = 3 * [inputs.pop('''prompt''' )] snake_case : Dict = ldmad_pipe.tokenizer( UpperCamelCase__ , padding='''max_length''' , max_length=ldmad_pipe.tokenizer.model_max_length , truncation=UpperCamelCase__ , return_tensors='''pt''' , ) snake_case : Optional[Any] = text_inputs['''input_ids'''].to(UpperCamelCase__ ) snake_case : Any = ldmad_pipe.text_encoder(UpperCamelCase__ )[0] snake_case : Tuple = prompt_embeds # forward snake_case : List[Any] = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : Dict = output.rgb, output.depth snake_case : Any = rgb_slice_a[0, -3:, -3:, -1] snake_case : Dict = depth_slice_a[0, -3:, -1] assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1e-4 assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1e-4 def lowerCAmelCase ( self : str ) -> List[Any]: """simple docstring""" snake_case : str = '''cpu''' # ensure determinism for the device-dependent torch.Generator snake_case : Dict = self.get_dummy_components() snake_case : List[str] = PNDMScheduler(skip_prk_steps=UpperCamelCase__ ) snake_case : Optional[Any] = StableDiffusionLDMaDPipeline(**UpperCamelCase__ ) snake_case : Dict = ldmad_pipe.to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : Dict = self.get_dummy_inputs(UpperCamelCase__ ) snake_case : str = '''french fries''' snake_case : List[str] = ldmad_pipe(**UpperCamelCase__ , negative_prompt=UpperCamelCase__ ) snake_case ,snake_case : Union[str, Any] = output.rgb, output.depth snake_case : Union[str, Any] = rgb[0, -3:, -3:, -1] snake_case : int = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) snake_case : Dict = np.array( [0.37_044, 0.71_811_503, 0.7_223_251, 0.48_603_675, 0.5_638_391, 0.6_364_948, 0.42_833_704, 0.4_901_315, 0.47_926_217] ) snake_case : Any = np.array([107.84_738, 84.62_802, 89.962_135] ) assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1e-2 assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1e-2 @slow @require_torch_gpu class snake_case__ ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Optional[int] ) -> List[str]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : Union[str, Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any]="cpu" , UpperCamelCase__ : Optional[int]=torch.floataa , UpperCamelCase__ : Union[str, Any]=0 ) -> Any: """simple docstring""" snake_case : Any = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) snake_case : Optional[Any] = np.random.RandomState(UpperCamelCase__ ).standard_normal((1, 4, 64, 64) ) snake_case : Any = torch.from_numpy(UpperCamelCase__ ).to(device=UpperCamelCase__ , dtype=UpperCamelCase__ ) snake_case : List[Any] = { '''prompt''': '''a photograph of an astronaut riding a horse''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" snake_case : Dict = StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d''' ) snake_case : Optional[Any] = ldmad_pipe.to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : Any = self.get_inputs(UpperCamelCase__ ) snake_case : str = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : List[Any] = output.rgb, output.depth snake_case : Optional[Any] = rgb[0, -3:, -3:, -1].flatten() snake_case : Tuple = rgb[0, -3:, -1].flatten() assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512) snake_case : Optional[Any] = np.array( [0.53_805_465, 0.56_707_305, 0.5_486_515, 0.57_012_236, 0.5_814_511, 0.56_253_487, 0.54_843_014, 0.55_092_263, 0.6_459_706] ) snake_case : str = np.array( [0.9_263_781, 0.6_678_672, 0.5_486_515, 0.92_202_145, 0.67_831_135, 0.56_253_487, 0.9_241_694, 0.7_551_478, 0.6_459_706] ) assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3e-3 assert np.abs(depth_slice - expected_slice_depth ).max() < 3e-3 @nightly @require_torch_gpu class snake_case__ ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : Optional[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : Any="cpu" , UpperCamelCase__ : Optional[int]=torch.floataa , UpperCamelCase__ : Optional[int]=0 ) -> str: """simple docstring""" snake_case : Dict = torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ ) snake_case : Optional[Any] = np.random.RandomState(UpperCamelCase__ ).standard_normal((1, 4, 64, 64) ) snake_case : int = torch.from_numpy(UpperCamelCase__ ).to(device=UpperCamelCase__ , dtype=UpperCamelCase__ ) snake_case : List[str] = { '''prompt''': '''a photograph of an astronaut riding a horse''', '''latents''': latents, '''generator''': generator, '''num_inference_steps''': 50, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def lowerCAmelCase ( self : Optional[Any] ) -> Tuple: """simple docstring""" snake_case : Optional[Any] = StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d''' ).to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : Dict = self.get_inputs(UpperCamelCase__ ) snake_case : str = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : Union[str, Any] = output.rgb, output.depth snake_case : Union[str, Any] = 0.495_586 snake_case : Tuple = 0.33_795_515 snake_case : Dict = 112.48_518 snake_case : Optional[int] = 98.489_746 assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3 assert np.abs(expected_depth_std - depth.std() ) < 1e-3 def lowerCAmelCase ( self : Dict ) -> Dict: """simple docstring""" snake_case : Optional[int] = StableDiffusionLDMaDPipeline.from_pretrained('''Intel/ldm3d-4c''' ).to(UpperCamelCase__ ) ldmad_pipe.set_progress_bar_config(disable=UpperCamelCase__ ) snake_case : int = self.get_inputs(UpperCamelCase__ ) snake_case : List[Any] = ldmad_pipe(**UpperCamelCase__ ) snake_case ,snake_case : Union[str, Any] = output.rgb, output.depth snake_case : Tuple = 0.4_194_127 snake_case : Optional[Any] = 0.35_375_586 snake_case : Any = 0.5_638_502 snake_case : int = 0.34_686_103 assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512, 1) assert np.abs(expected_rgb_mean - rgb.mean() ) < 1e-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1e-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1e-3 assert np.abs(expected_depth_std - depth.std() ) < 1e-3
83
0
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = OrderedDict( [ ('''align''', '''EfficientNetImageProcessor'''), ('''beit''', '''BeitImageProcessor'''), ('''bit''', '''BitImageProcessor'''), ('''blip''', '''BlipImageProcessor'''), ('''blip-2''', '''BlipImageProcessor'''), ('''bridgetower''', '''BridgeTowerImageProcessor'''), ('''chinese_clip''', '''ChineseCLIPImageProcessor'''), ('''clip''', '''CLIPImageProcessor'''), ('''clipseg''', '''ViTImageProcessor'''), ('''conditional_detr''', '''ConditionalDetrImageProcessor'''), ('''convnext''', '''ConvNextImageProcessor'''), ('''convnextv2''', '''ConvNextImageProcessor'''), ('''cvt''', '''ConvNextImageProcessor'''), ('''data2vec-vision''', '''BeitImageProcessor'''), ('''deformable_detr''', '''DeformableDetrImageProcessor'''), ('''deit''', '''DeiTImageProcessor'''), ('''deta''', '''DetaImageProcessor'''), ('''detr''', '''DetrImageProcessor'''), ('''dinat''', '''ViTImageProcessor'''), ('''donut-swin''', '''DonutImageProcessor'''), ('''dpt''', '''DPTImageProcessor'''), ('''efficientformer''', '''EfficientFormerImageProcessor'''), ('''efficientnet''', '''EfficientNetImageProcessor'''), ('''flava''', '''FlavaImageProcessor'''), ('''focalnet''', '''BitImageProcessor'''), ('''git''', '''CLIPImageProcessor'''), ('''glpn''', '''GLPNImageProcessor'''), ('''groupvit''', '''CLIPImageProcessor'''), ('''imagegpt''', '''ImageGPTImageProcessor'''), ('''instructblip''', '''BlipImageProcessor'''), ('''layoutlmv2''', '''LayoutLMv2ImageProcessor'''), ('''layoutlmv3''', '''LayoutLMv3ImageProcessor'''), ('''levit''', '''LevitImageProcessor'''), ('''mask2former''', '''Mask2FormerImageProcessor'''), ('''maskformer''', '''MaskFormerImageProcessor'''), ('''mgp-str''', '''ViTImageProcessor'''), ('''mobilenet_v1''', '''MobileNetV1ImageProcessor'''), ('''mobilenet_v2''', '''MobileNetV2ImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevitv2''', '''MobileViTImageProcessor'''), ('''nat''', '''ViTImageProcessor'''), ('''oneformer''', '''OneFormerImageProcessor'''), ('''owlvit''', '''OwlViTImageProcessor'''), ('''perceiver''', '''PerceiverImageProcessor'''), ('''pix2struct''', '''Pix2StructImageProcessor'''), ('''poolformer''', '''PoolFormerImageProcessor'''), ('''regnet''', '''ConvNextImageProcessor'''), ('''resnet''', '''ConvNextImageProcessor'''), ('''sam''', '''SamImageProcessor'''), ('''segformer''', '''SegformerImageProcessor'''), ('''swiftformer''', '''ViTImageProcessor'''), ('''swin''', '''ViTImageProcessor'''), ('''swin2sr''', '''Swin2SRImageProcessor'''), ('''swinv2''', '''ViTImageProcessor'''), ('''table-transformer''', '''DetrImageProcessor'''), ('''timesformer''', '''VideoMAEImageProcessor'''), ('''tvlt''', '''TvltImageProcessor'''), ('''upernet''', '''SegformerImageProcessor'''), ('''van''', '''ConvNextImageProcessor'''), ('''videomae''', '''VideoMAEImageProcessor'''), ('''vilt''', '''ViltImageProcessor'''), ('''vit''', '''ViTImageProcessor'''), ('''vit_hybrid''', '''ViTHybridImageProcessor'''), ('''vit_mae''', '''ViTImageProcessor'''), ('''vit_msn''', '''ViTImageProcessor'''), ('''xclip''', '''CLIPImageProcessor'''), ('''yolos''', '''YolosImageProcessor'''), ] ) lowerCAmelCase__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def a__ ( SCREAMING_SNAKE_CASE : str ): '''simple docstring''' for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: lowerCAmelCase : Optional[int] = model_type_to_module_name(SCREAMING_SNAKE_CASE ) lowerCAmelCase : str = importlib.import_module(f""".{module_name}""" , "transformers.models" ) try: return getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(SCREAMING_SNAKE_CASE , "__name__" , SCREAMING_SNAKE_CASE ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. lowerCAmelCase : Optional[int] = importlib.import_module("transformers" ) if hasattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ): return getattr(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return None def a__ ( SCREAMING_SNAKE_CASE : Union[str, os.PathLike] , SCREAMING_SNAKE_CASE : Optional[Union[str, os.PathLike]] = None , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : bool = False , SCREAMING_SNAKE_CASE : Optional[Dict[str, str]] = None , SCREAMING_SNAKE_CASE : Optional[Union[bool, str]] = None , SCREAMING_SNAKE_CASE : Optional[str] = None , SCREAMING_SNAKE_CASE : bool = False , **SCREAMING_SNAKE_CASE : Union[str, Any] , ): '''simple docstring''' lowerCAmelCase : Dict = get_file_from_repo( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , cache_dir=SCREAMING_SNAKE_CASE , force_download=SCREAMING_SNAKE_CASE , resume_download=SCREAMING_SNAKE_CASE , proxies=SCREAMING_SNAKE_CASE , use_auth_token=SCREAMING_SNAKE_CASE , revision=SCREAMING_SNAKE_CASE , local_files_only=SCREAMING_SNAKE_CASE , ) if resolved_config_file is None: logger.info( "Could not locate the image processor configuration file, will try to use the model config instead." ) return {} with open(SCREAMING_SNAKE_CASE , encoding="utf-8" ) as reader: return json.load(SCREAMING_SNAKE_CASE ) class SCREAMING_SNAKE_CASE__ : """simple docstring""" def __init__( self ): """simple docstring""" raise EnvironmentError( "AutoImageProcessor is designed to be instantiated " "using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method." ) @classmethod @replace_list_option_in_docstrings(snake_case__ ) def lowercase__ ( cls , snake_case__ , **snake_case__ ): """simple docstring""" lowerCAmelCase : Any = kwargs.pop("config" , snake_case__ ) lowerCAmelCase : List[str] = kwargs.pop("trust_remote_code" , snake_case__ ) lowerCAmelCase : List[Any] = True lowerCAmelCase , lowerCAmelCase : Tuple = ImageProcessingMixin.get_image_processor_dict(snake_case__ , **snake_case__ ) lowerCAmelCase : int = config_dict.get("image_processor_type" , snake_case__ ) lowerCAmelCase : str = None if "AutoImageProcessor" in config_dict.get("auto_map" , {} ): lowerCAmelCase : Dict = config_dict["auto_map"]["AutoImageProcessor"] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: lowerCAmelCase : str = config_dict.pop("feature_extractor_type" , snake_case__ ) if feature_extractor_class is not None: logger.warning( "Could not find image processor class in the image processor config or the model config. Loading" " based on pattern matching with the model's feature extractor configuration." ) lowerCAmelCase : List[str] = feature_extractor_class.replace("FeatureExtractor" , "ImageProcessor" ) if "AutoFeatureExtractor" in config_dict.get("auto_map" , {} ): lowerCAmelCase : List[Any] = config_dict["auto_map"]["AutoFeatureExtractor"] lowerCAmelCase : List[Any] = feature_extractor_auto_map.replace("FeatureExtractor" , "ImageProcessor" ) logger.warning( "Could not find image processor auto map in the image processor config or the model config." " Loading based on pattern matching with the model's feature extractor configuration." ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(snake_case__ , snake_case__ ): lowerCAmelCase : Dict = AutoConfig.from_pretrained(snake_case__ , **snake_case__ ) # It could be in `config.image_processor_type`` lowerCAmelCase : str = getattr(snake_case__ , "image_processor_type" , snake_case__ ) if hasattr(snake_case__ , "auto_map" ) and "AutoImageProcessor" in config.auto_map: lowerCAmelCase : Union[str, Any] = config.auto_map["AutoImageProcessor"] if image_processor_class is not None: lowerCAmelCase : Union[str, Any] = image_processor_class_from_name(snake_case__ ) lowerCAmelCase : List[Any] = image_processor_auto_map is not None lowerCAmelCase : int = image_processor_class is not None or type(snake_case__ ) in IMAGE_PROCESSOR_MAPPING lowerCAmelCase : int = resolve_trust_remote_code( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) if has_remote_code and trust_remote_code: lowerCAmelCase : List[Any] = get_class_from_dynamic_module( snake_case__ , snake_case__ , **snake_case__ ) lowerCAmelCase : str = kwargs.pop("code_revision" , snake_case__ ) if os.path.isdir(snake_case__ ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(snake_case__ , **snake_case__ ) elif image_processor_class is not None: return image_processor_class.from_dict(snake_case__ , **snake_case__ ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(snake_case__ ) in IMAGE_PROCESSOR_MAPPING: lowerCAmelCase : Optional[Any] = IMAGE_PROCESSOR_MAPPING[type(snake_case__ )] return image_processor_class.from_dict(snake_case__ , **snake_case__ ) raise ValueError( f"""Unrecognized image processor in {pretrained_model_name_or_path}. Should have a """ f"""`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following """ f"""`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def lowercase__ ( snake_case__ , snake_case__ ): """simple docstring""" IMAGE_PROCESSOR_MAPPING.register(snake_case__ , snake_case__ )
108
"""simple docstring""" from __future__ import annotations def lowercase (SCREAMING_SNAKE_CASE_ : str ) -> list[int]: return [ord(SCREAMING_SNAKE_CASE_ ) - 96 for elem in plain] def lowercase (SCREAMING_SNAKE_CASE_ : list[int] ) -> str: return "".join(chr(elem + 96 ) for elem in encoded ) def lowercase () -> None: SCREAMING_SNAKE_CASE = encode(input('-> ' ).strip().lower() ) print('Encoded: ' , SCREAMING_SNAKE_CASE_ ) print('Decoded:' , decode(SCREAMING_SNAKE_CASE_ ) ) if __name__ == "__main__": main()
113
0
"""simple docstring""" from ...processing_utils import ProcessorMixin class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = ["image_processor", "feature_extractor"] __UpperCamelCase = "TvltImageProcessor" __UpperCamelCase = "TvltFeatureExtractor" def __init__( self : int , lowercase_ : Optional[Any] , lowercase_ : Optional[Any]): '''simple docstring''' super().__init__(image_processor=lowercase_ , feature_extractor=lowercase_) SCREAMING_SNAKE_CASE_ : Union[str, Any] = image_processor SCREAMING_SNAKE_CASE_ : Optional[Any] = feature_extractor def __call__( self : Any , lowercase_ : str=None , lowercase_ : Optional[Any]=None , lowercase_ : Optional[Any]=None , lowercase_ : str=None , lowercase_ : int=False , lowercase_ : Union[str, Any]=False , *lowercase_ : List[Any] , **lowercase_ : List[str] , ): '''simple docstring''' if images is None and audio is None: raise ValueError('''You need to specify either an `images` or `audio` input to process.''') SCREAMING_SNAKE_CASE_ : Any = None if images is not None: SCREAMING_SNAKE_CASE_ : Tuple = self.image_processor(lowercase_ , mask_pixel=lowercase_ , *lowercase_ , **lowercase_) if images_mixed is not None: SCREAMING_SNAKE_CASE_ : Optional[int] = self.image_processor(lowercase_ , is_mixed=lowercase_ , *lowercase_ , **lowercase_) if audio is not None: SCREAMING_SNAKE_CASE_ : Any = self.feature_extractor( lowercase_ , *lowercase_ , sampling_rate=lowercase_ , mask_audio=lowercase_ , **lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = {} if audio is not None: output_dict.update(lowercase_) if images is not None: output_dict.update(lowercase_) if images_mixed_dict is not None: output_dict.update(lowercase_) return output_dict @property def _SCREAMING_SNAKE_CASE ( self : List[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = self.image_processor.model_input_names SCREAMING_SNAKE_CASE_ : Dict = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names))
318
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) UpperCAmelCase_ : List[str] = { """RWKV/rwkv-4-169m-pile""": """https://huggingface.co/RWKV/rwkv-4-169m-pile/resolve/main/config.json""", """RWKV/rwkv-4-430m-pile""": """https://huggingface.co/RWKV/rwkv-4-430m-pile/resolve/main/config.json""", """RWKV/rwkv-4-1b5-pile""": """https://huggingface.co/RWKV/rwkv-4-1b5-pile/resolve/main/config.json""", """RWKV/rwkv-4-3b-pile""": """https://huggingface.co/RWKV/rwkv-4-3b-pile/resolve/main/config.json""", """RWKV/rwkv-4-7b-pile""": """https://huggingface.co/RWKV/rwkv-4-7b-pile/resolve/main/config.json""", """RWKV/rwkv-4-14b-pile""": """https://huggingface.co/RWKV/rwkv-4-14b-pile/resolve/main/config.json""", """RWKV/rwkv-raven-1b5""": """https://huggingface.co/RWKV/rwkv-raven-1b5/resolve/main/config.json""", """RWKV/rwkv-raven-3b""": """https://huggingface.co/RWKV/rwkv-raven-3b/resolve/main/config.json""", """RWKV/rwkv-raven-7b""": """https://huggingface.co/RWKV/rwkv-raven-7b/resolve/main/config.json""", """RWKV/rwkv-raven-14b""": """https://huggingface.co/RWKV/rwkv-raven-14b/resolve/main/config.json""", } class lowerCAmelCase__ ( UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "rwkv" __UpperCamelCase = {"max_position_embeddings": "context_length"} def __init__( self : Union[str, Any] , lowercase_ : Any=50277 , lowercase_ : str=1024 , lowercase_ : List[str]=4096 , lowercase_ : Optional[Any]=32 , lowercase_ : Any=None , lowercase_ : Any=None , lowercase_ : List[Any]=1e-5 , lowercase_ : Union[str, Any]=0 , lowercase_ : Union[str, Any]=0 , lowercase_ : int=6 , lowercase_ : Tuple=False , lowercase_ : Any=True , **lowercase_ : Any , ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE_ : Any = context_length SCREAMING_SNAKE_CASE_ : int = hidden_size SCREAMING_SNAKE_CASE_ : int = num_hidden_layers SCREAMING_SNAKE_CASE_ : List[str] = attention_hidden_size if attention_hidden_size is not None else hidden_size SCREAMING_SNAKE_CASE_ : int = intermediate_size if intermediate_size is not None else 4 * hidden_size SCREAMING_SNAKE_CASE_ : int = layer_norm_epsilon SCREAMING_SNAKE_CASE_ : Optional[int] = rescale_every SCREAMING_SNAKE_CASE_ : Dict = use_cache SCREAMING_SNAKE_CASE_ : Dict = bos_token_id SCREAMING_SNAKE_CASE_ : Any = eos_token_id super().__init__( tie_word_embeddings=lowercase_ , bos_token_id=lowercase_ , eos_token_id=lowercase_ , **lowercase_)
318
1
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## UpperCamelCase = 16 UpperCamelCase = 32 def lowercase_ ( _lowerCamelCase : Accelerator , _lowerCamelCase : int = 16): lowercase__ : List[Any] = AutoTokenizer.from_pretrained("bert-base-cased") lowercase__ : Optional[int] = load_dataset("glue" , "mrpc") def tokenize_function(_lowerCamelCase : Dict): # max_length=None => use the model max length (it's actually the default) lowercase__ : Tuple = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=_lowerCamelCase , max_length=_lowerCamelCase) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): lowercase__ : Optional[int] = datasets.map( _lowerCamelCase , batched=_lowerCamelCase , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowercase__ : int = tokenized_datasets.rename_column("label" , "labels") def collate_fn(_lowerCamelCase : int): # On TPU it's best to pad everything to the same length or training will be very slow. lowercase__ : str = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": lowercase__ : List[Any] = 16 elif accelerator.mixed_precision != "no": lowercase__ : Any = 8 else: lowercase__ : Tuple = None return tokenizer.pad( _lowerCamelCase , padding="longest" , max_length=_lowerCamelCase , pad_to_multiple_of=_lowerCamelCase , return_tensors="pt" , ) # Instantiate dataloaders. lowercase__ : Dict = DataLoader( tokenized_datasets["train"] , shuffle=_lowerCamelCase , collate_fn=_lowerCamelCase , batch_size=_lowerCamelCase) lowercase__ : Optional[int] = DataLoader( tokenized_datasets["validation"] , shuffle=_lowerCamelCase , collate_fn=_lowerCamelCase , batch_size=_lowerCamelCase) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders UpperCamelCase = mocked_dataloaders # noqa: F811 def lowercase_ ( _lowerCamelCase : Dict , _lowerCamelCase : Optional[Any]): # For testing only if os.environ.get("TESTING_MOCKED_DATALOADERS" , _lowerCamelCase) == "1": lowercase__ : int = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: lowercase__ : int = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="all" , project_dir=args.project_dir) else: lowercase__ : List[Any] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowercase__ : Any = config["lr"] lowercase__ : List[str] = int(config["num_epochs"]) lowercase__ : List[str] = int(config["seed"]) lowercase__ : int = int(config["batch_size"]) set_seed(_lowerCamelCase) lowercase__ , lowercase__ : Optional[Any] = get_dataloaders(_lowerCamelCase , _lowerCamelCase) lowercase__ : List[str] = evaluate.load("glue" , "mrpc") # If the batch size is too big we use gradient accumulation lowercase__ : Tuple = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: lowercase__ : Optional[int] = batch_size // MAX_GPU_BATCH_SIZE lowercase__ : Union[str, Any] = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowercase__ : Tuple = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=_lowerCamelCase) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). lowercase__ : Any = model.to(accelerator.device) # Instantiate optimizer lowercase__ : List[str] = AdamW(params=model.parameters() , lr=_lowerCamelCase) # Instantiate scheduler lowercase__ : Optional[int] = get_linear_schedule_with_warmup( optimizer=_lowerCamelCase , num_warmup_steps=100 , num_training_steps=(len(_lowerCamelCase) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ : Optional[Any] = accelerator.prepare( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: lowercase__ : Dict = os.path.split(_lowerCamelCase)[-1].split(".")[0] accelerator.init_trackers(_lowerCamelCase , _lowerCamelCase) # Now we train the model for epoch in range(_lowerCamelCase): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: lowercase__ : Optional[Any] = 0 for step, batch in enumerate(_lowerCamelCase): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device) lowercase__ : Dict = model(**_lowerCamelCase) lowercase__ : Tuple = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() lowercase__ : str = loss / gradient_accumulation_steps accelerator.backward(_lowerCamelCase) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_lowerCamelCase): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device) with torch.no_grad(): lowercase__ : Tuple = model(**_lowerCamelCase) lowercase__ : str = outputs.logits.argmax(dim=-1) lowercase__ , lowercase__ : Tuple = accelerator.gather_for_metrics((predictions, batch["labels"])) metric.add_batch( predictions=_lowerCamelCase , references=_lowerCamelCase , ) lowercase__ : Dict = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , _lowerCamelCase) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { "accuracy": eval_metric["accuracy"], "f1": eval_metric["f1"], "train_loss": total_loss.item() / len(_lowerCamelCase), "epoch": epoch, } , step=_lowerCamelCase , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def lowercase_ ( ): lowercase__ : str = argparse.ArgumentParser(description="Simple example of training script.") parser.add_argument( "--mixed_precision" , type=_lowerCamelCase , default=_lowerCamelCase , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU.") parser.add_argument( "--with_tracking" , action="store_true" , help="Whether to load in all available experiment trackers from the environment and use them for logging." , ) parser.add_argument( "--project_dir" , type=_lowerCamelCase , default="logs" , help="Location on where to store experiment tracking logs` and relevent project information" , ) lowercase__ : int = parser.parse_args() lowercase__ : Tuple = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(_lowerCamelCase , _lowerCamelCase) if __name__ == "__main__": main()
87
"""simple docstring""" from __future__ import annotations class _UpperCAmelCase : def __init__( self : Tuple , _lowercase : str , _lowercase : str ): __UpperCAmelCase , __UpperCAmelCase = text, pattern __UpperCAmelCase , __UpperCAmelCase = len(_lowercase ), len(_lowercase ) def a ( self : Optional[int] , _lowercase : str ): for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def a ( self : int , _lowercase : int ): for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def a ( self : Optional[Any] ): # searches pattern in text and returns index positions __UpperCAmelCase = [] for i in range(self.textLen - self.patLen + 1 ): __UpperCAmelCase = self.mismatch_in_text(_lowercase ) if mismatch_index == -1: positions.append(_lowercase ) else: __UpperCAmelCase = self.match_in_pattern(self.text[mismatch_index] ) __UpperCAmelCase = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions _lowercase : str = 'ABAABA' _lowercase : Tuple = 'AB' _lowercase : Dict = BoyerMooreSearch(text, pattern) _lowercase : Any = bms.bad_character_heuristic() if len(positions) == 0: print('No match found') else: print('Pattern found in following positions: ') print(positions)
332
0
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 snake_case__(unittest.TestCase ): """simple docstring""" @property def snake_case ( self : Any ): torch.manual_seed(0 ) lowercase__ : Tuple = 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 : List[str] ): torch.manual_seed(0 ) lowercase__ : Optional[int] = 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 ) lowercase__ : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) return CLIPTextModel(SCREAMING_SNAKE_CASE ) def snake_case ( self : str ): lowercase__ : Any = self.dummy_uncond_unet lowercase__ : Dict = DDIMScheduler() lowercase__ : Optional[Any] = self.dummy_vq_model lowercase__ : Union[str, Any] = LDMPipeline(unet=SCREAMING_SNAKE_CASE , vqvae=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE ) ldm.to(SCREAMING_SNAKE_CASE ) ldm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) lowercase__ : int = torch.manual_seed(0 ) lowercase__ : Optional[int] = ldm(generator=SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="numpy" ).images lowercase__ : str = torch.manual_seed(0 ) lowercase__ : List[Any] = ldm(generator=SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type="numpy" , return_dict=SCREAMING_SNAKE_CASE )[0] lowercase__ : Any = image[0, -3:, -3:, -1] lowercase__ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowercase__ : List[Any] = np.array([0.8_512, 0.818, 0.6_411, 0.6_808, 0.4_465, 0.5_618, 0.46, 0.6_231, 0.5_172] ) lowercase__ : Optional[Any] = 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 snake_case__(unittest.TestCase ): """simple docstring""" def snake_case ( self : Optional[Any] ): lowercase__ : int = LDMPipeline.from_pretrained("CompVis/ldm-celebahq-256" ) ldm.to(SCREAMING_SNAKE_CASE ) ldm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE ) lowercase__ : Dict = torch.manual_seed(0 ) lowercase__ : Tuple = ldm(generator=SCREAMING_SNAKE_CASE , num_inference_steps=5 , output_type="numpy" ).images lowercase__ : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) lowercase__ : Optional[Any] = np.array([0.4_399, 0.44_975, 0.46_825, 0.474, 0.4_359, 0.4_581, 0.45_095, 0.4_341, 0.4_447] ) lowercase__ : int = 1E-2 if torch_device != "mps" else 3E-2 assert np.abs(image_slice.flatten() - expected_slice ).max() < tolerance
121
from __future__ import annotations from math import pi # Define the Reduced Planck Constant ℏ (H bar), speed of light C, value of # Pi and the function lowerCAmelCase__ = 1.054571817e-34 # unit of ℏ : J * s lowerCAmelCase__ = 3e8 # unit of c : m * s^-1 def __lowerCamelCase ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" if (force, area, distance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if force < 0: raise ValueError("Magnitude of force can not be negative" ) if distance < 0: raise ValueError("Distance can not be negative" ) if area < 0: raise ValueError("Area can not be negative" ) if force == 0: lowercase__ : Optional[Any] = (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / ( 240 * (distance) ** 4 ) return {"force": force} elif area == 0: lowercase__ : str = (240 * force * (distance) ** 4) / ( REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 ) return {"area": area} elif distance == 0: lowercase__ : Tuple = ( (REDUCED_PLANCK_CONSTANT * SPEED_OF_LIGHT * pi**2 * area) / (240 * force) ) ** (1 / 4) return {"distance": distance} raise ValueError("One and only one argument must be 0" ) # Run doctest if __name__ == "__main__": import doctest doctest.testmod()
121
1
def a ( lowerCamelCase_ = 400_0000 ): '''simple docstring''' lowercase__ = [0, 1] lowercase__ = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 lowercase__ = 0 for j in range(len(SCREAMING_SNAKE_CASE_ ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(F"{solution() = }")
207
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { '''google/mobilenet_v2_1.4_224''': '''https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json''', '''google/mobilenet_v2_1.0_224''': '''https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json''', '''google/mobilenet_v2_0.75_160''': '''https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json''', '''google/mobilenet_v2_0.35_96''': '''https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json''', # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class UpperCAmelCase_ ( UpperCamelCase ): '''simple docstring''' __A : Dict = "mobilenet_v2" def __init__( self , __A=3 , __A=224 , __A=1.0 , __A=8 , __A=8 , __A=6 , __A=32 , __A=True , __A=True , __A="relu6" , __A=True , __A=0.8 , __A=0.02 , __A=0.001 , __A=255 , **__A , ): """simple docstring""" super().__init__(**__A ) if depth_multiplier <= 0: raise ValueError("depth_multiplier must be greater than zero." ) lowerCamelCase : str = num_channels lowerCamelCase : Any = image_size lowerCamelCase : Union[str, Any] = depth_multiplier lowerCamelCase : Tuple = depth_divisible_by lowerCamelCase : Dict = min_depth lowerCamelCase : Dict = expand_ratio lowerCamelCase : Optional[Any] = output_stride lowerCamelCase : int = first_layer_is_expansion lowerCamelCase : Union[str, Any] = finegrained_output lowerCamelCase : Optional[Any] = hidden_act lowerCamelCase : Optional[Any] = tf_padding lowerCamelCase : Optional[Any] = classifier_dropout_prob lowerCamelCase : Dict = initializer_range lowerCamelCase : str = layer_norm_eps lowerCamelCase : Optional[Any] = semantic_loss_ignore_index class UpperCAmelCase_ ( UpperCamelCase ): '''simple docstring''' __A : Union[str, Any] = version.parse("1.11" ) @property def _snake_case ( self ): """simple docstring""" return OrderedDict([("pixel_values", {0: "batch"})] ) @property def _snake_case ( self ): """simple docstring""" if self.task == "image-classification": return OrderedDict([("logits", {0: "batch"})] ) else: return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})] ) @property def _snake_case ( self ): """simple docstring""" return 1e-4
283
0
import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = { 'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json', 'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json', } class lowerCAmelCase_ ( _lowerCAmelCase ): UpperCAmelCase__ : Any = "encodec" def __init__( self, SCREAMING_SNAKE_CASE_=[1.5, 3.0, 6.0, 12.0, 24.0], SCREAMING_SNAKE_CASE_=2_4000, SCREAMING_SNAKE_CASE_=1, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=128, SCREAMING_SNAKE_CASE_=32, SCREAMING_SNAKE_CASE_=1, SCREAMING_SNAKE_CASE_=[8, 5, 4, 2], SCREAMING_SNAKE_CASE_="weight_norm", SCREAMING_SNAKE_CASE_=7, SCREAMING_SNAKE_CASE_=7, SCREAMING_SNAKE_CASE_=3, SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_=True, SCREAMING_SNAKE_CASE_="reflect", SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_=2, SCREAMING_SNAKE_CASE_=1.0, SCREAMING_SNAKE_CASE_=1024, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=True, **SCREAMING_SNAKE_CASE_, ) -> Optional[int]: UpperCamelCase : List[Any] = target_bandwidths UpperCamelCase : str = sampling_rate UpperCamelCase : Any = audio_channels UpperCamelCase : List[str] = normalize UpperCamelCase : List[Any] = chunk_length_s UpperCamelCase : List[Any] = overlap UpperCamelCase : Any = hidden_size UpperCamelCase : str = num_filters UpperCamelCase : Any = num_residual_layers UpperCamelCase : int = upsampling_ratios UpperCamelCase : Tuple = norm_type UpperCamelCase : Union[str, Any] = kernel_size UpperCamelCase : str = last_kernel_size UpperCamelCase : Union[str, Any] = residual_kernel_size UpperCamelCase : str = dilation_growth_rate UpperCamelCase : int = use_causal_conv UpperCamelCase : int = pad_mode UpperCamelCase : List[Any] = compress UpperCamelCase : Dict = num_lstm_layers UpperCamelCase : List[Any] = trim_right_ratio UpperCamelCase : List[Any] = codebook_size UpperCamelCase : List[Any] = codebook_dim if codebook_dim is not None else hidden_size UpperCamelCase : Optional[Any] = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( F"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}""" ) super().__init__(**SCREAMING_SNAKE_CASE_ ) @property def snake_case_ ( self ) -> Optional[int]: if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def snake_case_ ( self ) -> Optional[int]: if self.chunk_length_s is None or self.overlap is None: return None else: return max(1, int((1.0 - self.overlap) * self.chunk_length ) ) @property def snake_case_ ( self ) -> int: UpperCamelCase : Optional[int] = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def snake_case_ ( self ) -> int: return int(1000 * self.target_bandwidths[-1] // (self.frame_rate * 10) )
366
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = {'''vocab_file''': '''spiece.model'''} __UpperCAmelCase = { '''vocab_file''': { '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''', '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''', } } __UpperCAmelCase = { '''AI-Sweden/gpt-sw3-126m''': 2_048, '''AI-Sweden/gpt-sw3-350m''': 2_048, '''AI-Sweden/gpt-sw3-1.6b''': 2_048, '''AI-Sweden/gpt-sw3-6.7b''': 2_048, '''AI-Sweden/gpt-sw3-20b''': 2_048, } class lowerCAmelCase_ ( a__ ): UpperCAmelCase__ : Union[str, Any] = VOCAB_FILES_NAMES UpperCAmelCase__ : Any = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase__ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase__ : Optional[int] = ["input_ids", "attention_mask"] def __init__( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=False, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_=None, SCREAMING_SNAKE_CASE_ = None, **SCREAMING_SNAKE_CASE_, ) -> None: UpperCamelCase : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs UpperCamelCase : Dict = kwargs.get('name_or_path' ) if name_or_path is None: logger.warning( 'name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,' ' you are testing the model, this can safely be ignored' ) UpperCamelCase : Tuple = 'None' # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing UpperCamelCase : str = '<|endoftext|>' if eos_token is None else eos_token UpperCamelCase : Tuple = '<unk>' if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: UpperCamelCase : str = unk_token if pad_token is None else pad_token UpperCamelCase : List[str] = eos_token if bos_token is None else bos_token else: UpperCamelCase : List[Any] = '<pad>' if pad_token is None else pad_token UpperCamelCase : Dict = '<s>' if bos_token is None else bos_token super().__init__( do_lower_case=SCREAMING_SNAKE_CASE_, remove_space=SCREAMING_SNAKE_CASE_, keep_accents=SCREAMING_SNAKE_CASE_, bos_token=SCREAMING_SNAKE_CASE_, eos_token=SCREAMING_SNAKE_CASE_, unk_token=SCREAMING_SNAKE_CASE_, pad_token=SCREAMING_SNAKE_CASE_, sp_model_kwargs=self.sp_model_kwargs, **SCREAMING_SNAKE_CASE_, ) UpperCamelCase : List[str] = do_lower_case UpperCamelCase : List[str] = remove_space UpperCamelCase : List[Any] = keep_accents UpperCamelCase : List[str] = vocab_file UpperCamelCase : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE_ ) # Used for whitespace normalization in input texts # fmt : off UpperCamelCase : Dict = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '', '„'} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing UpperCamelCase : List[Any] = re.compile( F"""[{"".join(map(SCREAMING_SNAKE_CASE_, list(range(0, 9 ) ) + list(range(11, 32 ) ) + list(range(127, 160 ) ) + [160, 173, 8203] ) )}]""" ) def __getstate__( self ) -> Tuple: UpperCamelCase : List[Any] = self.__dict__.copy() UpperCamelCase : Optional[int] = None return state def __setstate__( self, SCREAMING_SNAKE_CASE_ ) -> Any: UpperCamelCase : Any = d # for backward compatibility if not hasattr(self, 'sp_model_kwargs' ): UpperCamelCase : Optional[int] = {} UpperCamelCase : int = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def snake_case_ ( self ) -> int: return len(self.sp_model ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase : Dict = self.non_printing_characters_re.sub('', SCREAMING_SNAKE_CASE_ ) # Normalize whitespaces UpperCamelCase : Any = ''.join([char if char not in self.whitespaces else ' ' for char in text] ) # NFC Unicode normalization UpperCamelCase : Dict = unicodedata.normalize('NFC', SCREAMING_SNAKE_CASE_ ) return text def snake_case_ ( self, SCREAMING_SNAKE_CASE_, **SCREAMING_SNAKE_CASE_ ) -> List[str]: UpperCamelCase : Any = self.preprocess_text(SCREAMING_SNAKE_CASE_ ) return self.sp_model.encode(SCREAMING_SNAKE_CASE_, out_type=SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> int: return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> str: return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE_ ) @staticmethod def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> str: return out_string def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> str: UpperCamelCase : Optional[Any] = [] UpperCamelCase : List[Any] = '' UpperCamelCase : str = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE_ ) + token UpperCamelCase : Dict = True UpperCamelCase : Optional[Any] = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : str = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE_ ) return out_string def snake_case_ ( self ) -> Dict[str, int]: UpperCamelCase : Tuple = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = None ) -> Tuple[str]: if not os.path.isdir(SCREAMING_SNAKE_CASE_ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCamelCase : List[str] = os.path.join( SCREAMING_SNAKE_CASE_, (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, SCREAMING_SNAKE_CASE_ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE_, 'wb' ) as fi: UpperCamelCase : Any = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE_ ) return (out_vocab_file,) def snake_case_ ( self, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: if isinstance(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = self.preprocess_text(SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[Any] = self.sp_model.encode(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase : Union[str, Any] = [self.preprocess_text(SCREAMING_SNAKE_CASE_ ) for t in text] UpperCamelCase : Any = self.sp_model.encode(SCREAMING_SNAKE_CASE_ ) if return_tensors is True or return_tensors == "pt": UpperCamelCase : List[Any] = torch.tensor(SCREAMING_SNAKE_CASE_ ) return token_ids def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> str: return self.sp_model.decode(SCREAMING_SNAKE_CASE_ ) def snake_case_ ( self, SCREAMING_SNAKE_CASE_ ) -> List[int]: UpperCamelCase : List[Any] = [F"""User: {text}""" if is_user else F"""Bot: {text}""" for is_user, text in conversation.iter_texts()] UpperCamelCase : Optional[Any] = ( F"""{self.eos_token}{self.bos_token}""" + F"""{self.bos_token}""".join(SCREAMING_SNAKE_CASE_ ) + F"""{self.bos_token}Bot:""" ) return self.encode(text=SCREAMING_SNAKE_CASE_ )
103
0
def UpperCamelCase ( _A = 2000000 ): """simple docstring""" __magic_name__ : Union[str, Any] = [0 for i in range(n + 1 )] __magic_name__ : Optional[int] = 1 __magic_name__ : Dict = 1 for i in range(2, int(n**0.5 ) + 1 ): if primality_list[i] == 0: for j in range(i * i, n + 1, _A ): __magic_name__ : Union[str, Any] = 1 __magic_name__ : Optional[int] = 0 for i in range(_A ): if primality_list[i] == 0: sum_of_primes += i return sum_of_primes if __name__ == "__main__": print(F"""{solution() = }""")
342
import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case__ ( _lowerCAmelCase , unittest.TestCase ): lowercase__ : Optional[Any] = MgpstrTokenizer lowercase__ : int = False lowercase__ : Any = {} lowercase__ : Optional[int] = False def __magic_name__ ( self ) -> Optional[Any]: super().setUp() # fmt: off __magic_name__ : List[str] = ["""[GO]""", """[s]""", """0""", """1""", """2""", """3""", """4""", """5""", """6""", """7""", """8""", """9""", """a""", """b""", """c""", """d""", """e""", """f""", """g""", """h""", """i""", """j""", """k""", """l""", """m""", """n""", """o""", """p""", """q""", """r""", """s""", """t""", """u""", """v""", """w""", """x""", """y""", """z"""] # fmt: on __magic_name__ : List[Any] = dict(zip(lowerCAmelCase__ , range(len(lowerCAmelCase__ ) ) ) ) __magic_name__ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(lowerCAmelCase__ ) + """\n""" ) def __magic_name__ ( self , **lowerCAmelCase__ ) -> Optional[int]: return MgpstrTokenizer.from_pretrained(self.tmpdirname , **lowerCAmelCase__ ) def __magic_name__ ( self , lowerCAmelCase__ ) -> Optional[int]: __magic_name__ : List[str] = """tester""" __magic_name__ : int = """tester""" return input_text, output_text @unittest.skip("""MGP-STR always lower cases letters.""" ) def __magic_name__ ( self ) -> str: pass def __magic_name__ ( self ) -> List[str]: __magic_name__ : List[Any] = self.get_tokenizers(do_lower_case=lowerCAmelCase__ ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): __magic_name__ : Dict = """[SPECIAL_TOKEN]""" tokenizer.add_special_tokens({"""cls_token""": special_token} ) __magic_name__ : List[str] = tokenizer.encode([special_token] , add_special_tokens=lowerCAmelCase__ ) self.assertEqual(len(lowerCAmelCase__ ) , 1 ) __magic_name__ : Tuple = tokenizer.decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ ) self.assertTrue(special_token not in decoded ) def __magic_name__ ( self ) -> Union[str, Any]: __magic_name__ : int = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): __magic_name__ ,__magic_name__ : Optional[Any] = self.get_input_output_texts(lowerCAmelCase__ ) __magic_name__ : List[Any] = tokenizer.tokenize(lowerCAmelCase__ ) __magic_name__ : Any = tokenizer.convert_tokens_to_ids(lowerCAmelCase__ ) __magic_name__ : Union[str, Any] = tokenizer.encode(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ ) self.assertListEqual(lowerCAmelCase__ , lowerCAmelCase__ ) __magic_name__ : List[Any] = tokenizer.convert_ids_to_tokens(lowerCAmelCase__ ) self.assertNotEqual(len(lowerCAmelCase__ ) , 0 ) __magic_name__ : Optional[int] = tokenizer.decode(lowerCAmelCase__ ) self.assertIsInstance(lowerCAmelCase__ , lowerCAmelCase__ ) self.assertEqual(text_a.replace(""" """ , """""" ) , lowerCAmelCase__ ) @unittest.skip("""MGP-STR tokenizer only handles one sequence.""" ) def __magic_name__ ( self ) -> Tuple: pass @unittest.skip("""inputs cannot be pretokenized in MgpstrTokenizer""" ) def __magic_name__ ( self ) -> Optional[Any]: pass
342
1
'''simple docstring''' import contextlib import os import sqlitea import pytest from datasets import Dataset, Features, Value from datasets.io.sql import SqlDatasetReader, SqlDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases, require_sqlalchemy def SCREAMING_SNAKE_CASE__ ( snake_case : Any , snake_case : str ) -> str: """simple docstring""" assert isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @require_sqlalchemy @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def SCREAMING_SNAKE_CASE__ ( snake_case : List[Any] , snake_case : int , snake_case : List[str] , snake_case : Dict ) -> Union[str, Any]: """simple docstring""" a : Optional[Any] = tmp_path / """cache""" a : Tuple = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a : List[Any] = SqlDatasetReader( 'dataset' , 'sqlite:///' + sqlite_path , cache_dir=__SCREAMING_SNAKE_CASE , keep_in_memory=__SCREAMING_SNAKE_CASE ).read() _check_sql_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) @require_sqlalchemy @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def SCREAMING_SNAKE_CASE__ ( snake_case : List[Any] , snake_case : str , snake_case : Any , snake_case : Optional[Any] ) -> List[Any]: """simple docstring""" a : Dict = tmp_path / """cache""" a : Union[str, Any] = {"""col_1""": """string""", """col_2""": """int64""", """col_3""": """float64"""} a : Tuple = features.copy() if features else default_expected_features a : Optional[int] = ( Features({feature: Value(__SCREAMING_SNAKE_CASE ) for feature, dtype in features.items()} ) if features is not None else None ) a : Any = SqlDatasetReader('dataset' , 'sqlite:///' + sqlite_path , features=__SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE ).read() _check_sql_dataset(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) def SCREAMING_SNAKE_CASE__ ( snake_case : List[Any] ) -> Optional[Any]: """simple docstring""" with contextlib.closing(sqlitea.connect(__SCREAMING_SNAKE_CASE ) ) as con: a : List[str] = con.cursor() cur.execute('SELECT * FROM dataset' ) for row in cur: yield row @require_sqlalchemy def SCREAMING_SNAKE_CASE__ ( snake_case : List[str] , snake_case : Optional[Any] , snake_case : Union[str, Any] ) -> str: """simple docstring""" a : str = tmp_path / """cache""" a : int = os.path.join(__SCREAMING_SNAKE_CASE , 'tmp.sql' ) a : Tuple = SqlDatasetReader('dataset' , 'sqlite:///' + sqlite_path , cache_dir=__SCREAMING_SNAKE_CASE ).read() SqlDatasetWriter(__SCREAMING_SNAKE_CASE , 'dataset' , 'sqlite:///' + output_sqlite_path , num_proc=1 ).write() a : int = iter_sql_file(__SCREAMING_SNAKE_CASE ) a : int = iter_sql_file(__SCREAMING_SNAKE_CASE ) for rowa, rowa in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE__ ( snake_case : int , snake_case : Union[str, Any] , snake_case : Optional[Any] ) -> List[Any]: """simple docstring""" a : int = tmp_path / """cache""" a : Optional[Any] = os.path.join(__SCREAMING_SNAKE_CASE , 'tmp.sql' ) a : Optional[int] = SqlDatasetReader('dataset' , 'sqlite:///' + sqlite_path , cache_dir=__SCREAMING_SNAKE_CASE ).read() SqlDatasetWriter(__SCREAMING_SNAKE_CASE , 'dataset' , 'sqlite:///' + output_sqlite_path , num_proc=2 ).write() a : List[str] = iter_sql_file(__SCREAMING_SNAKE_CASE ) a : Optional[Any] = iter_sql_file(__SCREAMING_SNAKE_CASE ) for rowa, rowa in zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): assert rowa == rowa @require_sqlalchemy def SCREAMING_SNAKE_CASE__ ( snake_case : List[str] , snake_case : Any , snake_case : str ) -> Union[str, Any]: """simple docstring""" a : List[str] = tmp_path / """cache""" a : Union[str, Any] = os.path.join(__SCREAMING_SNAKE_CASE , 'tmp.sql' ) a : Any = SqlDatasetReader('dataset' , 'sqlite:///' + sqlite_path , cache_dir=__SCREAMING_SNAKE_CASE ).read() with pytest.raises(__SCREAMING_SNAKE_CASE ): SqlDatasetWriter(__SCREAMING_SNAKE_CASE , 'dataset' , 'sqlite:///' + output_sqlite_path , num_proc=0 ).write()
370
'''simple docstring''' from __future__ import annotations def SCREAMING_SNAKE_CASE__ ( snake_case : int | float | str , snake_case : int | float | str ) -> list[str]: """simple docstring""" if nth_term == "": return [""] a : Dict = int(snake_case ) a : Optional[int] = int(snake_case ) a : list[str] = [] for temp in range(int(snake_case ) ): series.append(F"""1 / {pow(temp + 1 , int(snake_case ) )}""" if series else '1' ) return series if __name__ == "__main__": import doctest doctest.testmod() UpperCamelCase : Optional[int] = int(input("""Enter the last number (nth term) of the P-Series""")) UpperCamelCase : List[Any] = int(input("""Enter the power for P-Series""")) print("""Formula of P-Series => 1+1/2^p+1/3^p ..... 1/n^p""") print(p_series(nth_term, power))
345
0
"""simple docstring""" import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING A_ : int = logging.get_logger(__name__) A_ : str = { "microsoft/conditional-detr-resnet-50": ( "https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json" ), } class lowerCamelCase (A__ ): lowerCamelCase__ : Optional[Any] = 'conditional_detr' lowerCamelCase__ : List[Any] = ['past_key_values'] lowerCamelCase__ : List[Any] = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Optional[Any] , __UpperCAmelCase : List[str]=True , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : List[str]=3 , __UpperCAmelCase : int=3_0_0 , __UpperCAmelCase : Tuple=6 , __UpperCAmelCase : Tuple=2_0_4_8 , __UpperCAmelCase : int=8 , __UpperCAmelCase : List[Any]=6 , __UpperCAmelCase : int=2_0_4_8 , __UpperCAmelCase : Optional[Any]=8 , __UpperCAmelCase : List[str]=0.0 , __UpperCAmelCase : Union[str, Any]=0.0 , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : List[str]="relu" , __UpperCAmelCase : Any=2_5_6 , __UpperCAmelCase : Union[str, Any]=0.1 , __UpperCAmelCase : int=0.0 , __UpperCAmelCase : Optional[int]=0.0 , __UpperCAmelCase : int=0.02 , __UpperCAmelCase : Any=1.0 , __UpperCAmelCase : Tuple=False , __UpperCAmelCase : List[Any]="sine" , __UpperCAmelCase : Tuple="resnet50" , __UpperCAmelCase : Optional[Any]=True , __UpperCAmelCase : Optional[Any]=False , __UpperCAmelCase : Union[str, Any]=2 , __UpperCAmelCase : str=5 , __UpperCAmelCase : Union[str, Any]=2 , __UpperCAmelCase : Tuple=1 , __UpperCAmelCase : Tuple=1 , __UpperCAmelCase : Union[str, Any]=2 , __UpperCAmelCase : Optional[int]=5 , __UpperCAmelCase : Dict=2 , __UpperCAmelCase : Optional[int]=0.25 , **__UpperCAmelCase : Dict , ) -> Tuple: 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.""" ) SCREAMING_SNAKE_CASE__ = CONFIG_MAPPING["""resnet"""](out_features=["""stage4"""] ) elif isinstance(__UpperCAmelCase , __UpperCAmelCase ): SCREAMING_SNAKE_CASE__ = backbone_config.get("""model_type""" ) SCREAMING_SNAKE_CASE__ = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE__ = config_class.from_dict(__UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = use_timm_backbone SCREAMING_SNAKE_CASE__ = backbone_config SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = num_queries SCREAMING_SNAKE_CASE__ = d_model SCREAMING_SNAKE_CASE__ = encoder_ffn_dim SCREAMING_SNAKE_CASE__ = encoder_layers SCREAMING_SNAKE_CASE__ = encoder_attention_heads SCREAMING_SNAKE_CASE__ = decoder_ffn_dim SCREAMING_SNAKE_CASE__ = decoder_layers SCREAMING_SNAKE_CASE__ = decoder_attention_heads SCREAMING_SNAKE_CASE__ = dropout SCREAMING_SNAKE_CASE__ = attention_dropout SCREAMING_SNAKE_CASE__ = activation_dropout SCREAMING_SNAKE_CASE__ = activation_function SCREAMING_SNAKE_CASE__ = init_std SCREAMING_SNAKE_CASE__ = init_xavier_std SCREAMING_SNAKE_CASE__ = encoder_layerdrop SCREAMING_SNAKE_CASE__ = decoder_layerdrop SCREAMING_SNAKE_CASE__ = encoder_layers SCREAMING_SNAKE_CASE__ = auxiliary_loss SCREAMING_SNAKE_CASE__ = position_embedding_type SCREAMING_SNAKE_CASE__ = backbone SCREAMING_SNAKE_CASE__ = use_pretrained_backbone SCREAMING_SNAKE_CASE__ = dilation # Hungarian matcher SCREAMING_SNAKE_CASE__ = class_cost SCREAMING_SNAKE_CASE__ = bbox_cost SCREAMING_SNAKE_CASE__ = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE__ = mask_loss_coefficient SCREAMING_SNAKE_CASE__ = dice_loss_coefficient SCREAMING_SNAKE_CASE__ = cls_loss_coefficient SCREAMING_SNAKE_CASE__ = bbox_loss_coefficient SCREAMING_SNAKE_CASE__ = giou_loss_coefficient SCREAMING_SNAKE_CASE__ = focal_alpha super().__init__(is_encoder_decoder=__UpperCAmelCase , **__UpperCAmelCase ) @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> int: return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> int: return self.d_model def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: SCREAMING_SNAKE_CASE__ = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE__ = self.__class__.model_type return output class lowerCamelCase (A__ ): lowerCamelCase__ : Dict = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ("""pixel_mask""", {0: """batch"""}), ] ) @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> float: return 1e-5 @property def SCREAMING_SNAKE_CASE ( self : int ) -> int: return 1_2
165
"""simple docstring""" def A ( snake_case__ = 10_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 1, 1 SCREAMING_SNAKE_CASE__ = 2 while True: SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = fa + fa SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = fa, f index += 1 for _ in str(snake_case__ ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
165
1
'''simple docstring''' import json import os import torch from diffusers import UNetaDModel os.makedirs('hub/hopper-medium-v2/unet/hor32', exist_ok=True) os.makedirs('hub/hopper-medium-v2/unet/hor128', exist_ok=True) os.makedirs('hub/hopper-medium-v2/value_function', exist_ok=True) def lowerCamelCase__ ( _A ): if hor == 128: a : int = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') a : List[str] = (32, 128, 256) a : Dict = ('UpResnetBlock1D', 'UpResnetBlock1D') elif hor == 32: a : int = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') a : Any = (32, 64, 128, 256) a : Dict = ('UpResnetBlock1D', 'UpResnetBlock1D', 'UpResnetBlock1D') a : int = torch.load(f"""/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch""" ) a : Optional[Any] = model.state_dict() a : Any = { 'down_block_types': down_block_types, 'block_out_channels': block_out_channels, 'up_block_types': up_block_types, 'layers_per_block': 1, 'use_timestep_embedding': True, 'out_block_type': 'OutConv1DBlock', 'norm_num_groups': 8, 'downsample_each_block': False, 'in_channels': 14, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'flip_sin_to_cos': False, 'freq_shift': 1, 'sample_size': 6_5536, 'mid_block_type': 'MidResTemporalBlock1D', 'act_fn': 'mish', } a : str = UNetaDModel(**_A ) print(f"""length of state dict: {len(state_dict.keys() )}""" ) print(f"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) a : List[str] = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): a : List[str] = state_dict.pop(_A ) hf_value_function.load_state_dict(_A ) torch.save(hf_value_function.state_dict() , f"""hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin""" ) with open(f"""hub/hopper-medium-v2/unet/hor{hor}/config.json""" , 'w' ) as f: json.dump(_A , _A ) def lowerCamelCase__ ( ): a : str = { 'in_channels': 14, 'down_block_types': ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'), 'up_block_types': (), 'out_block_type': 'ValueFunction', 'mid_block_type': 'ValueFunctionMidBlock1D', 'block_out_channels': (32, 64, 128, 256), 'layers_per_block': 1, 'downsample_each_block': True, 'sample_size': 6_5536, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'use_timestep_embedding': True, 'flip_sin_to_cos': False, 'freq_shift': 1, 'norm_num_groups': 8, 'act_fn': 'mish', } a : Optional[int] = torch.load('/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch' ) a : str = model a : Dict = UNetaDModel(**_A ) print(f"""length of state dict: {len(state_dict.keys() )}""" ) print(f"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) a : Union[str, Any] = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): a : int = state_dict.pop(_A ) hf_value_function.load_state_dict(_A ) torch.save(hf_value_function.state_dict() , 'hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin' ) with open('hub/hopper-medium-v2/value_function/config.json' , 'w' ) as f: json.dump(_A , _A ) if __name__ == "__main__": unet(3_2) # unet(128) value_function()
362
'''simple docstring''' import os import pickle import unittest from transformers import AutoTokenizer from transformers.models.bert.tokenization_bert import BertTokenizer from transformers.models.bert_japanese.tokenization_bert_japanese import ( VOCAB_FILES_NAMES, BertJapaneseTokenizer, CharacterTokenizer, JumanppTokenizer, MecabTokenizer, SudachiTokenizer, WordpieceTokenizer, ) from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi from ...test_tokenization_common import TokenizerTesterMixin @custom_tokenizers class a__( lowerCamelCase__ , unittest.TestCase ): lowercase__ = BertJapaneseTokenizer lowercase__ = False lowercase__ = True def lowercase_ ( self : int ): super().setUp() a : List[Any] = [ '[UNK]', '[CLS]', '[SEP]', 'こんにちは', 'こん', 'にちは', 'ばんは', '##こん', '##にちは', '##ばんは', '世界', '##世界', '、', '##、', '。', '##。', ] a : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def lowercase_ ( self : Any , __snake_case : str ): a : Union[str, Any] = 'こんにちは、世界。 \nこんばんは、世界。' a : List[Any] = 'こんにちは 、 世界 。 こんばんは 、 世界 。' return input_text, output_text def lowercase_ ( self : Optional[Any] , __snake_case : Optional[Any] ): a , a : List[str] = self.get_input_output_texts(__snake_case ) a : Optional[int] = tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) a : str = tokenizer.decode(__snake_case , clean_up_tokenization_spaces=__snake_case ) return text, ids def lowercase_ ( self : Optional[Any] ): pass # TODO add if relevant def lowercase_ ( self : List[Any] ): pass # TODO add if relevant def lowercase_ ( self : Dict ): pass # TODO add if relevant def lowercase_ ( self : List[Any] ): a : Optional[int] = self.tokenizer_class(self.vocab_file ) a : Optional[int] = tokenizer.tokenize('こんにちは、世界。\nこんばんは、世界。' ) self.assertListEqual(__snake_case , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) def lowercase_ ( self : Union[str, Any] ): a : Tuple = self.tokenizer_class(self.vocab_file , word_tokenizer_type='mecab' ) self.assertIsNotNone(__snake_case ) a : List[str] = 'こんにちは、世界。\nこんばんは、世界。' a : Tuple = tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) a : Optional[int] = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(__snake_case , 'wb' ) as handle: pickle.dump(__snake_case , __snake_case ) with open(__snake_case , 'rb' ) as handle: a : Optional[Any] = pickle.load(__snake_case ) a : Tuple = tokenizer_new.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) def lowercase_ ( self : Dict ): a : List[str] = MecabTokenizer(mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def lowercase_ ( self : List[Any] ): try: a : int = MecabTokenizer(mecab_dic='unidic_lite' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def lowercase_ ( self : Any ): try: a : Union[str, Any] = MecabTokenizer(mecab_dic='unidic' ) except ModuleNotFoundError: return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def lowercase_ ( self : str ): a : Tuple = MecabTokenizer(do_lower_case=__snake_case , mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iphone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) def lowercase_ ( self : Union[str, Any] ): try: a : Any = MecabTokenizer( do_lower_case=__snake_case , normalize_text=__snake_case , mecab_option='-d /usr/local/lib/mecab/dic/jumandic' ) except RuntimeError: # if dict doesn't exist in the system, previous code raises this error. return self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れた', '\u3000', '。'] , ) def lowercase_ ( self : List[Any] ): a : Dict = MecabTokenizer(normalize_text=__snake_case , mecab_dic='ipadic' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップルストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', ' ', '。'] , ) @require_sudachi def lowercase_ ( self : str ): a : Optional[int] = self.tokenizer_class(self.vocab_file , word_tokenizer_type='sudachi' ) self.assertIsNotNone(__snake_case ) a : List[Any] = 'こんにちは、世界。\nこんばんは、世界。' a : int = tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) a : Tuple = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(__snake_case , 'wb' ) as handle: pickle.dump(__snake_case , __snake_case ) with open(__snake_case , 'rb' ) as handle: a : Optional[int] = pickle.load(__snake_case ) a : List[Any] = tokenizer_new.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) @require_sudachi def lowercase_ ( self : List[Any] ): a : Optional[Any] = SudachiTokenizer(sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iPhone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' '] , ) @require_sudachi def lowercase_ ( self : Any ): a : str = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='A' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国', '人', '参政', '権'] ) @require_sudachi def lowercase_ ( self : Optional[Any] ): a : Optional[int] = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='B' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国人', '参政権'] ) @require_sudachi def lowercase_ ( self : Optional[Any] ): a : Dict = SudachiTokenizer(sudachi_dict_type='core' , sudachi_split_mode='C' ) self.assertListEqual(tokenizer.tokenize('外国人参政権' ) , ['外国人参政権'] ) @require_sudachi def lowercase_ ( self : Dict ): a : Optional[int] = SudachiTokenizer(do_lower_case=__snake_case , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iphone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', ' ', '。', ' ', ' '] , ) @require_sudachi def lowercase_ ( self : Tuple ): a : int = SudachiTokenizer(normalize_text=__snake_case , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , [' ', '\t', 'アップル', 'ストア', 'で', 'iPhone', '8', ' ', 'が', ' ', ' ', '\n ', '発売', 'さ', 'れ', 'た', '\u3000', '。', ' ', ' '] , ) @require_sudachi def lowercase_ ( self : Union[str, Any] ): a : List[str] = SudachiTokenizer(trim_whitespace=__snake_case , sudachi_dict_type='core' ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れ', 'た', '。'] , ) @require_jumanpp def lowercase_ ( self : List[Any] ): a : Optional[int] = self.tokenizer_class(self.vocab_file , word_tokenizer_type='jumanpp' ) self.assertIsNotNone(__snake_case ) a : str = 'こんにちは、世界。\nこんばんは、世界。' a : Tuple = tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , ['こんにちは', '、', '世界', '。', 'こん', '##ばんは', '、', '世界', '。'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__snake_case ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] ) a : Optional[Any] = os.path.join(self.tmpdirname , 'tokenizer.bin' ) with open(__snake_case , 'wb' ) as handle: pickle.dump(__snake_case , __snake_case ) with open(__snake_case , 'rb' ) as handle: a : List[str] = pickle.load(__snake_case ) a : Any = tokenizer_new.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) @require_jumanpp def lowercase_ ( self : List[str] ): a : Any = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def lowercase_ ( self : List[str] ): a : List[Any] = JumanppTokenizer(do_lower_case=__snake_case ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iphone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def lowercase_ ( self : Any ): a : List[Any] = JumanppTokenizer(normalize_text=__snake_case ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['ア', 'ッ', 'フ', '゚', 'ル', 'ストア', 'で', 'iPhone', '8', '\u3000', 'が', '\u3000', '\u3000', '\u3000', '発売', 'さ', 'れた', '\u3000', '。'] , ) @require_jumanpp def lowercase_ ( self : Any ): a : str = JumanppTokenizer(trim_whitespace=__snake_case ) self.assertListEqual( tokenizer.tokenize(' \tアップルストアでiPhone8 が \n 発売された 。 ' ) , ['アップル', 'ストア', 'で', 'iPhone', '8', 'が', '発売', 'さ', 'れた', '。'] , ) @require_jumanpp def lowercase_ ( self : Tuple ): a : int = JumanppTokenizer() self.assertListEqual( tokenizer.tokenize('ありがとうございますm(_ _)m見つけるのが大変です。' ) , ['ありがとう', 'ございます', 'm(_ _)m', '見つける', 'の', 'が', '大変です', '。'] , ) def lowercase_ ( self : Any ): a : int = ['[UNK]', '[CLS]', '[SEP]', 'こんにちは', 'こん', 'にちは', 'ばんは', '##こん', '##にちは', '##ばんは'] a : Optional[int] = {} for i, token in enumerate(__snake_case ): a : Dict = i a : Optional[Any] = WordpieceTokenizer(vocab=__snake_case , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('こんにちは' ) , ['こんにちは'] ) self.assertListEqual(tokenizer.tokenize('こんばんは' ) , ['こん', '##ばんは'] ) self.assertListEqual(tokenizer.tokenize('こんばんは こんばんにちは こんにちは' ) , ['こん', '##ばんは', '[UNK]', 'こんにちは'] ) def lowercase_ ( self : Tuple ): a : List[Any] = BertJapaneseTokenizer.from_pretrained('nlp-waseda/roberta-base-japanese-with-auto-jumanpp' ) a : List[Any] = tokenizer.subword_tokenizer a : List[str] = subword_tokenizer.tokenize('国境 の 長い トンネル を 抜ける と 雪国 であった 。' ) self.assertListEqual(__snake_case , ['▁国境', '▁の', '▁長い', '▁トンネル', '▁を', '▁抜ける', '▁と', '▁雪', '国', '▁であった', '▁。'] ) a : Union[str, Any] = subword_tokenizer.tokenize('こんばんは こんばん にち は こんにちは' ) self.assertListEqual(__snake_case , ['▁こん', 'ばん', 'は', '▁こん', 'ばん', '▁に', 'ち', '▁は', '▁こんにちは'] ) def lowercase_ ( self : Union[str, Any] ): a : Optional[Any] = self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese' ) a : Dict = tokenizer.encode('ありがとう。' , add_special_tokens=__snake_case ) a : str = tokenizer.encode('どういたしまして。' , add_special_tokens=__snake_case ) a : Optional[int] = tokenizer.build_inputs_with_special_tokens(__snake_case ) a : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__snake_case , __snake_case ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class a__( lowerCamelCase__ , unittest.TestCase ): lowercase__ = BertJapaneseTokenizer lowercase__ = False def lowercase_ ( self : List[Any] ): super().setUp() a : List[Any] = ['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。'] a : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def lowercase_ ( self : Optional[Any] , **__snake_case : List[Any] ): return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type='character' , **__snake_case ) def lowercase_ ( self : Tuple , __snake_case : List[str] ): a : int = 'こんにちは、世界。 \nこんばんは、世界。' a : Optional[Any] = 'こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。' return input_text, output_text def lowercase_ ( self : str ): pass # TODO add if relevant def lowercase_ ( self : List[str] ): pass # TODO add if relevant def lowercase_ ( self : Any ): pass # TODO add if relevant def lowercase_ ( self : Any ): a : Optional[int] = self.tokenizer_class(self.vocab_file , subword_tokenizer_type='character' ) a : Tuple = tokenizer.tokenize('こんにちは、世界。 \nこんばんは、世界。' ) self.assertListEqual( __snake_case , ['こ', 'ん', 'に', 'ち', 'は', '、', '世', '界', '。', 'こ', 'ん', 'ば', 'ん', 'は', '、', '世', '界', '。'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__snake_case ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] ) def lowercase_ ( self : Any ): a : Union[str, Any] = ['[UNK]', '[CLS]', '[SEP]', 'こ', 'ん', 'に', 'ち', 'は', 'ば', '世', '界', '、', '。'] a : Optional[Any] = {} for i, token in enumerate(__snake_case ): a : Tuple = i a : Optional[int] = CharacterTokenizer(vocab=__snake_case , unk_token='[UNK]' ) self.assertListEqual(tokenizer.tokenize('' ) , [] ) self.assertListEqual(tokenizer.tokenize('こんにちは' ) , ['こ', 'ん', 'に', 'ち', 'は'] ) self.assertListEqual(tokenizer.tokenize('こんにちほ' ) , ['こ', 'ん', 'に', 'ち', '[UNK]'] ) def lowercase_ ( self : Tuple ): a : List[Any] = self.tokenizer_class.from_pretrained('cl-tohoku/bert-base-japanese-char' ) a : Optional[int] = tokenizer.encode('ありがとう。' , add_special_tokens=__snake_case ) a : List[str] = tokenizer.encode('どういたしまして。' , add_special_tokens=__snake_case ) a : Optional[int] = tokenizer.build_inputs_with_special_tokens(__snake_case ) a : Dict = tokenizer.build_inputs_with_special_tokens(__snake_case , __snake_case ) # 2 is for "[CLS]", 3 is for "[SEP]" assert encoded_sentence == [2] + text + [3] assert encoded_pair == [2] + text + [3] + text_a + [3] @custom_tokenizers class a__( unittest.TestCase ): def lowercase_ ( self : List[str] ): a : List[Any] = 'cl-tohoku/bert-base-japanese' a : Dict = AutoTokenizer.from_pretrained(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) class a__( unittest.TestCase ): def lowercase_ ( self : Union[str, Any] ): a : List[str] = 'cl-tohoku/bert-base-japanese' with self.assertLogs('transformers' , level='WARNING' ) as cm: BertTokenizer.from_pretrained(__snake_case ) self.assertTrue( cm.records[0].message.startswith( 'The tokenizer class you load from this checkpoint is not the same type as the class this function' ' is called from.' ) ) a : Dict = 'bert-base-cased' with self.assertLogs('transformers' , level='WARNING' ) as cm: BertJapaneseTokenizer.from_pretrained(__snake_case ) self.assertTrue( cm.records[0].message.startswith( 'The tokenizer class you load from this checkpoint is not the same type as the class this function' ' is called from.' ) )
96
0
'''simple docstring''' a__ : List[Any] = { 'Pillow': 'Pillow<10.0.0', 'accelerate': 'accelerate>=0.20.3', 'av': 'av==9.2.0', 'beautifulsoup4': 'beautifulsoup4', 'black': 'black~=23.1', 'codecarbon': 'codecarbon==1.2.0', 'cookiecutter': 'cookiecutter==1.7.3', 'dataclasses': 'dataclasses', 'datasets': 'datasets!=2.5.0', 'decord': 'decord==0.6.0', 'deepspeed': 'deepspeed>=0.9.3', 'diffusers': 'diffusers', 'dill': 'dill<0.3.5', 'evaluate': 'evaluate>=0.2.0', 'fairscale': 'fairscale>0.3', 'faiss-cpu': 'faiss-cpu', 'fastapi': 'fastapi', 'filelock': 'filelock', 'flax': 'flax>=0.4.1,<=0.7.0', 'ftfy': 'ftfy', 'fugashi': 'fugashi>=1.0', 'GitPython': 'GitPython<3.1.19', 'hf-doc-builder': 'hf-doc-builder>=0.3.0', 'huggingface-hub': 'huggingface-hub>=0.14.1,<1.0', 'importlib_metadata': 'importlib_metadata', 'ipadic': 'ipadic>=1.0.0,<2.0', 'isort': 'isort>=5.5.4', 'jax': 'jax>=0.2.8,!=0.3.2,<=0.4.13', 'jaxlib': 'jaxlib>=0.1.65,<=0.4.13', 'jieba': 'jieba', 'kenlm': 'kenlm', 'keras-nlp': 'keras-nlp>=0.3.1', 'librosa': 'librosa', 'nltk': 'nltk', 'natten': 'natten>=0.14.6', 'numpy': 'numpy>=1.17', 'onnxconverter-common': 'onnxconverter-common', 'onnxruntime-tools': 'onnxruntime-tools>=1.4.2', 'onnxruntime': 'onnxruntime>=1.4.0', 'opencv-python': 'opencv-python', 'optuna': 'optuna', 'optax': 'optax>=0.0.8,<=0.1.4', 'packaging': 'packaging>=20.0', 'parameterized': 'parameterized', 'phonemizer': 'phonemizer', 'protobuf': 'protobuf', 'psutil': 'psutil', 'pyyaml': 'pyyaml>=5.1', 'pydantic': 'pydantic<2', 'pytest': 'pytest>=7.2.0', 'pytest-timeout': 'pytest-timeout', 'pytest-xdist': 'pytest-xdist', 'python': 'python>=3.8.0', 'ray[tune]': 'ray[tune]', 'regex': 'regex!=2019.12.17', 'requests': 'requests', 'rhoknp': 'rhoknp>=1.1.0,<1.3.1', 'rjieba': 'rjieba', 'rouge-score': 'rouge-score!=0.0.7,!=0.0.8,!=0.1,!=0.1.1', 'ruff': 'ruff>=0.0.241,<=0.0.259', 'sacrebleu': 'sacrebleu>=1.4.12,<2.0.0', 'sacremoses': 'sacremoses', 'safetensors': 'safetensors>=0.3.1', 'sagemaker': 'sagemaker>=2.31.0', 'scikit-learn': 'scikit-learn', 'sentencepiece': 'sentencepiece>=0.1.91,!=0.1.92', 'sigopt': 'sigopt', 'starlette': 'starlette', 'sudachipy': 'sudachipy>=0.6.6', 'sudachidict_core': 'sudachidict_core>=20220729', 'tensorflow-cpu': 'tensorflow-cpu>=2.6,<2.14', 'tensorflow': 'tensorflow>=2.6,<2.14', 'tensorflow-text': 'tensorflow-text<2.14', 'tf2onnx': 'tf2onnx', 'timeout-decorator': 'timeout-decorator', 'timm': 'timm', 'tokenizers': 'tokenizers>=0.11.1,!=0.11.3,<0.14', 'torch': 'torch>=1.9,!=1.12.0', 'torchaudio': 'torchaudio', 'torchvision': 'torchvision', 'pyctcdecode': 'pyctcdecode>=0.4.0', 'tqdm': 'tqdm>=4.27', 'unidic': 'unidic>=1.0.2', 'unidic_lite': 'unidic_lite>=1.0.7', 'urllib3': 'urllib3<2.0.0', 'uvicorn': 'uvicorn', }
80
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool __magic_name__: Tuple = { "Acehnese Arabic": "ace_Arab", "Acehnese Latin": "ace_Latn", "Mesopotamian Arabic": "acm_Arab", "Ta'izzi-Adeni Arabic": "acq_Arab", "Tunisian Arabic": "aeb_Arab", "Afrikaans": "afr_Latn", "South Levantine Arabic": "ajp_Arab", "Akan": "aka_Latn", "Amharic": "amh_Ethi", "North Levantine Arabic": "apc_Arab", "Modern Standard Arabic": "arb_Arab", "Modern Standard Arabic Romanized": "arb_Latn", "Najdi Arabic": "ars_Arab", "Moroccan Arabic": "ary_Arab", "Egyptian Arabic": "arz_Arab", "Assamese": "asm_Beng", "Asturian": "ast_Latn", "Awadhi": "awa_Deva", "Central Aymara": "ayr_Latn", "South Azerbaijani": "azb_Arab", "North Azerbaijani": "azj_Latn", "Bashkir": "bak_Cyrl", "Bambara": "bam_Latn", "Balinese": "ban_Latn", "Belarusian": "bel_Cyrl", "Bemba": "bem_Latn", "Bengali": "ben_Beng", "Bhojpuri": "bho_Deva", "Banjar Arabic": "bjn_Arab", "Banjar Latin": "bjn_Latn", "Standard Tibetan": "bod_Tibt", "Bosnian": "bos_Latn", "Buginese": "bug_Latn", "Bulgarian": "bul_Cyrl", "Catalan": "cat_Latn", "Cebuano": "ceb_Latn", "Czech": "ces_Latn", "Chokwe": "cjk_Latn", "Central Kurdish": "ckb_Arab", "Crimean Tatar": "crh_Latn", "Welsh": "cym_Latn", "Danish": "dan_Latn", "German": "deu_Latn", "Southwestern Dinka": "dik_Latn", "Dyula": "dyu_Latn", "Dzongkha": "dzo_Tibt", "Greek": "ell_Grek", "English": "eng_Latn", "Esperanto": "epo_Latn", "Estonian": "est_Latn", "Basque": "eus_Latn", "Ewe": "ewe_Latn", "Faroese": "fao_Latn", "Fijian": "fij_Latn", "Finnish": "fin_Latn", "Fon": "fon_Latn", "French": "fra_Latn", "Friulian": "fur_Latn", "Nigerian Fulfulde": "fuv_Latn", "Scottish Gaelic": "gla_Latn", "Irish": "gle_Latn", "Galician": "glg_Latn", "Guarani": "grn_Latn", "Gujarati": "guj_Gujr", "Haitian Creole": "hat_Latn", "Hausa": "hau_Latn", "Hebrew": "heb_Hebr", "Hindi": "hin_Deva", "Chhattisgarhi": "hne_Deva", "Croatian": "hrv_Latn", "Hungarian": "hun_Latn", "Armenian": "hye_Armn", "Igbo": "ibo_Latn", "Ilocano": "ilo_Latn", "Indonesian": "ind_Latn", "Icelandic": "isl_Latn", "Italian": "ita_Latn", "Javanese": "jav_Latn", "Japanese": "jpn_Jpan", "Kabyle": "kab_Latn", "Jingpho": "kac_Latn", "Kamba": "kam_Latn", "Kannada": "kan_Knda", "Kashmiri Arabic": "kas_Arab", "Kashmiri Devanagari": "kas_Deva", "Georgian": "kat_Geor", "Central Kanuri Arabic": "knc_Arab", "Central Kanuri Latin": "knc_Latn", "Kazakh": "kaz_Cyrl", "Kabiyè": "kbp_Latn", "Kabuverdianu": "kea_Latn", "Khmer": "khm_Khmr", "Kikuyu": "kik_Latn", "Kinyarwanda": "kin_Latn", "Kyrgyz": "kir_Cyrl", "Kimbundu": "kmb_Latn", "Northern Kurdish": "kmr_Latn", "Kikongo": "kon_Latn", "Korean": "kor_Hang", "Lao": "lao_Laoo", "Ligurian": "lij_Latn", "Limburgish": "lim_Latn", "Lingala": "lin_Latn", "Lithuanian": "lit_Latn", "Lombard": "lmo_Latn", "Latgalian": "ltg_Latn", "Luxembourgish": "ltz_Latn", "Luba-Kasai": "lua_Latn", "Ganda": "lug_Latn", "Luo": "luo_Latn", "Mizo": "lus_Latn", "Standard Latvian": "lvs_Latn", "Magahi": "mag_Deva", "Maithili": "mai_Deva", "Malayalam": "mal_Mlym", "Marathi": "mar_Deva", "Minangkabau Arabic ": "min_Arab", "Minangkabau Latin": "min_Latn", "Macedonian": "mkd_Cyrl", "Plateau Malagasy": "plt_Latn", "Maltese": "mlt_Latn", "Meitei Bengali": "mni_Beng", "Halh Mongolian": "khk_Cyrl", "Mossi": "mos_Latn", "Maori": "mri_Latn", "Burmese": "mya_Mymr", "Dutch": "nld_Latn", "Norwegian Nynorsk": "nno_Latn", "Norwegian Bokmål": "nob_Latn", "Nepali": "npi_Deva", "Northern Sotho": "nso_Latn", "Nuer": "nus_Latn", "Nyanja": "nya_Latn", "Occitan": "oci_Latn", "West Central Oromo": "gaz_Latn", "Odia": "ory_Orya", "Pangasinan": "pag_Latn", "Eastern Panjabi": "pan_Guru", "Papiamento": "pap_Latn", "Western Persian": "pes_Arab", "Polish": "pol_Latn", "Portuguese": "por_Latn", "Dari": "prs_Arab", "Southern Pashto": "pbt_Arab", "Ayacucho Quechua": "quy_Latn", "Romanian": "ron_Latn", "Rundi": "run_Latn", "Russian": "rus_Cyrl", "Sango": "sag_Latn", "Sanskrit": "san_Deva", "Santali": "sat_Olck", "Sicilian": "scn_Latn", "Shan": "shn_Mymr", "Sinhala": "sin_Sinh", "Slovak": "slk_Latn", "Slovenian": "slv_Latn", "Samoan": "smo_Latn", "Shona": "sna_Latn", "Sindhi": "snd_Arab", "Somali": "som_Latn", "Southern Sotho": "sot_Latn", "Spanish": "spa_Latn", "Tosk Albanian": "als_Latn", "Sardinian": "srd_Latn", "Serbian": "srp_Cyrl", "Swati": "ssw_Latn", "Sundanese": "sun_Latn", "Swedish": "swe_Latn", "Swahili": "swh_Latn", "Silesian": "szl_Latn", "Tamil": "tam_Taml", "Tatar": "tat_Cyrl", "Telugu": "tel_Telu", "Tajik": "tgk_Cyrl", "Tagalog": "tgl_Latn", "Thai": "tha_Thai", "Tigrinya": "tir_Ethi", "Tamasheq Latin": "taq_Latn", "Tamasheq Tifinagh": "taq_Tfng", "Tok Pisin": "tpi_Latn", "Tswana": "tsn_Latn", "Tsonga": "tso_Latn", "Turkmen": "tuk_Latn", "Tumbuka": "tum_Latn", "Turkish": "tur_Latn", "Twi": "twi_Latn", "Central Atlas Tamazight": "tzm_Tfng", "Uyghur": "uig_Arab", "Ukrainian": "ukr_Cyrl", "Umbundu": "umb_Latn", "Urdu": "urd_Arab", "Northern Uzbek": "uzn_Latn", "Venetian": "vec_Latn", "Vietnamese": "vie_Latn", "Waray": "war_Latn", "Wolof": "wol_Latn", "Xhosa": "xho_Latn", "Eastern Yiddish": "ydd_Hebr", "Yoruba": "yor_Latn", "Yue Chinese": "yue_Hant", "Chinese Simplified": "zho_Hans", "Chinese Traditional": "zho_Hant", "Standard Malay": "zsm_Latn", "Zulu": "zul_Latn", } class snake_case__ ( _lowerCAmelCase ): lowercase__ : List[str] = '''facebook/nllb-200-distilled-600M''' lowercase__ : List[Any] = ( '''This is a tool that translates text from a language to another. It takes three inputs: `text`, which should ''' '''be the text to translate, `src_lang`, which should be the language of the text to translate and `tgt_lang`, ''' '''which should be the language for the desired ouput language. Both `src_lang` and `tgt_lang` are written in ''' '''plain English, such as \'Romanian\', or \'Albanian\'. It returns the text translated in `tgt_lang`.''' ) lowercase__ : List[str] = '''translator''' lowercase__ : Optional[Any] = AutoTokenizer lowercase__ : int = AutoModelForSeqaSeqLM lowercase__ : List[Any] = LANGUAGE_CODES lowercase__ : str = ['''text''', '''text''', '''text'''] lowercase__ : Any = ['''text'''] def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[str]: if src_lang not in self.lang_to_code: raise ValueError(F'{src_lang} is not a supported language.' ) if tgt_lang not in self.lang_to_code: raise ValueError(F'{tgt_lang} is not a supported language.' ) __magic_name__ : Tuple = self.lang_to_code[src_lang] __magic_name__ : Dict = self.lang_to_code[tgt_lang] return self.pre_processor._build_translation_inputs( lowerCAmelCase__ , return_tensors="""pt""" , src_lang=lowerCAmelCase__ , tgt_lang=lowerCAmelCase__ ) def __magic_name__ ( self , lowerCAmelCase__ ) -> Dict: return self.model.generate(**lowerCAmelCase__ ) def __magic_name__ ( self , lowerCAmelCase__ ) -> Dict: return self.post_processor.decode(outputs[0].tolist() , skip_special_tokens=lowerCAmelCase__ )
342
0
"""simple docstring""" import argparse import datetime def lowercase__ ( lowercase_ ) -> Optional[int]: """simple docstring""" _UpperCamelCase : int = { "0": "Sunday", "1": "Monday", "2": "Tuesday", "3": "Wednesday", "4": "Thursday", "5": "Friday", "6": "Saturday", } _UpperCamelCase : Union[str, Any] = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0} # Validate if not 0 < len(lowercase_ ) < 11: raise ValueError("Must be 10 characters long" ) # Get month _UpperCamelCase : Any = int(date_input[0] + date_input[1] ) # Validate if not 0 < m < 13: raise ValueError("Month must be between 1 - 12" ) _UpperCamelCase : int = date_input[2] # Validate if sep_a not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'" ) # Get day _UpperCamelCase : List[Any] = int(date_input[3] + date_input[4] ) # Validate if not 0 < d < 32: raise ValueError("Date must be between 1 - 31" ) # Get second separator _UpperCamelCase : Union[str, Any] = date_input[5] # Validate if sep_a not in ["-", "/"]: raise ValueError("Date separator must be '-' or '/'" ) # Get year _UpperCamelCase : Dict = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] ) # Arbitrary year range if not 45 < y < 8_500: raise ValueError( "Year out of range. There has to be some sort of limit...right?" ) # Get datetime obj for validation _UpperCamelCase : Dict = datetime.date(int(lowercase_ ) ,int(lowercase_ ) ,int(lowercase_ ) ) # Start math if m <= 2: _UpperCamelCase : str = y - 1 _UpperCamelCase : Union[str, Any] = m + 12 # maths var _UpperCamelCase : Union[str, Any] = int(str(lowercase_ )[:2] ) _UpperCamelCase : str = int(str(lowercase_ )[2:] ) _UpperCamelCase : List[Any] = int(2.6 * m - 5.39 ) _UpperCamelCase : int = int(c / 4 ) _UpperCamelCase : List[Any] = int(k / 4 ) _UpperCamelCase : List[str] = int(d + k ) _UpperCamelCase : str = int(t + u + v + x ) _UpperCamelCase : Union[str, Any] = int(z - (2 * c) ) _UpperCamelCase : List[str] = round(w % 7 ) # End math # Validate math if f != convert_datetime_days[dt_ck.weekday()]: raise AssertionError("The date was evaluated incorrectly. Contact developer." ) # Response _UpperCamelCase : int = F'''Your date {date_input}, is a {days[str(lowercase_ )]}!''' return response if __name__ == "__main__": import doctest doctest.testmod() lowerCamelCase__ = argparse.ArgumentParser( description=( "Find out what day of the week nearly any date is or was. Enter " "date as a string in the mm-dd-yyyy or mm/dd/yyyy format" ) ) parser.add_argument( "date_input", type=str, help="Date as a string (mm-dd-yyyy or mm/dd/yyyy)" ) lowerCamelCase__ = parser.parse_args() zeller(args.date_input)
358
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase__ = logging.get_logger(__name__) lowerCamelCase__ = { "facebook/xlm-roberta-xl": "https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json", "facebook/xlm-roberta-xxl": "https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json", # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' SCREAMING_SNAKE_CASE__ :List[Any] = "xlm-roberta-xl" def __init__( self : Any , __a : Tuple=25_0880 , __a : Optional[Any]=2560 , __a : List[str]=36 , __a : Any=32 , __a : Dict=1_0240 , __a : Optional[Any]="gelu" , __a : int=0.1 , __a : Tuple=0.1 , __a : str=514 , __a : Any=1 , __a : List[Any]=0.02 , __a : List[str]=1e-0_5 , __a : Optional[Any]=1 , __a : List[Any]=0 , __a : Tuple=2 , __a : int="absolute" , __a : Dict=True , __a : Dict=None , **__a : Tuple , ) -> str: super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) _UpperCamelCase : Any = vocab_size _UpperCamelCase : Optional[int] = hidden_size _UpperCamelCase : str = num_hidden_layers _UpperCamelCase : Optional[int] = num_attention_heads _UpperCamelCase : List[str] = hidden_act _UpperCamelCase : Union[str, Any] = intermediate_size _UpperCamelCase : str = hidden_dropout_prob _UpperCamelCase : str = attention_probs_dropout_prob _UpperCamelCase : Dict = max_position_embeddings _UpperCamelCase : Optional[Any] = type_vocab_size _UpperCamelCase : str = initializer_range _UpperCamelCase : Any = layer_norm_eps _UpperCamelCase : Any = position_embedding_type _UpperCamelCase : Union[str, Any] = use_cache _UpperCamelCase : Optional[Any] = classifier_dropout class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): '''simple docstring''' @property def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": _UpperCamelCase : Any = {0: "batch", 1: "choice", 2: "sequence"} else: _UpperCamelCase : Dict = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
310
0
'''simple docstring''' import os import string import sys _A : Optional[Any] =1 << 8 _A : Union[str, Any] ={ '''tab''': ord('''\t'''), '''newline''': ord('''\r'''), '''esc''': 27, '''up''': 65 + ARROW_KEY_FLAG, '''down''': 66 + ARROW_KEY_FLAG, '''right''': 67 + ARROW_KEY_FLAG, '''left''': 68 + ARROW_KEY_FLAG, '''mod_int''': 91, '''undefined''': sys.maxsize, '''interrupt''': 3, '''insert''': 50, '''delete''': 51, '''pg_up''': 53, '''pg_down''': 54, } _A : Optional[Any] =KEYMAP['''up'''] _A : Optional[Any] =KEYMAP['''left'''] if sys.platform == "win32": _A : List[str] =[] _A : Union[str, Any] ={ b'''\xe0H''': KEYMAP['''up'''] - ARROW_KEY_FLAG, b'''\x00H''': KEYMAP['''up'''] - ARROW_KEY_FLAG, b'''\xe0P''': KEYMAP['''down'''] - ARROW_KEY_FLAG, b'''\x00P''': KEYMAP['''down'''] - ARROW_KEY_FLAG, b'''\xe0M''': KEYMAP['''right'''] - ARROW_KEY_FLAG, b'''\x00M''': KEYMAP['''right'''] - ARROW_KEY_FLAG, b'''\xe0K''': KEYMAP['''left'''] - ARROW_KEY_FLAG, b'''\x00K''': KEYMAP['''left'''] - ARROW_KEY_FLAG, } for i in range(10): _A : List[str] =ord(str(i)) def SCREAMING_SNAKE_CASE_ () -> int: if os.name == "nt": import msvcrt lowerCamelCase__ : str = """mbcs""" # Flush the keyboard buffer while msvcrt.kbhit(): msvcrt.getch() if len(UpperCamelCase ) == 0: # Read the keystroke lowerCamelCase__ : List[Any] = msvcrt.getch() # If it is a prefix char, get second part if ch in (b"\x00", b"\xe0"): lowerCamelCase__ : Optional[int] = ch + msvcrt.getch() # Translate actual Win chars to bullet char types try: lowerCamelCase__ : Tuple = chr(WIN_KEYMAP[cha] ) WIN_CH_BUFFER.append(chr(KEYMAP["""mod_int"""] ) ) WIN_CH_BUFFER.append(UpperCamelCase ) if ord(UpperCamelCase ) in ( KEYMAP["insert"] - 1 << 9, KEYMAP["delete"] - 1 << 9, KEYMAP["pg_up"] - 1 << 9, KEYMAP["pg_down"] - 1 << 9, ): WIN_CH_BUFFER.append(chr(126 ) ) lowerCamelCase__ : str = chr(KEYMAP["""esc"""] ) except KeyError: lowerCamelCase__ : List[str] = cha[1] else: lowerCamelCase__ : Any = ch.decode(UpperCamelCase ) else: lowerCamelCase__ : str = WIN_CH_BUFFER.pop(0 ) elif os.name == "posix": import termios import tty lowerCamelCase__ : List[Any] = sys.stdin.fileno() lowerCamelCase__ : Any = termios.tcgetattr(UpperCamelCase ) try: tty.setraw(UpperCamelCase ) lowerCamelCase__ : Dict = sys.stdin.read(1 ) finally: termios.tcsetattr(UpperCamelCase , termios.TCSADRAIN , UpperCamelCase ) return ch def SCREAMING_SNAKE_CASE_ () -> Optional[int]: lowerCamelCase__ : Dict = get_raw_chars() if ord(UpperCamelCase ) in [KEYMAP["interrupt"], KEYMAP["newline"]]: return char elif ord(UpperCamelCase ) == KEYMAP["esc"]: lowerCamelCase__ : List[str] = get_raw_chars() if ord(UpperCamelCase ) == KEYMAP["mod_int"]: lowerCamelCase__ : str = get_raw_chars() if ord(UpperCamelCase ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(UpperCamelCase ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: return chr(ord(UpperCamelCase ) + ARROW_KEY_FLAG ) else: return KEYMAP["undefined"] else: return get_raw_chars() else: if char in string.printable: return char else: return KEYMAP["undefined"]
41
from __future__ import annotations import os from collections.abc import Mapping _UpperCAmelCase : Tuple = tuple[int, int] class lowercase : def __init__( self , A_ , A_ ) -> None: """simple docstring""" UpperCamelCase = vertices UpperCamelCase = { (min(A_ ), max(A_ )): weight for edge, weight in edges.items() } def __UpperCamelCase ( self , A_ , A_ ) -> None: """simple docstring""" self.vertices.add(edge[0] ) self.vertices.add(edge[1] ) UpperCamelCase = weight def __UpperCamelCase ( self ) -> Graph: """simple docstring""" UpperCamelCase = Graph({min(self.vertices )} , {} ) UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 while len(subgraph.vertices ) < len(self.vertices ): UpperCamelCase = max(self.edges.values() ) + 1 for edge, weight in self.edges.items(): if (edge[0] in subgraph.vertices) ^ (edge[1] in subgraph.vertices): if weight < min_weight: UpperCamelCase = edge UpperCamelCase = weight subgraph.add_edge(A_ , A_ ) return subgraph def A ( lowercase = "p107_network.txt" ) -> int: '''simple docstring''' UpperCamelCase = os.path.abspath(os.path.dirname(lowercase ) ) UpperCamelCase = os.path.join(lowercase , lowercase ) UpperCamelCase = {} UpperCamelCase = 42 UpperCamelCase = 42 UpperCamelCase = 42 with open(lowercase ) as f: UpperCamelCase = f.read().strip().split('\n' ) UpperCamelCase = [line.split(',' ) for line in data] for edgea in range(1 , len(lowercase ) ): for edgea in range(lowercase ): if adjaceny_matrix[edgea][edgea] != "-": UpperCamelCase = int(adjaceny_matrix[edgea][edgea] ) UpperCamelCase = Graph(set(range(len(lowercase ) ) ) , lowercase ) UpperCamelCase = graph.prims_algorithm() UpperCamelCase = sum(graph.edges.values() ) UpperCamelCase = sum(subgraph.edges.values() ) return initial_total - optimal_total if __name__ == "__main__": print(F'''{solution() = }''')
222
0
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class __SCREAMING_SNAKE_CASE ( unittest.TestCase): def UpperCamelCase__ ( self ): """simple docstring""" debug_launcher(test_script.main ) def UpperCamelCase__ ( self ): """simple docstring""" debug_launcher(test_ops.main )
122
import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class __SCREAMING_SNAKE_CASE ( __lowercase , unittest.TestCase): _SCREAMING_SNAKE_CASE : Tuple = BarthezTokenizer _SCREAMING_SNAKE_CASE : int = BarthezTokenizerFast _SCREAMING_SNAKE_CASE : Dict = True _SCREAMING_SNAKE_CASE : Tuple = True def UpperCamelCase__ ( self ): """simple docstring""" super().setUp() lowerCAmelCase__ = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=_UpperCamelCase ) lowerCAmelCase__ = tokenizer def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase__ = '<pad>' lowerCAmelCase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCamelCase ) , _UpperCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCamelCase ) , _UpperCamelCase ) def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(_UpperCamelCase ) , 10_11_22 ) def UpperCamelCase__ ( self ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 10_11_22 ) @require_torch def UpperCamelCase__ ( self ): """simple docstring""" lowerCAmelCase__ = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] lowerCAmelCase__ = [0, 57, 30_18, 7_03_07, 91, 2] lowerCAmelCase__ = self.tokenizer( _UpperCamelCase , max_length=len(_UpperCamelCase ) , padding=_UpperCamelCase , truncation=_UpperCamelCase , return_tensors='pt' ) self.assertIsInstance(_UpperCamelCase , _UpperCamelCase ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) lowerCAmelCase__ = batch.input_ids.tolist()[0] self.assertListEqual(_UpperCamelCase , _UpperCamelCase ) def UpperCamelCase__ ( self ): """simple docstring""" if not self.test_rust_tokenizer: return lowerCAmelCase__ = self.get_tokenizer() lowerCAmelCase__ = self.get_rust_tokenizer() lowerCAmelCase__ = 'I was born in 92000, and this is falsé.' lowerCAmelCase__ = tokenizer.tokenize(_UpperCamelCase ) lowerCAmelCase__ = rust_tokenizer.tokenize(_UpperCamelCase ) self.assertListEqual(_UpperCamelCase , _UpperCamelCase ) lowerCAmelCase__ = tokenizer.encode(_UpperCamelCase , add_special_tokens=_UpperCamelCase ) lowerCAmelCase__ = rust_tokenizer.encode(_UpperCamelCase , add_special_tokens=_UpperCamelCase ) self.assertListEqual(_UpperCamelCase , _UpperCamelCase ) lowerCAmelCase__ = self.get_rust_tokenizer() lowerCAmelCase__ = tokenizer.encode(_UpperCamelCase ) lowerCAmelCase__ = rust_tokenizer.encode(_UpperCamelCase ) self.assertListEqual(_UpperCamelCase , _UpperCamelCase ) @slow def UpperCamelCase__ ( self ): """simple docstring""" # fmt: off lowerCAmelCase__ = {'input_ids': [[0, 4_90, 1_43_28, 45_07, 3_54, 47, 4_36_69, 95, 25, 7_81_17, 2_02_15, 1_97_79, 1_90, 22, 4_00, 4, 3_53_43, 8_03_10, 6_03, 86, 2_49_37, 1_05, 3_34_38, 9_47_62, 1_96, 3_96_42, 7, 15, 1_59_33, 1_73, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1_05_34, 87, 25, 66, 33_58, 1_96, 5_52_89, 8, 8_29_61, 81, 22_04, 7_52_03, 7, 15, 7_63, 1_29_56, 2_16, 1_78, 1_43_28, 95_95, 13_77, 6_96_93, 7, 4_48, 7_10_21, 1_96, 1_81_06, 14_37, 1_39_74, 1_08, 90_83, 4, 4_93_15, 7, 39, 86, 13_26, 27_93, 4_63_33, 4, 4_48, 1_96, 7_45_88, 7, 4_93_15, 7, 39, 21, 8_22, 3_84_70, 74, 21, 6_67_23, 6_24_80, 8, 2_20_50, 5, 2]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. lowerCAmelCase__ = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=_UpperCamelCase , model_name='moussaKam/mbarthez' , revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' , sequences=_UpperCamelCase , )
122
1
import operator def SCREAMING_SNAKE_CASE_ ( __A : list , __A : bool = False , __A : list | None = None ) -> list: """simple docstring""" a_ : Union[str, Any] = operator.lt if reverse else operator.gt a_ : List[str] = solution or [] if not arr: return solution a_ : str = [arr.pop(0 )] for i, item in enumerate(__A ): if _operator(__A , sublist[-1] ): sublist.append(__A ) arr.pop(__A ) # merging sublist into solution list if not solution: solution.extend(__A ) else: while sublist: a_ : List[Any] = sublist.pop(0 ) for i, xx in enumerate(__A ): if not _operator(__A , __A ): solution.insert(__A , __A ) break else: solution.append(__A ) strand_sort(__A , __A , __A ) return solution if __name__ == "__main__": assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]
32
UpperCAmelCase_ : Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] UpperCAmelCase_ : str = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def SCREAMING_SNAKE_CASE_ ( __A : int , __A : int , __A : int ) -> str: """simple docstring""" assert len(str(__A ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: a_ : List[str] = year // 1_00 a_ : Optional[int] = (5 * (century % 4) + 2) % 7 a_ : List[str] = year % 1_00 a_ : str = centurian % 12 a_ : List[str] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 a_ : Any = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) a_ : Any = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
32
1
from __future__ import annotations import math import random from typing import Any class A__ : def __init__( self : Tuple ): '''simple docstring''' lowerCAmelCase__ : list[Any] = [] lowerCAmelCase__ : int = 0 lowerCAmelCase__ : int = 0 def _lowerCamelCase ( self : int ): '''simple docstring''' return self.head == self.tail def _lowerCamelCase ( self : Tuple , a : Any ): '''simple docstring''' self.data.append(a ) lowerCAmelCase__ : int = self.tail + 1 def _lowerCamelCase ( self : List[str] ): '''simple docstring''' lowerCAmelCase__ : Optional[int] = self.data[self.head] lowerCAmelCase__ : Optional[int] = self.head + 1 return ret def _lowerCamelCase ( self : List[str] ): '''simple docstring''' return self.tail - self.head def _lowerCamelCase ( self : Optional[int] ): '''simple docstring''' print(self.data ) print('**************' ) print(self.data[self.head : self.tail] ) class A__ : def __init__( self : List[Any] , a : Any ): '''simple docstring''' lowerCAmelCase__ : Optional[Any] = data lowerCAmelCase__ : MyNode | None = None lowerCAmelCase__ : MyNode | None = None lowerCAmelCase__ : int = 1 def _lowerCamelCase ( self : List[Any] ): '''simple docstring''' return self.data def _lowerCamelCase ( self : List[str] ): '''simple docstring''' return self.left def _lowerCamelCase ( self : Any ): '''simple docstring''' return self.right def _lowerCamelCase ( self : Optional[int] ): '''simple docstring''' return self.height def _lowerCamelCase ( self : List[Any] , a : Any ): '''simple docstring''' lowerCAmelCase__ : Optional[Any] = data def _lowerCamelCase ( self : List[Any] , a : MyNode | None ): '''simple docstring''' lowerCAmelCase__ : Optional[Any] = node def _lowerCamelCase ( self : List[str] , a : MyNode | None ): '''simple docstring''' lowerCAmelCase__ : List[str] = node def _lowerCamelCase ( self : List[Any] , a : int ): '''simple docstring''' lowerCAmelCase__ : Dict = height def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> int: if node is None: return 0 return node.get_height() def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int: if a > b: return a return b def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> MyNode: print('left rotation node:' , node.get_data() ) lowerCAmelCase__ : Optional[Any] = node.get_left() assert ret is not None node.set_left(ret.get_right() ) ret.set_right(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : Union[str, Any] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : Tuple = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(SCREAMING_SNAKE_CASE_ ) return ret def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> MyNode: print('right rotation node:' , node.get_data() ) lowerCAmelCase__ : str = node.get_right() assert ret is not None node.set_right(ret.get_left() ) ret.set_left(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : Optional[int] = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : Dict = my_max(get_height(ret.get_right() ) , get_height(ret.get_left() ) ) + 1 ret.set_height(SCREAMING_SNAKE_CASE_ ) return ret def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> MyNode: lowerCAmelCase__ : Any = node.get_left() assert left_child is not None node.set_left(left_rotation(SCREAMING_SNAKE_CASE_ ) ) return right_rotation(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> MyNode: lowerCAmelCase__ : Dict = node.get_right() assert right_child is not None node.set_right(right_rotation(SCREAMING_SNAKE_CASE_ ) ) return left_rotation(SCREAMING_SNAKE_CASE_ ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> MyNode | None: if node is None: return MyNode(SCREAMING_SNAKE_CASE_ ) if data < node.get_data(): node.set_left(insert_node(node.get_left() , SCREAMING_SNAKE_CASE_ ) ) if ( get_height(node.get_left() ) - get_height(node.get_right() ) == 2 ): # an unbalance detected lowerCAmelCase__ : Optional[int] = node.get_left() assert left_child is not None if ( data < left_child.get_data() ): # new node is the left child of the left child lowerCAmelCase__ : Tuple = right_rotation(SCREAMING_SNAKE_CASE_ ) else: lowerCAmelCase__ : str = lr_rotation(SCREAMING_SNAKE_CASE_ ) else: node.set_right(insert_node(node.get_right() , SCREAMING_SNAKE_CASE_ ) ) if get_height(node.get_right() ) - get_height(node.get_left() ) == 2: lowerCAmelCase__ : Tuple = node.get_right() assert right_child is not None if data < right_child.get_data(): lowerCAmelCase__ : Tuple = rl_rotation(SCREAMING_SNAKE_CASE_ ) else: lowerCAmelCase__ : Union[str, Any] = left_rotation(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : int = my_max(get_height(node.get_right() ) , get_height(node.get_left() ) ) + 1 node.set_height(SCREAMING_SNAKE_CASE_ ) return node def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> Any: while True: lowerCAmelCase__ : Optional[int] = root.get_right() if right_child is None: break lowerCAmelCase__ : Optional[Any] = right_child return root.get_data() def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ ) -> Any: while True: lowerCAmelCase__ : Tuple = root.get_left() if left_child is None: break lowerCAmelCase__ : List[Any] = left_child return root.get_data() def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> MyNode | None: lowerCAmelCase__ : str = root.get_left() lowerCAmelCase__ : Dict = root.get_right() if root.get_data() == data: if left_child is not None and right_child is not None: lowerCAmelCase__ : Union[str, Any] = get_left_most(SCREAMING_SNAKE_CASE_ ) root.set_data(SCREAMING_SNAKE_CASE_ ) root.set_right(del_node(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) elif left_child is not None: lowerCAmelCase__ : Optional[Any] = left_child elif right_child is not None: lowerCAmelCase__ : Optional[int] = right_child else: return None elif root.get_data() > data: if left_child is None: print('No such data' ) return root else: root.set_left(del_node(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) else: # root.get_data() < data if right_child is None: return root else: root.set_right(del_node(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) if get_height(SCREAMING_SNAKE_CASE_ ) - get_height(SCREAMING_SNAKE_CASE_ ) == 2: assert right_child is not None if get_height(right_child.get_right() ) > get_height(right_child.get_left() ): lowerCAmelCase__ : Dict = left_rotation(SCREAMING_SNAKE_CASE_ ) else: lowerCAmelCase__ : List[str] = rl_rotation(SCREAMING_SNAKE_CASE_ ) elif get_height(SCREAMING_SNAKE_CASE_ ) - get_height(SCREAMING_SNAKE_CASE_ ) == -2: assert left_child is not None if get_height(left_child.get_left() ) > get_height(left_child.get_right() ): lowerCAmelCase__ : Optional[int] = right_rotation(SCREAMING_SNAKE_CASE_ ) else: lowerCAmelCase__ : Dict = lr_rotation(SCREAMING_SNAKE_CASE_ ) lowerCAmelCase__ : str = my_max(get_height(root.get_right() ) , get_height(root.get_left() ) ) + 1 root.set_height(SCREAMING_SNAKE_CASE_ ) return root class A__ : def __init__( self : Any ): '''simple docstring''' lowerCAmelCase__ : MyNode | None = None def _lowerCamelCase ( self : Union[str, Any] ): '''simple docstring''' return get_height(self.root ) def _lowerCamelCase ( self : List[Any] , a : Any ): '''simple docstring''' print('insert:' + str(a ) ) lowerCAmelCase__ : Optional[Any] = insert_node(self.root , a ) def _lowerCamelCase ( self : Tuple , a : Any ): '''simple docstring''' print('delete:' + str(a ) ) if self.root is None: print('Tree is empty!' ) return lowerCAmelCase__ : List[str] = del_node(self.root , a ) def __str__( self : Dict , ): # a level traversale, gives a more intuitive look on the tree '''simple docstring''' lowerCAmelCase__ : int = '' lowerCAmelCase__ : int = MyQueue() q.push(self.root ) lowerCAmelCase__ : Any = self.get_height() if layer == 0: return output lowerCAmelCase__ : Optional[Any] = 0 while not q.is_empty(): lowerCAmelCase__ : Any = q.pop() lowerCAmelCase__ : str = ' ' * int(math.pow(2 , layer - 1 ) ) output += space if node is None: output += "*" q.push(a ) q.push(a ) else: output += str(node.get_data() ) q.push(node.get_left() ) q.push(node.get_right() ) output += space lowerCAmelCase__ : str = cnt + 1 for i in range(100 ): if cnt == math.pow(2 , a ) - 1: lowerCAmelCase__ : Dict = layer - 1 if layer == 0: output += "\n*************************************" return output output += "\n" break output += "\n*************************************" return output def lowerCAmelCase__ ( ) -> None: import doctest doctest.testmod() if __name__ == "__main__": _test() lowerCamelCase__ = AVLtree() lowerCamelCase__ = list(range(10)) random.shuffle(lst) for i in lst: t.insert(i) print(str(t)) random.shuffle(lst) for i in lst: t.del_node(i) print(str(t))
307
import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate lowerCamelCase__ = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow("""""", """|""", """|"""), datarow=DataRow("""""", """|""", """|"""), padding=1, with_header_hide=None, ) lowerCamelCase__ = [] lowerCamelCase__ = [] lowerCamelCase__ = {"""type""": """section""", """text""": {"""type""": """plain_text""", """text""": """No failed tests! 🤗""", """emoji""": True}} lowerCamelCase__ = [ { """type""": """header""", """text""": { """type""": """plain_text""", """text""": F"""🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results""", """emoji""": True, }, } ] lowerCamelCase__ = 0 for log in Path().glob("""*.log"""): lowerCamelCase__ = 0 with open(log, """r""") as f: for line in f: lowerCamelCase__ = json.loads(line) if line.get("""nodeid""", """""") != "": lowerCamelCase__ = line["""nodeid"""] if line.get("""duration""", None) is not None: lowerCamelCase__ = F"""{line["duration"]:.4f}""" if line.get("""outcome""", """""") == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split("""_""")[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) lowerCamelCase__ = [] log.unlink() lowerCamelCase__ = """""" lowerCamelCase__ = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += F"*{name[1:]}: {num_failed} failed test*\n" else: message += F"*{name[1:]}: {num_failed} failed tests*\n" lowerCamelCase__ = [] lowerCamelCase__ = {} for test in failed_tests: lowerCamelCase__ = test[0].split("""::""") lowerCamelCase__ = data[0].split("""/""")[-1] if data[0] not in filesafailed: lowerCamelCase__ = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) lowerCamelCase__ = [test[0] for test in failed_table] lowerCamelCase__ = list(set(files)) # Count number of instances in failed_tests lowerCamelCase__ = [] for file in individual_files: table.append([file, len(filesafailed[file])]) lowerCamelCase__ = tabulate( table, headers=["""Test Location""", """Num Failed"""], tablefmt=hf_table_format, stralign="""right""", ) message += F"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 3000: lowerCamelCase__ = """Too many failed tests, please see the full report in the Action results.""" lowerCamelCase__ = len(err) + 10 lowerCamelCase__ = message[: 3000 - offset] + F"""\n...\n```\n{err}""" print(F"""### {message}""") else: lowerCamelCase__ = """No failed tests! 🤗""" print(F"""## {message}""") payload.append(no_error_payload) if os.environ.get("""TEST_TYPE""", """""") != "": from slack_sdk import WebClient lowerCamelCase__ = WebClient(token=os.environ["""SLACK_API_TOKEN"""]) if message != "No failed tests! 🤗": lowerCamelCase__ = { """type""": """section""", """text""": { """type""": """mrkdwn""", """text""": message, }, } payload.append(md_report) lowerCamelCase__ = { """type""": """section""", """text""": { """type""": """mrkdwn""", """text""": """*For more details:*""", }, """accessory""": { """type""": """button""", """text""": { """type""": """plain_text""", """text""": """Check Action results""", """emoji""": True, }, """url""": F"""https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}""", }, } payload.append(action_button) lowerCamelCase__ = { """type""": """context""", """elements""": [ { """type""": """plain_text""", """text""": F"""Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}""", } ], } payload.append(date_report) lowerCamelCase__ = client.chat_postMessage(channel="""#accelerate-ci-daily""", text=message, blocks=payload) lowerCamelCase__ = response.data["""ts"""] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name lowerCamelCase__ = """""" for i, row in enumerate(test_failures): if row[0] != test_class: lowerCamelCase__ = row[0] else: lowerCamelCase__ = """""" lowerCamelCase__ = { """type""": """section""", """text""": { """type""": """mrkdwn""", """text""": F"""Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```""", }, } client.chat_postMessage( channel="""#accelerate-ci-daily""", thread_ts=ts, blocks=[payload], )
307
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING a__ : int = logging.get_logger(__name__) a__ : Optional[Any] = { '''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_ ( a__ ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = 'deformable_detr' __SCREAMING_SNAKE_CASE : Union[str, Any] = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self , _lowerCamelCase=True , _lowerCamelCase=None , _lowerCamelCase=3 , _lowerCamelCase=300 , _lowerCamelCase=1024 , _lowerCamelCase=6 , _lowerCamelCase=1024 , _lowerCamelCase=8 , _lowerCamelCase=6 , _lowerCamelCase=1024 , _lowerCamelCase=8 , _lowerCamelCase=0.0 , _lowerCamelCase=True , _lowerCamelCase="relu" , _lowerCamelCase=256 , _lowerCamelCase=0.1 , _lowerCamelCase=0.0 , _lowerCamelCase=0.0 , _lowerCamelCase=0.0_2 , _lowerCamelCase=1.0 , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase="sine" , _lowerCamelCase="resnet50" , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=4 , _lowerCamelCase=4 , _lowerCamelCase=4 , _lowerCamelCase=False , _lowerCamelCase=300 , _lowerCamelCase=False , _lowerCamelCase=1 , _lowerCamelCase=5 , _lowerCamelCase=2 , _lowerCamelCase=1 , _lowerCamelCase=1 , _lowerCamelCase=5 , _lowerCamelCase=2 , _lowerCamelCase=0.1 , _lowerCamelCase=0.2_5 , _lowerCamelCase=False , **_lowerCamelCase , ) ->Optional[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.''' ) SCREAMING_SNAKE_CASE : Dict = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(_lowerCamelCase , _lowerCamelCase ): SCREAMING_SNAKE_CASE : List[Any] = backbone_config.get('''model_type''' ) SCREAMING_SNAKE_CASE : Optional[Any] = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE : int = config_class.from_dict(_lowerCamelCase ) SCREAMING_SNAKE_CASE : str = use_timm_backbone SCREAMING_SNAKE_CASE : Optional[int] = backbone_config SCREAMING_SNAKE_CASE : Union[str, Any] = num_channels SCREAMING_SNAKE_CASE : Optional[Any] = num_queries SCREAMING_SNAKE_CASE : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[int] = d_model SCREAMING_SNAKE_CASE : str = encoder_ffn_dim SCREAMING_SNAKE_CASE : str = encoder_layers SCREAMING_SNAKE_CASE : str = encoder_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = decoder_ffn_dim SCREAMING_SNAKE_CASE : int = decoder_layers SCREAMING_SNAKE_CASE : Union[str, Any] = decoder_attention_heads SCREAMING_SNAKE_CASE : List[str] = dropout SCREAMING_SNAKE_CASE : Optional[int] = attention_dropout SCREAMING_SNAKE_CASE : str = activation_dropout SCREAMING_SNAKE_CASE : Optional[int] = activation_function SCREAMING_SNAKE_CASE : Optional[int] = init_std SCREAMING_SNAKE_CASE : List[str] = init_xavier_std SCREAMING_SNAKE_CASE : Optional[Any] = encoder_layerdrop SCREAMING_SNAKE_CASE : Union[str, Any] = auxiliary_loss SCREAMING_SNAKE_CASE : List[Any] = position_embedding_type SCREAMING_SNAKE_CASE : str = backbone SCREAMING_SNAKE_CASE : Dict = use_pretrained_backbone SCREAMING_SNAKE_CASE : Dict = dilation # deformable attributes SCREAMING_SNAKE_CASE : str = num_feature_levels SCREAMING_SNAKE_CASE : Optional[Any] = encoder_n_points SCREAMING_SNAKE_CASE : Any = decoder_n_points SCREAMING_SNAKE_CASE : str = two_stage SCREAMING_SNAKE_CASE : List[str] = two_stage_num_proposals SCREAMING_SNAKE_CASE : Dict = 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 SCREAMING_SNAKE_CASE : int = class_cost SCREAMING_SNAKE_CASE : Union[str, Any] = bbox_cost SCREAMING_SNAKE_CASE : Optional[int] = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE : Dict = mask_loss_coefficient SCREAMING_SNAKE_CASE : Union[str, Any] = dice_loss_coefficient SCREAMING_SNAKE_CASE : str = bbox_loss_coefficient SCREAMING_SNAKE_CASE : Tuple = giou_loss_coefficient SCREAMING_SNAKE_CASE : Optional[int] = eos_coefficient SCREAMING_SNAKE_CASE : Tuple = focal_alpha SCREAMING_SNAKE_CASE : Optional[int] = disable_custom_kernels super().__init__(is_encoder_decoder=_lowerCamelCase , **_lowerCamelCase ) @property def __lowerCAmelCase ( self ) ->int: return self.encoder_attention_heads @property def __lowerCAmelCase ( self ) ->int: return self.d_model def __lowerCAmelCase ( self ) ->Any: SCREAMING_SNAKE_CASE : str = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: SCREAMING_SNAKE_CASE : Optional[int] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE : Any = self.__class__.model_type return output
313
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def UpperCAmelCase_( a__ , a__=False ): """simple docstring""" SCREAMING_SNAKE_CASE : int = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""module.blocks.{i}.norm1.weight""", F"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""module.blocks.{i}.norm1.bias""", F"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append( (F"""module.blocks.{i}.attn.proj.weight""", F"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.attn.proj.bias""", F"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""module.blocks.{i}.norm2.weight""", F"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""module.blocks.{i}.norm2.bias""", F"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc1.weight""", F"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc1.bias""", F"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc2.weight""", F"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""module.blocks.{i}.mlp.fc2.bias""", F"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ('''module.cls_token''', '''vit.embeddings.cls_token'''), ('''module.patch_embed.proj.weight''', '''vit.embeddings.patch_embeddings.projection.weight'''), ('''module.patch_embed.proj.bias''', '''vit.embeddings.patch_embeddings.projection.bias'''), ('''module.pos_embed''', '''vit.embeddings.position_embeddings'''), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''module.norm.weight''', '''layernorm.weight'''), ('''module.norm.bias''', '''layernorm.bias'''), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE : Any = [(pair[0], pair[1][4:]) if pair[1].startswith('''vit''' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('''norm.weight''', '''vit.layernorm.weight'''), ('''norm.bias''', '''vit.layernorm.bias'''), ('''head.weight''', '''classifier.weight'''), ('''head.bias''', '''classifier.bias'''), ] ) return rename_keys def UpperCAmelCase_( a__ , a__ , a__=False ): """simple docstring""" for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE : Any = '''''' else: SCREAMING_SNAKE_CASE : Optional[int] = '''vit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(F"""module.blocks.{i}.attn.qkv.weight""" ) SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(F"""module.blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : List[str] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE : Any = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[-config.hidden_size :] def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = ['''head.weight''', '''head.bias'''] for k in ignore_keys: state_dict.pop(a__ , a__ ) def UpperCAmelCase_( a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = [ '''module.fc.fc1.weight''', '''module.fc.fc1.bias''', '''module.fc.bn1.weight''', '''module.fc.bn1.bias''', '''module.fc.bn1.running_mean''', '''module.fc.bn1.running_var''', '''module.fc.bn1.num_batches_tracked''', '''module.fc.fc2.weight''', '''module.fc.fc2.bias''', '''module.fc.bn2.weight''', '''module.fc.bn2.bias''', '''module.fc.bn2.running_mean''', '''module.fc.bn2.running_var''', '''module.fc.bn2.num_batches_tracked''', '''module.fc.fc3.weight''', '''module.fc.fc3.bias''', ] for k in ignore_keys: state_dict.pop(a__ , a__ ) def UpperCAmelCase_( a__ , a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : int = dct.pop(a__ ) SCREAMING_SNAKE_CASE : Optional[Any] = val def UpperCAmelCase_( a__ , a__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Any = ViTMSNConfig() SCREAMING_SNAKE_CASE : Optional[int] = 1_000 SCREAMING_SNAKE_CASE : str = '''datasets/huggingface/label-files''' SCREAMING_SNAKE_CASE : List[str] = '''imagenet-1k-id2label.json''' SCREAMING_SNAKE_CASE : Union[str, Any] = json.load(open(hf_hub_download(a__ , a__ ) , '''r''' ) ) SCREAMING_SNAKE_CASE : List[Any] = {int(a__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : str = idalabel SCREAMING_SNAKE_CASE : int = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: SCREAMING_SNAKE_CASE : Tuple = 384 SCREAMING_SNAKE_CASE : Any = 1_536 SCREAMING_SNAKE_CASE : List[str] = 6 elif "l16" in checkpoint_url: SCREAMING_SNAKE_CASE : Optional[int] = 1_024 SCREAMING_SNAKE_CASE : Optional[int] = 4_096 SCREAMING_SNAKE_CASE : Tuple = 24 SCREAMING_SNAKE_CASE : Union[str, Any] = 16 SCREAMING_SNAKE_CASE : Dict = 0.1 elif "b4" in checkpoint_url: SCREAMING_SNAKE_CASE : str = 4 elif "l7" in checkpoint_url: SCREAMING_SNAKE_CASE : Union[str, Any] = 7 SCREAMING_SNAKE_CASE : Union[str, Any] = 1_024 SCREAMING_SNAKE_CASE : List[Any] = 4_096 SCREAMING_SNAKE_CASE : List[Any] = 24 SCREAMING_SNAKE_CASE : Tuple = 16 SCREAMING_SNAKE_CASE : Union[str, Any] = 0.1 SCREAMING_SNAKE_CASE : Union[str, Any] = ViTMSNModel(a__ ) SCREAMING_SNAKE_CASE : Optional[int] = torch.hub.load_state_dict_from_url(a__ , map_location='''cpu''' )['''target_encoder'''] SCREAMING_SNAKE_CASE : Any = ViTImageProcessor(size=config.image_size ) remove_projection_head(a__ ) SCREAMING_SNAKE_CASE : Any = create_rename_keys(a__ , base_model=a__ ) for src, dest in rename_keys: rename_key(a__ , a__ , a__ ) read_in_q_k_v(a__ , a__ , base_model=a__ ) model.load_state_dict(a__ ) model.eval() SCREAMING_SNAKE_CASE : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' SCREAMING_SNAKE_CASE : Dict = Image.open(requests.get(a__ , stream=a__ ).raw ) SCREAMING_SNAKE_CASE : Optional[int] = ViTImageProcessor( size=config.image_size , image_mean=a__ , image_std=a__ ) SCREAMING_SNAKE_CASE : int = image_processor(images=a__ , return_tensors='''pt''' ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE : Tuple = model(**a__ ) SCREAMING_SNAKE_CASE : str = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[-1.0_915, -1.4_876, -1.1_809]] ) elif "b16" in checkpoint_url: SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[14.2_889, -18.9_045, 11.7_281]] ) elif "l16" in checkpoint_url: SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[41.5_028, -22.8_681, 45.6_475]] ) elif "b4" in checkpoint_url: SCREAMING_SNAKE_CASE : str = torch.tensor([[-4.3_868, 5.2_932, -0.4_137]] ) else: SCREAMING_SNAKE_CASE : List[str] = torch.tensor([[-0.1_792, -0.6_465, 2.4_263]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , a__ , atol=1e-4 ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(a__ ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(a__ ) if __name__ == "__main__": a__ : Dict = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--checkpoint_url''', default='''https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar''', type=str, help='''URL of the checkpoint you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) a__ : Any = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
313
1
from sklearn.metrics import fa_score import datasets _UpperCAmelCase : Optional[Any] = """ The F1 score is the harmonic mean of the precision and recall. It can be computed with the equation: F1 = 2 * (precision * recall) / (precision + recall) """ _UpperCAmelCase : Union[str, Any] = """ Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None. pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1. average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`. - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary. - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives. - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall. - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification). sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better. Examples: Example 1-A simple binary example >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0]) >>> print(results) {'f1': 0.5} Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0) >>> print(round(results['f1'], 2)) 0.67 Example 3-The same simple binary example as in Example 1, but with `sample_weight` included. >>> f1_metric = datasets.load_metric(\"f1\") >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3]) >>> print(round(results['f1'], 2)) 0.35 Example 4-A multiclass example, with different values for the `average` input. >>> predictions = [0, 2, 1, 0, 0, 1] >>> references = [0, 1, 2, 0, 1, 2] >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\") >>> print(round(results['f1'], 2)) 0.33 >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\") >>> print(round(results['f1'], 2)) 0.27 >>> results = f1_metric.compute(predictions=predictions, references=references, average=None) >>> print(results) {'f1': array([0.8, 0. , 0. ])} """ _UpperCAmelCase : str = """ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase ( datasets.Metric ): def a ( self ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'] , ) def a ( self , snake_case , snake_case , snake_case=None , snake_case=1 , snake_case="binary" , snake_case=None ): snake_case_ = fa_score( snake_case , snake_case , labels=snake_case , pos_label=snake_case , average=snake_case , sample_weight=snake_case ) return {"f1": float(snake_case ) if score.size == 1 else score}
200
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _UpperCAmelCase : Tuple = { """configuration_xlm_roberta_xl""": [ """XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMRobertaXLConfig""", """XLMRobertaXLOnnxConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCAmelCase : int = [ """XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMRobertaXLForCausalLM""", """XLMRobertaXLForMaskedLM""", """XLMRobertaXLForMultipleChoice""", """XLMRobertaXLForQuestionAnswering""", """XLMRobertaXLForSequenceClassification""", """XLMRobertaXLForTokenClassification""", """XLMRobertaXLModel""", """XLMRobertaXLPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMRobertaXLConfig, XLMRobertaXLOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm_roberta_xl import ( XLM_ROBERTA_XL_PRETRAINED_MODEL_ARCHIVE_LIST, XLMRobertaXLForCausalLM, XLMRobertaXLForMaskedLM, XLMRobertaXLForMultipleChoice, XLMRobertaXLForQuestionAnswering, XLMRobertaXLForSequenceClassification, XLMRobertaXLForTokenClassification, XLMRobertaXLModel, XLMRobertaXLPreTrainedModel, ) else: import sys _UpperCAmelCase : Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
200
1
import unittest from typing import Tuple import torch from diffusers.utils import floats_tensor, randn_tensor, torch_all_close, torch_device from diffusers.utils.testing_utils import require_torch @require_torch class __UpperCAmelCase : @property def __magic_name__ ( self : List[Any] ): return self.get_dummy_input() @property def __magic_name__ ( self : str ): if self.block_type == "down": return (4, 3_2, 1_6, 1_6) elif self.block_type == "mid": return (4, 3_2, 3_2, 3_2) elif self.block_type == "up": return (4, 3_2, 6_4, 6_4) raise ValueError(F'''\'{self.block_type}\' is not a supported block_type. Set it to \'up\', \'mid\', or \'down\'.''' ) def __magic_name__ ( self : Any, __A : Tuple=True, __A : Optional[int]=False, __A : Tuple=False, __A : Union[str, Any]=False, ): UpperCAmelCase : Optional[Any] = 4 UpperCAmelCase : int = 3_2 UpperCAmelCase : int = (3_2, 3_2) UpperCAmelCase : List[Any] = torch.manual_seed(0 ) UpperCAmelCase : Dict = torch.device(__A ) UpperCAmelCase : Union[str, Any] = (batch_size, num_channels) + sizes UpperCAmelCase : Tuple = randn_tensor(__A, generator=__A, device=__A ) UpperCAmelCase : Optional[Any] = {'''hidden_states''': hidden_states} if include_temb: UpperCAmelCase : Optional[int] = 1_2_8 UpperCAmelCase : Union[str, Any] = randn_tensor((batch_size, temb_channels), generator=__A, device=__A ) if include_res_hidden_states_tuple: UpperCAmelCase : Dict = torch.manual_seed(1 ) UpperCAmelCase : List[Any] = (randn_tensor(__A, generator=__A, device=__A ),) if include_encoder_hidden_states: UpperCAmelCase : Tuple = floats_tensor((batch_size, 3_2, 3_2) ).to(__A ) if include_skip_sample: UpperCAmelCase : Optional[int] = randn_tensor(((batch_size, 3) + sizes), generator=__A, device=__A ) return dummy_input def __magic_name__ ( self : List[Any] ): UpperCAmelCase : List[Any] = { '''in_channels''': 3_2, '''out_channels''': 3_2, '''temb_channels''': 1_2_8, } if self.block_type == "up": UpperCAmelCase : Optional[Any] = 3_2 if self.block_type == "mid": init_dict.pop('''out_channels''' ) UpperCAmelCase : Optional[int] = self.dummy_input return init_dict, inputs_dict def __magic_name__ ( self : str, __A : Dict ): UpperCAmelCase , UpperCAmelCase : Tuple = self.prepare_init_args_and_inputs_for_common() UpperCAmelCase : Optional[int] = self.block_class(**__A ) unet_block.to(__A ) unet_block.eval() with torch.no_grad(): UpperCAmelCase : Tuple = unet_block(**__A ) if isinstance(__A, __A ): UpperCAmelCase : int = output[0] self.assertEqual(output.shape, self.output_shape ) UpperCAmelCase : Optional[int] = output[0, -1, -3:, -3:] UpperCAmelCase : Union[str, Any] = torch.tensor(__A ).to(__A ) assert torch_all_close(output_slice.flatten(), __A, atol=5E-3 ) @unittest.skipIf(torch_device == '''mps''', '''Training is not supported in mps''' ) def __magic_name__ ( self : Any ): UpperCAmelCase , UpperCAmelCase : List[Any] = self.prepare_init_args_and_inputs_for_common() UpperCAmelCase : Any = self.block_class(**__A ) model.to(__A ) model.train() UpperCAmelCase : Tuple = model(**__A ) if isinstance(__A, __A ): UpperCAmelCase : Dict = output[0] UpperCAmelCase : List[str] = torch.device(__A ) UpperCAmelCase : str = randn_tensor(output.shape, device=__A ) UpperCAmelCase : Dict = torch.nn.functional.mse_loss(__A, __A ) loss.backward()
336
import argparse import collections import json from pathlib import Path import requests import torch import yaml from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( MobileViTImageProcessor, MobileViTVaConfig, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, ) from transformers.utils import logging logging.set_verbosity_info() _lowerCamelCase : Optional[int] = logging.get_logger(__name__) def a__ ( UpperCAmelCase : Union[str, Any] ) -> Optional[Any]: print('''Loading config file...''' ) def flatten_yaml_as_dict(UpperCAmelCase : Tuple , UpperCAmelCase : Any="" , UpperCAmelCase : Dict="." ): UpperCAmelCase : List[str] = [] for k, v in d.items(): UpperCAmelCase : List[Any] = parent_key + sep + k if parent_key else k if isinstance(UpperCAmelCase , collections.abc.MutableMapping ): items.extend(flatten_yaml_as_dict(UpperCAmelCase , UpperCAmelCase , sep=UpperCAmelCase ).items() ) else: items.append((new_key, v) ) return dict(UpperCAmelCase ) UpperCAmelCase : List[str] = argparse.Namespace() with open(UpperCAmelCase , '''r''' ) as yaml_file: try: UpperCAmelCase : List[str] = yaml.load(UpperCAmelCase , Loader=yaml.FullLoader ) UpperCAmelCase : Optional[int] = flatten_yaml_as_dict(UpperCAmelCase ) for k, v in flat_cfg.items(): setattr(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) except yaml.YAMLError as exc: logger.error('''Error while loading config file: {}. Error message: {}'''.format(UpperCAmelCase , str(UpperCAmelCase ) ) ) return config def a__ ( UpperCAmelCase : List[str] , UpperCAmelCase : int ) -> List[Any]: UpperCAmelCase : int = MobileViTVaConfig() UpperCAmelCase : str = False # dataset if task_name.startswith('''imagenet1k_''' ): UpperCAmelCase : Any = 1_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase : Any = 384 else: UpperCAmelCase : Tuple = 256 UpperCAmelCase : int = '''imagenet-1k-id2label.json''' elif task_name.startswith('''imagenet21k_to_1k_''' ): UpperCAmelCase : Optional[Any] = 21_000 if int(task_name.strip().split('''_''' )[-1] ) == 384: UpperCAmelCase : str = 384 else: UpperCAmelCase : Dict = 256 UpperCAmelCase : List[Any] = '''imagenet-22k-id2label.json''' elif task_name.startswith('''ade20k_''' ): UpperCAmelCase : Optional[Any] = 151 UpperCAmelCase : Tuple = 512 UpperCAmelCase : Tuple = '''ade20k-id2label.json''' UpperCAmelCase : Tuple = True elif task_name.startswith('''voc_''' ): UpperCAmelCase : Dict = 21 UpperCAmelCase : str = 512 UpperCAmelCase : Union[str, Any] = '''pascal-voc-id2label.json''' UpperCAmelCase : Dict = True # orig_config UpperCAmelCase : List[Any] = load_orig_config_file(UpperCAmelCase ) assert getattr(UpperCAmelCase , '''model.classification.name''' , -1 ) == "mobilevit_v2", "Invalid model" UpperCAmelCase : Tuple = getattr(UpperCAmelCase , '''model.classification.mitv2.width_multiplier''' , 1.0 ) assert ( getattr(UpperCAmelCase , '''model.classification.mitv2.attn_norm_layer''' , -1 ) == "layer_norm_2d" ), "Norm layers other than layer_norm_2d is not supported" UpperCAmelCase : int = getattr(UpperCAmelCase , '''model.classification.activation.name''' , '''swish''' ) # config.image_size == getattr(orig_config, 'sampler.bs.crop_size_width', 256) if is_segmentation_model: UpperCAmelCase : str = getattr(UpperCAmelCase , '''model.segmentation.output_stride''' , 16 ) if "_deeplabv3" in task_name: UpperCAmelCase : int = getattr(UpperCAmelCase , '''model.segmentation.deeplabv3.aspp_rates''' , [12, 24, 36] ) UpperCAmelCase : Any = getattr(UpperCAmelCase , '''model.segmentation.deeplabv3.aspp_out_channels''' , 512 ) UpperCAmelCase : Optional[Any] = getattr(UpperCAmelCase , '''model.segmentation.deeplabv3.aspp_dropout''' , 0.1 ) # id2label UpperCAmelCase : Union[str, Any] = '''huggingface/label-files''' UpperCAmelCase : List[Any] = json.load(open(hf_hub_download(UpperCAmelCase , UpperCAmelCase , repo_type='''dataset''' ) , '''r''' ) ) UpperCAmelCase : Any = {int(UpperCAmelCase ): v for k, v in idalabel.items()} UpperCAmelCase : int = idalabel UpperCAmelCase : Optional[int] = {v: k for k, v in idalabel.items()} return config def a__ ( UpperCAmelCase : Dict , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : Optional[int] ) -> List[str]: UpperCAmelCase : Union[str, Any] = dct.pop(UpperCAmelCase ) UpperCAmelCase : List[str] = val def a__ ( UpperCAmelCase : Union[str, Any] , UpperCAmelCase : int=False ) -> Union[str, Any]: if base_model: UpperCAmelCase : Dict = '''''' else: UpperCAmelCase : Dict = '''mobilevitv2.''' UpperCAmelCase : Optional[int] = [] for k in state_dict.keys(): if k[:8] == "encoder.": UpperCAmelCase : List[str] = k[8:] else: UpperCAmelCase : Dict = k if ".block." in k: UpperCAmelCase : List[Any] = k_new.replace('''.block.''' , '''.''' ) if ".conv." in k: UpperCAmelCase : Optional[int] = k_new.replace('''.conv.''' , '''.convolution.''' ) if ".norm." in k: UpperCAmelCase : List[str] = k_new.replace('''.norm.''' , '''.normalization.''' ) if "conv_1." in k: UpperCAmelCase : Union[str, Any] = k_new.replace('''conv_1.''' , f'''{model_prefix}conv_stem.''' ) for i in [1, 2]: if f'''layer_{i}.''' in k: UpperCAmelCase : Union[str, Any] = k_new.replace(f'''layer_{i}.''' , f'''{model_prefix}encoder.layer.{i-1}.layer.''' ) if ".exp_1x1." in k: UpperCAmelCase : Optional[Any] = k_new.replace('''.exp_1x1.''' , '''.expand_1x1.''' ) if ".red_1x1." in k: UpperCAmelCase : int = k_new.replace('''.red_1x1.''' , '''.reduce_1x1.''' ) for i in [3, 4, 5]: if f'''layer_{i}.0.''' in k: UpperCAmelCase : Any = k_new.replace(f'''layer_{i}.0.''' , f'''{model_prefix}encoder.layer.{i-1}.downsampling_layer.''' ) if f'''layer_{i}.1.local_rep.0.''' in k: UpperCAmelCase : str = k_new.replace(f'''layer_{i}.1.local_rep.0.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_kxk.''' ) if f'''layer_{i}.1.local_rep.1.''' in k: UpperCAmelCase : int = k_new.replace(f'''layer_{i}.1.local_rep.1.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_1x1.''' ) for i in [3, 4, 5]: if i == 3: UpperCAmelCase : Dict = [0, 1] elif i == 4: UpperCAmelCase : Dict = [0, 1, 2, 3] elif i == 5: UpperCAmelCase : int = [0, 1, 2] for j in j_in: if f'''layer_{i}.1.global_rep.{j}.''' in k: UpperCAmelCase : Optional[Any] = k_new.replace( f'''layer_{i}.1.global_rep.{j}.''' , f'''{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}.''' ) if f'''layer_{i}.1.global_rep.{j+1}.''' in k: UpperCAmelCase : Any = k_new.replace( f'''layer_{i}.1.global_rep.{j+1}.''' , f'''{model_prefix}encoder.layer.{i-1}.layernorm.''' ) if f'''layer_{i}.1.conv_proj.''' in k: UpperCAmelCase : Union[str, Any] = k_new.replace(f'''layer_{i}.1.conv_proj.''' , f'''{model_prefix}encoder.layer.{i-1}.conv_projection.''' ) if "pre_norm_attn.0." in k: UpperCAmelCase : Optional[int] = k_new.replace('''pre_norm_attn.0.''' , '''layernorm_before.''' ) if "pre_norm_attn.1." in k: UpperCAmelCase : Optional[Any] = k_new.replace('''pre_norm_attn.1.''' , '''attention.''' ) if "pre_norm_ffn.0." in k: UpperCAmelCase : List[Any] = k_new.replace('''pre_norm_ffn.0.''' , '''layernorm_after.''' ) if "pre_norm_ffn.1." in k: UpperCAmelCase : List[Any] = k_new.replace('''pre_norm_ffn.1.''' , '''ffn.conv1.''' ) if "pre_norm_ffn.3." in k: UpperCAmelCase : Any = k_new.replace('''pre_norm_ffn.3.''' , '''ffn.conv2.''' ) if "classifier.1." in k: UpperCAmelCase : Optional[int] = k_new.replace('''classifier.1.''' , '''classifier.''' ) if "seg_head." in k: UpperCAmelCase : Union[str, Any] = k_new.replace('''seg_head.''' , '''segmentation_head.''' ) if ".aspp_layer." in k: UpperCAmelCase : Tuple = k_new.replace('''.aspp_layer.''' , '''.''' ) if ".aspp_pool." in k: UpperCAmelCase : Optional[int] = k_new.replace('''.aspp_pool.''' , '''.''' ) rename_keys.append((k, k_new) ) return rename_keys def a__ ( UpperCAmelCase : Union[str, Any] ) -> Any: UpperCAmelCase : str = [] for k in state_dict.keys(): if k.startswith('''seg_head.aux_head.''' ): keys_to_ignore.append(UpperCAmelCase ) for k in keys_to_ignore: state_dict.pop(UpperCAmelCase , UpperCAmelCase ) def a__ ( ) -> Union[str, Any]: UpperCAmelCase : int = '''http://images.cocodataset.org/val2017/000000039769.jpg''' # url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg" UpperCAmelCase : List[str] = Image.open(requests.get(UpperCAmelCase , stream=UpperCAmelCase ).raw ) return im @torch.no_grad() def a__ ( UpperCAmelCase : int , UpperCAmelCase : int , UpperCAmelCase : Union[str, Any] , UpperCAmelCase : List[Any] ) -> Union[str, Any]: UpperCAmelCase : Union[str, Any] = get_mobilevitva_config(UpperCAmelCase , UpperCAmelCase ) # load original state_dict UpperCAmelCase : List[str] = torch.load(UpperCAmelCase , map_location='''cpu''' ) # load huggingface model if task_name.startswith('''ade20k_''' ) or task_name.startswith('''voc_''' ): UpperCAmelCase : str = MobileViTVaForSemanticSegmentation(UpperCAmelCase ).eval() UpperCAmelCase : str = False else: UpperCAmelCase : Union[str, Any] = MobileViTVaForImageClassification(UpperCAmelCase ).eval() UpperCAmelCase : Any = False # remove and rename some keys of load the original model UpperCAmelCase : Optional[Any] = checkpoint remove_unused_keys(UpperCAmelCase ) UpperCAmelCase : Optional[Any] = create_rename_keys(UpperCAmelCase , base_model=UpperCAmelCase ) for rename_key_src, rename_key_dest in rename_keys: rename_key(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) # load modified state_dict model.load_state_dict(UpperCAmelCase ) # Check outputs on an image, prepared by MobileViTImageProcessor UpperCAmelCase : Dict = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 32 ) UpperCAmelCase : Any = image_processor(images=prepare_img() , return_tensors='''pt''' ) UpperCAmelCase : Union[str, Any] = model(**UpperCAmelCase ) # verify classification model if task_name.startswith('''imagenet''' ): UpperCAmelCase : Optional[Any] = outputs.logits UpperCAmelCase : int = logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) if task_name.startswith('''imagenet1k_256''' ) and config.width_multiplier == 1.0: # expected_logits for base variant UpperCAmelCase : str = torch.tensor([-1.6_336E00, -7.3_204E-02, -5.1_883E-01] ) assert torch.allclose(logits[0, :3] , UpperCAmelCase , atol=1E-4 ) Path(UpperCAmelCase ).mkdir(exist_ok=UpperCAmelCase ) print(f'''Saving model {task_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCAmelCase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCAmelCase ) if __name__ == "__main__": _lowerCamelCase : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--task", default="imagenet1k_256", type=str, help=( "Name of the task for which the MobileViTV2 model you'd like to convert is trained on . " "\n Classification (ImageNet-1k)\n - MobileViTV2 (256x256) : imagenet1k_256\n - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384\n - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :\n imagenet21k_to_1k_256\n - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on\n ImageNet-1k 384x384) : imagenet21k_to_1k_384\n Segmentation\n - ADE20K Dataset : ade20k_deeplabv3\n - Pascal VOC 2012 Dataset: voc_deeplabv3\n " ), choices=[ "imagenet1k_256", "imagenet1k_384", "imagenet21k_to_1k_256", "imagenet21k_to_1k_384", "ade20k_deeplabv3", "voc_deeplabv3", ], ) parser.add_argument( "--orig_checkpoint_path", required=True, type=str, help="Path to the original state dict (.pt file)." ) parser.add_argument("--orig_config_path", required=True, type=str, help="Path to the original config file.") parser.add_argument( "--pytorch_dump_folder_path", required=True, type=str, help="Path to the output PyTorch model directory." ) _lowerCamelCase : Optional[int] = parser.parse_args() convert_mobilevitva_checkpoint( args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path )
336
1
import argparse from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline if __name__ == "__main__": UpperCAmelCase__ = argparse.ArgumentParser() parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""") parser.add_argument( """--txt2img_unclip""", default="""kakaobrain/karlo-v1-alpha""", type=str, required=False, help="""The pretrained txt2img unclip.""", ) UpperCAmelCase__ = parser.parse_args() UpperCAmelCase__ = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip) UpperCAmelCase__ = CLIPImageProcessor() UpperCAmelCase__ = CLIPVisionModelWithProjection.from_pretrained("""openai/clip-vit-large-patch14""") UpperCAmelCase__ = UnCLIPImageVariationPipeline( decoder=txtaimg.decoder, text_encoder=txtaimg.text_encoder, tokenizer=txtaimg.tokenizer, text_proj=txtaimg.text_proj, feature_extractor=feature_extractor, image_encoder=image_encoder, super_res_first=txtaimg.super_res_first, super_res_last=txtaimg.super_res_last, decoder_scheduler=txtaimg.decoder_scheduler, super_res_scheduler=txtaimg.super_res_scheduler, ) imgaimg.save_pretrained(args.dump_path)
365
"""simple docstring""" import copy from typing import TYPE_CHECKING, Any, Mapping, Optional, OrderedDict from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto.configuration_auto import AutoConfig if TYPE_CHECKING: from ... import PreTrainedTokenizerBase, TensorType UpperCAmelCase__ = logging.get_logger(__name__) class a ( lowerCAmelCase_ ): _snake_case : List[Any] = 'vision-encoder-decoder' _snake_case : Optional[int] = True def __init__( self : int , **__lowerCAmelCase : Any ): super().__init__(**__lowerCAmelCase ) if "encoder" not in kwargs or "decoder" not in kwargs: raise ValueError( f'''A configuraton of type {self.model_type} cannot be instantiated because ''' f'''not both `encoder` and `decoder` sub-configurations are passed, but only {kwargs}''' ) _UpperCAmelCase = kwargs.pop("""encoder""" ) _UpperCAmelCase = encoder_config.pop("""model_type""" ) _UpperCAmelCase = kwargs.pop("""decoder""" ) _UpperCAmelCase = decoder_config.pop("""model_type""" ) _UpperCAmelCase = AutoConfig.for_model(__lowerCAmelCase , **__lowerCAmelCase ) _UpperCAmelCase = AutoConfig.for_model(__lowerCAmelCase , **__lowerCAmelCase ) _UpperCAmelCase = True @classmethod def lowerCAmelCase_ ( cls : int , __lowerCAmelCase : PretrainedConfig , __lowerCAmelCase : PretrainedConfig , **__lowerCAmelCase : str ): logger.info("""Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config""" ) _UpperCAmelCase = True _UpperCAmelCase = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **__lowerCAmelCase ) def lowerCAmelCase_ ( self : int ): _UpperCAmelCase = copy.deepcopy(self.__dict__ ) _UpperCAmelCase = self.encoder.to_dict() _UpperCAmelCase = self.decoder.to_dict() _UpperCAmelCase = self.__class__.model_type return output class a ( lowerCAmelCase_ ): _snake_case : Union[str, Any] = version.parse('1.11' ) @property def lowerCAmelCase_ ( self : int ): return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def lowerCAmelCase_ ( self : Tuple ): return 1e-4 @property def lowerCAmelCase_ ( self : Dict ): return OrderedDict({"""last_hidden_state""": {0: """batch""", 1: """encoder_sequence"""}} ) class a ( lowerCAmelCase_ ): @property def lowerCAmelCase_ ( self : Any ): _UpperCAmelCase = OrderedDict() _UpperCAmelCase = {0: """batch""", 1: """past_decoder_sequence + sequence"""} _UpperCAmelCase = {0: """batch""", 1: """past_decoder_sequence + sequence"""} _UpperCAmelCase = {0: """batch""", 1: """encoder_sequence"""} return common_inputs def lowerCAmelCase_ ( self : Union[str, Any] , __lowerCAmelCase : "PreTrainedTokenizerBase" , __lowerCAmelCase : int = -1 , __lowerCAmelCase : int = -1 , __lowerCAmelCase : bool = False , __lowerCAmelCase : Optional["TensorType"] = None , ): import torch _UpperCAmelCase = OrderedDict() _UpperCAmelCase = super().generate_dummy_inputs( __lowerCAmelCase , batch_size=__lowerCAmelCase , seq_length=__lowerCAmelCase , is_pair=__lowerCAmelCase , framework=__lowerCAmelCase ) _UpperCAmelCase , _UpperCAmelCase = dummy_input["""input_ids"""].shape _UpperCAmelCase = (batch, encoder_sequence, self._config.encoder_hidden_size) _UpperCAmelCase = dummy_input.pop("""input_ids""" ) _UpperCAmelCase = dummy_input.pop("""attention_mask""" ) _UpperCAmelCase = torch.zeros(__lowerCAmelCase ) return common_inputs class a ( lowerCAmelCase_ ): @property def lowerCAmelCase_ ( self : Tuple ): pass def lowerCAmelCase_ ( self : List[Any] , __lowerCAmelCase : PretrainedConfig ): return VisionEncoderDecoderEncoderOnnxConfig(__lowerCAmelCase ) def lowerCAmelCase_ ( self : int , __lowerCAmelCase : PretrainedConfig , __lowerCAmelCase : PretrainedConfig , __lowerCAmelCase : str = "default" ): _UpperCAmelCase = encoder_config.hidden_size return VisionEncoderDecoderDecoderOnnxConfig(__lowerCAmelCase , __lowerCAmelCase )
30
0
import functools from typing import Any def _a ( a :str , a :list[str] ) -> bool: # Validation if not isinstance(a , a ) or len(a ) == 0: raise ValueError('''the string should be not empty string''' ) if not isinstance(a , a ) or not all( isinstance(a , a ) and len(a ) > 0 for item in words ): raise ValueError('''the words should be a list of non-empty strings''' ) # Build trie a = {} a = '''WORD_KEEPER''' for word in words: a = trie for c in word: if c not in trie_node: a = {} a = trie_node[c] a = True a = len(a ) # Dynamic programming method @functools.cache def is_breakable(a :int ) -> bool: if index == len_string: return True a = trie for i in range(a , a ): a = trie_node.get(string[i] , a ) if trie_node is None: return False if trie_node.get(a , a ) and is_breakable(i + 1 ): return True return False return is_breakable(0 ) if __name__ == "__main__": import doctest doctest.testmod()
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { '''camembert-base''': '''https://huggingface.co/camembert-base/resolve/main/config.json''', '''umberto-commoncrawl-cased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json''' ), '''umberto-wikipedia-uncased-v1''': ( '''https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json''' ), } class _snake_case ( a__ ): snake_case__ = "camembert" def __init__( self : Union[str, Any] , UpperCAmelCase : List[Any]=30522 , UpperCAmelCase : Optional[int]=768 , UpperCAmelCase : Union[str, Any]=12 , UpperCAmelCase : Tuple=12 , UpperCAmelCase : Tuple=3072 , UpperCAmelCase : int="gelu" , UpperCAmelCase : Optional[int]=0.1 , UpperCAmelCase : int=0.1 , UpperCAmelCase : Tuple=512 , UpperCAmelCase : Tuple=2 , UpperCAmelCase : int=0.0_2 , UpperCAmelCase : Tuple=1E-12 , UpperCAmelCase : Union[str, Any]=1 , UpperCAmelCase : int=0 , UpperCAmelCase : int=2 , UpperCAmelCase : str="absolute" , UpperCAmelCase : Dict=True , UpperCAmelCase : int=None , **UpperCAmelCase : List[str] , ): super().__init__(pad_token_id=UpperCAmelCase , bos_token_id=UpperCAmelCase , eos_token_id=UpperCAmelCase , **UpperCAmelCase ) __lowerCamelCase : Any = vocab_size __lowerCamelCase : Optional[int] = hidden_size __lowerCamelCase : int = num_hidden_layers __lowerCamelCase : int = num_attention_heads __lowerCamelCase : int = hidden_act __lowerCamelCase : Union[str, Any] = intermediate_size __lowerCamelCase : Optional[int] = hidden_dropout_prob __lowerCamelCase : List[Any] = attention_probs_dropout_prob __lowerCamelCase : Dict = max_position_embeddings __lowerCamelCase : Tuple = type_vocab_size __lowerCamelCase : Any = initializer_range __lowerCamelCase : str = layer_norm_eps __lowerCamelCase : List[Any] = position_embedding_type __lowerCamelCase : Dict = use_cache __lowerCamelCase : List[Any] = classifier_dropout class _snake_case ( a__ ): @property def lowerCamelCase__ ( self : int ): if self.task == "multiple-choice": __lowerCamelCase : List[str] = {0: "batch", 1: "choice", 2: "sequence"} else: __lowerCamelCase : Tuple = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
135
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from diffusers import ( DDIMScheduler, KandinskyVaaControlnetPipeline, 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 lowercase_ (lowerCamelCase__ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = KandinskyVaaControlnetPipeline SCREAMING_SNAKE_CASE : Any = ['image_embeds', 'negative_image_embeds', 'hint'] SCREAMING_SNAKE_CASE : str = ['image_embeds', 'negative_image_embeds', 'hint'] SCREAMING_SNAKE_CASE : List[Any] = [ 'generator', 'height', 'width', 'latents', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] SCREAMING_SNAKE_CASE : List[str] = False @property def SCREAMING_SNAKE_CASE ( self : List[str] ): return 3_2 @property def SCREAMING_SNAKE_CASE ( self : List[str] ): return 3_2 @property def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): return self.time_input_dim @property def SCREAMING_SNAKE_CASE ( self : int ): return self.time_input_dim * 4 @property def SCREAMING_SNAKE_CASE ( self : str ): return 1_0_0 @property def SCREAMING_SNAKE_CASE ( self : Any ): torch.manual_seed(0 ) __lowercase = { '''in_channels''': 8, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image_hint''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } __lowercase = UNetaDConditionModel(**lowercase__ ) return model @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): return { "block_out_channels": [3_2, 3_2, 6_4, 6_4], "down_block_types": [ "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "AttnDownEncoderBlock2D", ], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 1_2, "out_channels": 3, "up_block_types": ["AttnUpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"], "vq_embed_dim": 4, } @property def SCREAMING_SNAKE_CASE ( self : Tuple ): torch.manual_seed(0 ) __lowercase = VQModel(**self.dummy_movq_kwargs ) return model def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): __lowercase = self.dummy_unet __lowercase = self.dummy_movq __lowercase = DDIMScheduler( num_train_timesteps=1_0_0_0 ,beta_schedule='''linear''' ,beta_start=0.0_0_0_8_5 ,beta_end=0.0_1_2 ,clip_sample=lowercase__ ,set_alpha_to_one=lowercase__ ,steps_offset=1 ,prediction_type='''epsilon''' ,thresholding=lowercase__ ,) __lowercase = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def SCREAMING_SNAKE_CASE ( self : Dict ,lowercase__ : Optional[Any] ,lowercase__ : Any=0 ): __lowercase = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(lowercase__ ) ).to(lowercase__ ) __lowercase = floats_tensor((1, self.text_embedder_hidden_size) ,rng=random.Random(seed + 1 ) ).to( lowercase__ ) # create hint __lowercase = floats_tensor((1, 3, 6_4, 6_4) ,rng=random.Random(lowercase__ ) ).to(lowercase__ ) if str(lowercase__ ).startswith('''mps''' ): __lowercase = torch.manual_seed(lowercase__ ) else: __lowercase = torch.Generator(device=lowercase__ ).manual_seed(lowercase__ ) __lowercase = { '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''hint''': hint, '''generator''': generator, '''height''': 6_4, '''width''': 6_4, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): __lowercase = '''cpu''' __lowercase = self.get_dummy_components() __lowercase = self.pipeline_class(**lowercase__ ) __lowercase = pipe.to(lowercase__ ) pipe.set_progress_bar_config(disable=lowercase__ ) __lowercase = pipe(**self.get_dummy_inputs(lowercase__ ) ) __lowercase = output.images __lowercase = pipe( **self.get_dummy_inputs(lowercase__ ) ,return_dict=lowercase__ ,)[0] __lowercase = image[0, -3:, -3:, -1] __lowercase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) __lowercase = np.array( [0.6_9_5_9_8_2_6, 0.8_6_8_2_7_9, 0.7_5_5_8_0_9_2, 0.6_8_7_6_9_4_6_7, 0.8_5_8_0_5_8_0_4, 0.6_5_9_7_7_4_9_6, 0.4_4_8_8_5_3_0_2, 0.5_9_5_9_1_1_1, 0.4_2_5_1_5_9_5] ) 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 lowercase_ (unittest.TestCase ): """simple docstring""" def SCREAMING_SNAKE_CASE ( self : List[str] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE ( self : List[Any] ): __lowercase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_controlnet_robotcat_fp16.npy''' ) __lowercase = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/hint_image_cat.png''' ) __lowercase = torch.from_numpy(np.array(lowercase__ ) ).float() / 2_5_5.0 __lowercase = hint.permute(2 ,0 ,1 ).unsqueeze(0 ) __lowercase = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' ,torch_dtype=torch.floataa ) pipe_prior.to(lowercase__ ) __lowercase = KandinskyVaaControlnetPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-controlnet-depth''' ,torch_dtype=torch.floataa ) __lowercase = pipeline.to(lowercase__ ) pipeline.set_progress_bar_config(disable=lowercase__ ) __lowercase = '''A robot, 4k photo''' __lowercase = torch.Generator(device='''cuda''' ).manual_seed(0 ) __lowercase , __lowercase = pipe_prior( lowercase__ ,generator=lowercase__ ,num_inference_steps=5 ,negative_prompt='''''' ,).to_tuple() __lowercase = torch.Generator(device='''cuda''' ).manual_seed(0 ) __lowercase = pipeline( image_embeds=lowercase__ ,negative_image_embeds=lowercase__ ,hint=lowercase__ ,generator=lowercase__ ,num_inference_steps=1_0_0 ,output_type='''np''' ,) __lowercase = output.images[0] assert image.shape == (5_1_2, 5_1_2, 3) assert_mean_pixel_difference(lowercase__ ,lowercase__ )
355
'''simple docstring''' lowerCAmelCase__ = '''ABCDEFGHIJKLMNOPQRSTUVWXYZ''' def _A ( ): """simple docstring""" __lowercase = input('''Enter message: ''' ) __lowercase = input('''Enter key [alphanumeric]: ''' ) __lowercase = input('''Encrypt/Decrypt [e/d]: ''' ) if mode.lower().startswith('''e''' ): __lowercase = '''encrypt''' __lowercase = encrypt_message(A__ , A__ ) elif mode.lower().startswith('''d''' ): __lowercase = '''decrypt''' __lowercase = decrypt_message(A__ , A__ ) print(F"\n{mode.title()}ed message:" ) print(A__ ) def _A ( A__ , A__ ): """simple docstring""" return translate_message(A__ , A__ , '''encrypt''' ) def _A ( A__ , A__ ): """simple docstring""" return translate_message(A__ , A__ , '''decrypt''' ) def _A ( A__ , A__ , A__ ): """simple docstring""" __lowercase = [] __lowercase = 0 __lowercase = key.upper() for symbol in message: __lowercase = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(A__ ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(A__ ): __lowercase = 0 else: translated.append(A__ ) return "".join(A__ ) if __name__ == "__main__": main()
52
0
'''simple docstring''' 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 snake_case ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" _lowerCamelCase = StableUnCLIPPipeline _lowerCamelCase = TEXT_TO_IMAGE_PARAMS _lowerCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS _lowerCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS _lowerCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false _lowerCamelCase = False def snake_case ( self ): """simple docstring""" lowerCamelCase_ = 32 lowerCamelCase_ = embedder_hidden_size # prior components torch.manual_seed(0 ) lowerCamelCase_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) lowerCamelCase_ = CLIPTextModelWithProjection( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__UpperCAmelCase , projection_dim=__UpperCAmelCase , 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_ = PriorTransformer( num_attention_heads=2 , attention_head_dim=12 , embedding_dim=__UpperCAmelCase , num_layers=1 , ) torch.manual_seed(0 ) lowerCamelCase_ = DDPMScheduler( variance_type="fixed_small_log" , prediction_type="sample" , num_train_timesteps=1000 , clip_sample=__UpperCAmelCase , clip_sample_range=5.0 , beta_schedule="squaredcos_cap_v2" , ) # regular denoising components torch.manual_seed(0 ) lowerCamelCase_ = StableUnCLIPImageNormalizer(embedding_dim=__UpperCAmelCase ) lowerCamelCase_ = DDPMScheduler(beta_schedule="squaredcos_cap_v2" ) torch.manual_seed(0 ) lowerCamelCase_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) torch.manual_seed(0 ) lowerCamelCase_ = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__UpperCAmelCase , 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_ = 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=__UpperCAmelCase , layers_per_block=1 , upcast_attention=__UpperCAmelCase , use_linear_projection=__UpperCAmelCase , ) torch.manual_seed(0 ) lowerCamelCase_ = DDIMScheduler( beta_schedule="scaled_linear" , beta_start=0.00_085 , beta_end=0.012 , prediction_type="v_prediction" , set_alpha_to_one=__UpperCAmelCase , steps_offset=1 , ) torch.manual_seed(0 ) lowerCamelCase_ = AutoencoderKL() lowerCamelCase_ = { # 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 snake_case ( self , UpperCamelCase , UpperCamelCase=0 ): """simple docstring""" if str(__UpperCAmelCase ).startswith("mps" ): lowerCamelCase_ = torch.manual_seed(__UpperCAmelCase ) else: lowerCamelCase_ = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) lowerCamelCase_ = { """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 snake_case ( self ): """simple docstring""" lowerCamelCase_ = torch_device == """cpu""" self._test_attention_slicing_forward_pass(test_max_difference=__UpperCAmelCase ) def snake_case ( self ): """simple docstring""" lowerCamelCase_ = torch_device in ["""cpu""", """mps"""] self._test_inference_batch_single_identical(test_max_difference=__UpperCAmelCase ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): """simple docstring""" def snake_case ( self ): """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self ): """simple docstring""" lowerCamelCase_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" ) lowerCamelCase_ = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) # 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_ = torch.Generator(device="cpu" ).manual_seed(0 ) lowerCamelCase_ = pipe("anime turle" , generator=__UpperCAmelCase , output_type="np" ) lowerCamelCase_ = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase ) def snake_case ( self ): """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() lowerCamelCase_ = StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l" , torch_dtype=torch.floataa ) lowerCamelCase_ = pipe.to(__UpperCAmelCase ) pipe.set_progress_bar_config(disable=__UpperCAmelCase ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() lowerCamelCase_ = pipe( "anime turtle" , prior_num_inference_steps=2 , num_inference_steps=2 , output_type="np" , ) lowerCamelCase_ = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
55
'''simple docstring''' # coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script dumps information about the environment import os import sys import transformers _lowerCAmelCase = '''3''' print('''Python version:''', sys.version) print('''transformers version:''', transformers.__version__) try: import torch print('''Torch version:''', torch.__version__) print('''Cuda available:''', torch.cuda.is_available()) print('''Cuda version:''', torch.version.cuda) print('''CuDNN version:''', torch.backends.cudnn.version()) print('''Number of GPUs available:''', torch.cuda.device_count()) print('''NCCL version:''', torch.cuda.nccl.version()) except ImportError: print('''Torch version:''', None) try: import deepspeed print('''DeepSpeed version:''', deepspeed.__version__) except ImportError: print('''DeepSpeed version:''', None) try: import tensorflow as tf print('''TensorFlow version:''', tf.__version__) print('''TF GPUs available:''', bool(tf.config.list_physical_devices('''GPU'''))) print('''Number of TF GPUs available:''', len(tf.config.list_physical_devices('''GPU'''))) except ImportError: print('''TensorFlow version:''', None)
37
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase :int = { """configuration_nllb_moe""": [ """NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """NllbMoeConfig""", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase :int = [ """NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST""", """NllbMoeForConditionalGeneration""", """NllbMoeModel""", """NllbMoePreTrainedModel""", """NllbMoeTop2Router""", """NllbMoeSparseMLP""", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys __UpperCAmelCase :Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
352
'''simple docstring''' import os import sys import unittest __UpperCAmelCase :Optional[int] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path __UpperCAmelCase :Dict = os.path.join(git_repo_path, "src", "diffusers") class a ( unittest.TestCase ): """simple docstring""" def lowerCamelCase__ ( self : Any ) -> int: __UpperCAmelCase : Optional[Any] = find_backend(''' if not is_torch_available():''' ) self.assertEqual(snake_case , '''torch''' ) # backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") # self.assertEqual(backend_with_underscore, "tensorflow_text") __UpperCAmelCase : Union[str, Any] = find_backend(''' if not (is_torch_available() and is_transformers_available()):''' ) self.assertEqual(snake_case , '''torch_and_transformers''' ) # double_backend_with_underscore = find_backend( # " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" # ) # self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") __UpperCAmelCase : List[str] = find_backend( ''' if not (is_torch_available() and is_transformers_available() and is_onnx_available()):''' ) self.assertEqual(snake_case , '''torch_and_transformers_and_onnx''' ) def lowerCamelCase__ ( self : Optional[int] ) -> int: __UpperCAmelCase : Tuple = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('''torch''' , snake_case ) self.assertIn('''torch_and_transformers''' , snake_case ) self.assertIn('''flax_and_transformers''' , snake_case ) self.assertIn('''torch_and_transformers_and_onnx''' , snake_case ) # Likewise, we can't assert on the exact content of a key self.assertIn('''UNet2DModel''' , objects['''torch'''] ) self.assertIn('''FlaxUNet2DConditionModel''' , objects['''flax'''] ) self.assertIn('''StableDiffusionPipeline''' , objects['''torch_and_transformers'''] ) self.assertIn('''FlaxStableDiffusionPipeline''' , objects['''flax_and_transformers'''] ) self.assertIn('''LMSDiscreteScheduler''' , objects['''torch_and_scipy'''] ) self.assertIn('''OnnxStableDiffusionPipeline''' , objects['''torch_and_transformers_and_onnx'''] ) def lowerCamelCase__ ( self : Optional[int] ) -> List[Any]: __UpperCAmelCase : str = create_dummy_object('''CONSTANT''' , '''\'torch\'''' ) self.assertEqual(snake_case , '''\nCONSTANT = None\n''' ) __UpperCAmelCase : Union[str, Any] = create_dummy_object('''function''' , '''\'torch\'''' ) self.assertEqual( snake_case , '''\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n''' ) __UpperCAmelCase : Optional[int] = ''' class FakeClass(metaclass=DummyObject): _backends = \'torch\' def __init__(self, *args, **kwargs): requires_backends(self, \'torch\') @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, \'torch\') @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, \'torch\') ''' __UpperCAmelCase : Optional[Any] = create_dummy_object('''FakeClass''' , '''\'torch\'''' ) self.assertEqual(snake_case , snake_case ) def lowerCamelCase__ ( self : int ) -> List[Any]: __UpperCAmelCase : List[str] = '''# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, ["torch"]) class FakeClass(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) @classmethod def from_config(cls, *args, **kwargs): requires_backends(cls, ["torch"]) @classmethod def from_pretrained(cls, *args, **kwargs): requires_backends(cls, ["torch"]) ''' __UpperCAmelCase : Optional[int] = create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']} ) self.assertEqual(dummy_files['''torch'''] , snake_case )
240
0
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def __lowerCAmelCase ( UpperCamelCase__ ) -> Tuple: __lowerCamelCase = filter(lambda UpperCamelCase__ : p.requires_grad , model.parameters() ) __lowerCamelCase = sum([np.prod(p.size() ) for p in model_parameters] ) return params __UpperCAmelCase =logging.getLogger(__name__) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Optional[int]: if metric == "rouge2": __lowerCamelCase = '''{val_avg_rouge2:.4f}-{step_count}''' elif metric == "bleu": __lowerCamelCase = '''{val_avg_bleu:.4f}-{step_count}''' elif metric == "em": __lowerCamelCase = '''{val_avg_em:.4f}-{step_count}''' elif metric == "loss": __lowerCamelCase = '''{val_avg_loss:.4f}-{step_count}''' else: raise NotImplementedError( f"""seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this""" ''' function.''' ) __lowerCamelCase = ModelCheckpoint( dirpath=UpperCamelCase__ , filename=UpperCamelCase__ , monitor=f"""val_{metric}""" , mode='''max''' , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Optional[int]: return EarlyStopping( monitor=f"""val_{metric}""" , mode='''min''' if '''loss''' in metric else '''max''' , patience=UpperCamelCase__ , verbose=UpperCamelCase__ , ) class a__ ( pl.Callback ): def SCREAMING_SNAKE_CASE__ ( self : Any , a : str , a : List[Any] ): """simple docstring""" __lowerCamelCase = {f"""lr_group_{i}""": param['''lr'''] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(a ) @rank_zero_only def SCREAMING_SNAKE_CASE__ ( self : Dict , a : pl.Trainer , a : pl.LightningModule , a : str , a : List[Any]=True ): """simple docstring""" logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) __lowerCamelCase = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['''log''', '''progress_bar''', '''preds''']} ) # Log results __lowerCamelCase = Path(pl_module.hparams.output_dir ) if type_path == "test": __lowerCamelCase = od / '''test_results.txt''' __lowerCamelCase = od / '''test_generations.txt''' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. __lowerCamelCase = od / f"""{type_path}_results/{trainer.global_step:05d}.txt""" __lowerCamelCase = od / f"""{type_path}_generations/{trainer.global_step:05d}.txt""" results_file.parent.mkdir(exist_ok=a ) generations_file.parent.mkdir(exist_ok=a ) with open(a , '''a+''' ) as writer: for key in sorted(a ): if key in ["log", "progress_bar", "preds"]: continue __lowerCamelCase = metrics[key] if isinstance(a , torch.Tensor ): __lowerCamelCase = val.item() __lowerCamelCase = f"""{key}: {val:.6f}\n""" writer.write(a ) if not save_generations: return if "preds" in metrics: __lowerCamelCase = '''\n'''.join(metrics['''preds'''] ) generations_file.open('''w+''' ).write(a ) @rank_zero_only def SCREAMING_SNAKE_CASE__ ( self : str , a : Dict , a : List[str] ): """simple docstring""" try: __lowerCamelCase = pl_module.model.model.num_parameters() except AttributeError: __lowerCamelCase = pl_module.model.num_parameters() __lowerCamelCase = count_trainable_parameters(a ) # mp stands for million parameters trainer.logger.log_metrics({'''n_params''': npars, '''mp''': npars / 1e6, '''grad_mp''': n_trainable_pars / 1e6} ) @rank_zero_only def SCREAMING_SNAKE_CASE__ ( self : int , a : pl.Trainer , a : pl.LightningModule ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(a , a , '''test''' ) @rank_zero_only def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : pl.Trainer , a : Optional[int] ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
67
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer __UpperCAmelCase =["gpt2"] __UpperCAmelCase ="gpt2" if is_tf_available(): class a__ ( tf.Module ): def __init__( self : str , a : Union[str, Any] ): """simple docstring""" super().__init__() __lowerCamelCase = tokenizer __lowerCamelCase = AutoConfig.from_pretrained(a ) __lowerCamelCase = TFGPTaLMHeadModel.from_config(a ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name='''text''' ),) ) def SCREAMING_SNAKE_CASE__ ( self : str , a : Tuple ): """simple docstring""" __lowerCamelCase = self.tokenizer(a ) __lowerCamelCase = tokenized['''input_ids'''].to_tensor() __lowerCamelCase = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) __lowerCamelCase = self.model(input_ids=a , attention_mask=a )['''logits'''] return outputs @require_tf @require_keras_nlp class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" super().setUp() __lowerCamelCase = [GPTaTokenizer.from_pretrained(a ) for checkpoint in (TOKENIZER_CHECKPOINTS)] __lowerCamelCase = [TFGPTaTokenizer.from_pretrained(a ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __lowerCamelCase = [ '''This is a straightforward English test sentence.''', '''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''', '''Now we\'re going to add some Chinese: 一 二 三 一二三''', '''And some much more rare Chinese: 齉 堃 齉堃''', '''Je vais aussi écrire en français pour tester les accents''', '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''', ] __lowerCamelCase = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: __lowerCamelCase = tokenizer([test_inputs] , return_tensors='''tf''' ) __lowerCamelCase = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors __lowerCamelCase = python_outputs[key].numpy() __lowerCamelCase = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(a , tf.intaa ) == tf_outputs_values ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = tf.function(a ) for test_inputs in self.test_sentences: __lowerCamelCase = tf.constant(a ) __lowerCamelCase = compiled_tokenizer(a ) __lowerCamelCase = tf_tokenizer(a ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = ModelToSave(tokenizer=a ) __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = model.serving(a ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __lowerCamelCase = Path(a ) / '''saved.model''' tf.saved_model.save(a , a , signatures={'''serving_default''': model.serving} ) __lowerCamelCase = tf.saved_model.load(a ) __lowerCamelCase = 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 SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = tf_tokenizer(a ) # Build model with some sample inputs __lowerCamelCase = tf_tokenizer.get_config() __lowerCamelCase = TFGPTaTokenizer.from_config(a ) __lowerCamelCase = model_from_config(a ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" for tf_tokenizer in self.tf_tokenizers: # for the test to run __lowerCamelCase = 12_31_23 for max_length in [3, 5, 10_24]: __lowerCamelCase = tf.convert_to_tensor([self.test_sentences[0]] ) __lowerCamelCase = tf_tokenizer(a , max_length=a ) __lowerCamelCase = out['''input_ids'''].numpy().shape[1] assert out_length == max_length
67
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase__ :str = { "configuration_xlm": ["XLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLMConfig", "XLMOnnxConfig"], "tokenization_xlm": ["XLMTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ :Optional[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: lowercase__ :List[str] = [ "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 lowercase__ :List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
369
import numpy as np import datasets lowercase__ :Dict = "\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n" lowercase__ :List[Any] = "\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n" lowercase__ :Dict = "\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {'mahalanobis': array([0.5])}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowercase ( datasets.Metric ): def A__ ( self): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { '''X''': datasets.Sequence(datasets.Value('''float''' ,id='''sequence''') ,id='''X'''), }) ,) def A__ ( self ,A__ ,A__): # convert to numpy arrays lowercase = np.array(A__) lowercase = np.array(A__) # Assert that arrays are 2D if len(X.shape) != 2: raise ValueError('''Expected `X` to be a 2D vector''') if len(reference_distribution.shape) != 2: raise ValueError('''Expected `reference_distribution` to be a 2D vector''') if reference_distribution.shape[0] < 2: raise ValueError( '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension''') # Get mahalanobis distance for each prediction lowercase = X - np.mean(A__) lowercase = np.cov(reference_distribution.T) try: lowercase = np.linalg.inv(A__) except np.linalg.LinAlgError: lowercase = np.linalg.pinv(A__) lowercase = np.dot(A__ ,A__) lowercase = np.dot(A__ ,X_minus_mu.T).diagonal() return {"mahalanobis": mahal_dist}
97
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available a_ = {'configuration_speech_encoder_decoder': ['SpeechEncoderDecoderConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['SpeechEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['FlaxSpeechEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_speech_encoder_decoder import SpeechEncoderDecoderConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speech_encoder_decoder import SpeechEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_speech_encoder_decoder import FlaxSpeechEncoderDecoderModel else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
175
import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('.') def __lowercase ( lowerCamelCase : Any ): UpperCamelCase_ : Union[str, Any] = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got ' F"{test_file} instead." ) UpperCamelCase_ : str = components[-1] if not test_fn.endswith('py' ): raise ValueError(F"`test_file` should be a python file. Got {test_fn} instead." ) if not test_fn.startswith('test_modeling_' ): raise ValueError( F"`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead." ) UpperCamelCase_ : Union[str, Any] = components[:-1] + [test_fn.replace('.py' , '' )] UpperCamelCase_ : List[Any] = '.'.join(lowerCamelCase ) return test_module_path def __lowercase ( lowerCamelCase : Optional[Any] ): UpperCamelCase_ : List[Any] = get_module_path(lowerCamelCase ) UpperCamelCase_ : Union[str, Any] = importlib.import_module(lowerCamelCase ) return test_module def __lowercase ( lowerCamelCase : List[str] ): UpperCamelCase_ : int = [] UpperCamelCase_ : Tuple = get_test_module(lowerCamelCase ) for attr in dir(lowerCamelCase ): if attr.endswith('ModelTester' ): tester_classes.append(getattr(lowerCamelCase , lowerCamelCase ) ) # sort with class names return sorted(lowerCamelCase , key=lambda lowerCamelCase : x.__name__ ) def __lowercase ( lowerCamelCase : str ): UpperCamelCase_ : List[str] = [] UpperCamelCase_ : Union[str, Any] = get_test_module(lowerCamelCase ) for attr in dir(lowerCamelCase ): UpperCamelCase_ : Dict = getattr(lowerCamelCase , lowerCamelCase ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). UpperCamelCase_ : Optional[int] = getattr(lowerCamelCase , 'all_model_classes' , [] ) if len(lowerCamelCase ) > 0: test_classes.append(lowerCamelCase ) # sort with class names return sorted(lowerCamelCase , key=lambda lowerCamelCase : x.__name__ ) def __lowercase ( lowerCamelCase : Dict ): UpperCamelCase_ : int = get_test_classes(lowerCamelCase ) UpperCamelCase_ : List[Any] = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(lowerCamelCase , key=lambda lowerCamelCase : x.__name__ ) def __lowercase ( lowerCamelCase : Tuple ): UpperCamelCase_ : int = test_class() if hasattr(lowerCamelCase , 'setUp' ): test.setUp() UpperCamelCase_ : List[Any] = None if hasattr(lowerCamelCase , 'model_tester' ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: UpperCamelCase_ : Optional[Any] = test.model_tester.__class__ return model_tester def __lowercase ( lowerCamelCase : Tuple , lowerCamelCase : Dict ): UpperCamelCase_ : Optional[Any] = get_test_classes(lowerCamelCase ) UpperCamelCase_ : Tuple = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(lowerCamelCase ) # sort with class names return sorted(lowerCamelCase , key=lambda lowerCamelCase : x.__name__ ) def __lowercase ( lowerCamelCase : Any , lowerCamelCase : Tuple ): UpperCamelCase_ : List[Any] = get_test_classes_for_model(lowerCamelCase , lowerCamelCase ) UpperCamelCase_ : int = [] for test_class in test_classes: UpperCamelCase_ : Tuple = get_model_tester_from_test_class(lowerCamelCase ) if tester_class is not None: tester_classes.append(lowerCamelCase ) # sort with class names return sorted(lowerCamelCase , key=lambda lowerCamelCase : x.__name__ ) def __lowercase ( lowerCamelCase : str ): UpperCamelCase_ : Tuple = get_test_classes(lowerCamelCase ) UpperCamelCase_ : Tuple = {test_class: get_model_tester_from_test_class(lowerCamelCase ) for test_class in test_classes} return test_tester_mapping def __lowercase ( lowerCamelCase : Any ): UpperCamelCase_ : List[str] = get_model_classes(lowerCamelCase ) UpperCamelCase_ : int = { model_class: get_test_classes_for_model(lowerCamelCase , lowerCamelCase ) for model_class in model_classes } return model_test_mapping def __lowercase ( lowerCamelCase : Tuple ): UpperCamelCase_ : Tuple = get_model_classes(lowerCamelCase ) UpperCamelCase_ : Optional[Any] = { model_class: get_tester_classes_for_model(lowerCamelCase , lowerCamelCase ) for model_class in model_classes } return model_to_tester_mapping def __lowercase ( lowerCamelCase : Any ): if isinstance(lowerCamelCase , lowerCamelCase ): return o elif isinstance(lowerCamelCase , lowerCamelCase ): return o.__name__ elif isinstance(lowerCamelCase , (list, tuple) ): return [to_json(lowerCamelCase ) for x in o] elif isinstance(lowerCamelCase , lowerCamelCase ): return {to_json(lowerCamelCase ): to_json(lowerCamelCase ) for k, v in o.items()} else: return o
175
1
# this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys SCREAMING_SNAKE_CASE_ = subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') SCREAMING_SNAKE_CASE_ = subprocess.check_output(F'''git diff --name-only {fork_point_sha}'''.split()).decode('utf-8').split() SCREAMING_SNAKE_CASE_ = '|'.join(sys.argv[1:]) SCREAMING_SNAKE_CASE_ = re.compile(RF'''^({joined_dirs}).*?\.py$''') SCREAMING_SNAKE_CASE_ = [x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
189
import inspect import tempfile from collections import OrderedDict, UserDict from collections.abc import MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import fields from enum import Enum from typing import Any, ContextManager, List, Tuple import numpy as np from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy if is_flax_available(): import jax.numpy as jnp class a ( UpperCAmelCase ): def __get__( self , A_ , A_=None ): '''simple docstring''' if obj is None: return self if self.fget is None: raise AttributeError("unreadable attribute" ) _UpperCAmelCase : Optional[int] = "__cached_" + self.fget.__name__ _UpperCAmelCase : Union[str, Any] = getattr(A_ , A_ , A_ ) if cached is None: _UpperCAmelCase : Dict = self.fget(A_ ) setattr(A_ , A_ , A_ ) return cached def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[Any] ) -> int: _UpperCAmelCase : str = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(F'invalid truth value {val!r}' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> int: if is_torch_fx_proxy(lowerCAmelCase ): return True if is_torch_available(): import torch if isinstance(lowerCAmelCase , torch.Tensor ): return True if is_tf_available(): import tensorflow as tf if isinstance(lowerCAmelCase , tf.Tensor ): return True if is_flax_available(): import jax.numpy as jnp from jax.core import Tracer if isinstance(lowerCAmelCase , (jnp.ndarray, Tracer) ): return True return isinstance(lowerCAmelCase , np.ndarray ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> Dict: return isinstance(lowerCAmelCase , np.ndarray ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[Any] ) -> Any: return _is_numpy(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Tuple ) -> Optional[int]: import torch return isinstance(lowerCAmelCase , torch.Tensor ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> Optional[int]: return False if not is_torch_available() else _is_torch(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[Any] ) -> List[Any]: import torch return isinstance(lowerCAmelCase , torch.device ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: int ) -> Tuple: return False if not is_torch_available() else _is_torch_device(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[str] ) -> Tuple: import torch if isinstance(lowerCAmelCase , lowerCAmelCase ): if hasattr(lowerCAmelCase , lowerCAmelCase ): _UpperCAmelCase : Any = getattr(lowerCAmelCase , lowerCAmelCase ) else: return False return isinstance(lowerCAmelCase , torch.dtype ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> int: return False if not is_torch_available() else _is_torch_dtype(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[Any] ) -> Optional[Any]: import tensorflow as tf return isinstance(lowerCAmelCase , tf.Tensor ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: str ) -> Optional[Any]: return False if not is_tf_available() else _is_tensorflow(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[int] ) -> Any: import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(lowerCAmelCase , "is_symbolic_tensor" ): return tf.is_symbolic_tensor(lowerCAmelCase ) return type(lowerCAmelCase ) == tf.Tensor def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Tuple ) -> Optional[Any]: return False if not is_tf_available() else _is_tf_symbolic_tensor(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[Any] ) -> List[str]: import jax.numpy as jnp # noqa: F811 return isinstance(lowerCAmelCase , jnp.ndarray ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[Any] ) -> str: return False if not is_flax_available() else _is_jax(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: str ) -> Tuple: if isinstance(lowerCAmelCase , (dict, UserDict) ): return {k: to_py_obj(lowerCAmelCase ) for k, v in obj.items()} elif isinstance(lowerCAmelCase , (list, tuple) ): return [to_py_obj(lowerCAmelCase ) for o in obj] elif is_tf_tensor(lowerCAmelCase ): return obj.numpy().tolist() elif is_torch_tensor(lowerCAmelCase ): return obj.detach().cpu().tolist() elif is_jax_tensor(lowerCAmelCase ): return np.asarray(lowerCAmelCase ).tolist() elif isinstance(lowerCAmelCase , (np.ndarray, np.number) ): # tolist also works on 0d np arrays return obj.tolist() else: return obj def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[Any] ) -> List[Any]: if isinstance(lowerCAmelCase , (dict, UserDict) ): return {k: to_numpy(lowerCAmelCase ) for k, v in obj.items()} elif isinstance(lowerCAmelCase , (list, tuple) ): return np.array(lowerCAmelCase ) elif is_tf_tensor(lowerCAmelCase ): return obj.numpy() elif is_torch_tensor(lowerCAmelCase ): return obj.detach().cpu().numpy() elif is_jax_tensor(lowerCAmelCase ): return np.asarray(lowerCAmelCase ) else: return obj class a ( UpperCAmelCase ): def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : Optional[Any] = fields(self ) # Safety and consistency checks if not len(A_ ): raise ValueError(f'{self.__class__.__name__} has no fields.' ) if not all(field.default is None for field in class_fields[1:] ): raise ValueError(f'{self.__class__.__name__} should not have more than one required field.' ) _UpperCAmelCase : Any = getattr(self , class_fields[0].name ) _UpperCAmelCase : List[str] = all(getattr(self , field.name ) is None for field in class_fields[1:] ) if other_fields_are_none and not is_tensor(A_ ): if isinstance(A_ , A_ ): _UpperCAmelCase : Union[str, Any] = first_field.items() _UpperCAmelCase : Optional[int] = True else: try: _UpperCAmelCase : Tuple = iter(A_ ) _UpperCAmelCase : Any = True except TypeError: _UpperCAmelCase : str = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(A_ ): if ( not isinstance(A_ , (list, tuple) ) or not len(A_ ) == 2 or not isinstance(element[0] , A_ ) ): if idx == 0: # If we do not have an iterator of key/values, set it as attribute _UpperCAmelCase : str = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f'Cannot set key/value for {element}. It needs to be a tuple (key, value).' ) break setattr(self , element[0] , element[1] ) if element[1] is not None: _UpperCAmelCase : List[str] = element[1] elif first_field is not None: _UpperCAmelCase : Tuple = first_field else: for field in class_fields: _UpperCAmelCase : int = getattr(self , field.name ) if v is not None: _UpperCAmelCase : Union[str, Any] = v def __delitem__( self , *A_ , **A_ ): '''simple docstring''' raise Exception(f'You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.' ) def _UpperCAmelCase ( self , *A_ , **A_ ): '''simple docstring''' raise Exception(f'You cannot use ``setdefault`` on a {self.__class__.__name__} instance.' ) def _UpperCAmelCase ( self , *A_ , **A_ ): '''simple docstring''' raise Exception(f'You cannot use ``pop`` on a {self.__class__.__name__} instance.' ) def _UpperCAmelCase ( self , *A_ , **A_ ): '''simple docstring''' raise Exception(f'You cannot use ``update`` on a {self.__class__.__name__} instance.' ) def __getitem__( self , A_ ): '''simple docstring''' if isinstance(A_ , A_ ): _UpperCAmelCase : Optional[int] = dict(self.items() ) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__( self , A_ , A_ ): '''simple docstring''' if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(A_ , A_ ) super().__setattr__(A_ , A_ ) def __setitem__( self , A_ , A_ ): '''simple docstring''' super().__setitem__(A_ , A_ ) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(A_ , A_ ) def _UpperCAmelCase ( self ): '''simple docstring''' return tuple(self[k] for k in self.keys() ) class a ( UpperCAmelCase , UpperCAmelCase ): @classmethod def _UpperCAmelCase ( cls , A_ ): '''simple docstring''' raise ValueError( f'{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys() )}' ) class a ( UpperCAmelCase ): _lowercase = "longest" _lowercase = "max_length" _lowercase = "do_not_pad" class a ( UpperCAmelCase ): _lowercase = "pt" _lowercase = "tf" _lowercase = "np" _lowercase = "jax" class a : def __init__( self , A_ ): '''simple docstring''' _UpperCAmelCase : Tuple = context_managers _UpperCAmelCase : Dict = ExitStack() def __enter__( self ): '''simple docstring''' for context_manager in self.context_managers: self.stack.enter_context(A_ ) def __exit__( self , *A_ , **A_ ): '''simple docstring''' self.stack.__exit__(*A_ , **A_ ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: int ) -> Optional[Any]: _UpperCAmelCase : Optional[Any] = infer_framework(lowerCAmelCase ) if framework == "tf": _UpperCAmelCase : Union[str, Any] = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": _UpperCAmelCase : Optional[int] = inspect.signature(model_class.forward ) # PyTorch models else: _UpperCAmelCase : Dict = inspect.signature(model_class.__call__ ) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[str] ) -> List[str]: _UpperCAmelCase : List[Any] = model_class.__name__ _UpperCAmelCase : Dict = infer_framework(lowerCAmelCase ) if framework == "tf": _UpperCAmelCase : Dict = inspect.signature(model_class.call ) # TensorFlow models elif framework == "pt": _UpperCAmelCase : Dict = inspect.signature(model_class.forward ) # PyTorch models else: _UpperCAmelCase : Tuple = inspect.signature(model_class.__call__ ) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: MutableMapping , lowerCAmelCase: str = "" , lowerCAmelCase: str = "." ) -> List[Any]: def _flatten_dict(lowerCAmelCase: int , lowerCAmelCase: Tuple="" , lowerCAmelCase: List[str]="." ): for k, v in d.items(): _UpperCAmelCase : Optional[int] = str(lowerCAmelCase ) + delimiter + str(lowerCAmelCase ) if parent_key else k if v and isinstance(lowerCAmelCase , lowerCAmelCase ): yield from flatten_dict(lowerCAmelCase , lowerCAmelCase , delimiter=lowerCAmelCase ).items() else: yield key, v return dict(_flatten_dict(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) ) @contextmanager def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Union[str, Any] , lowerCAmelCase: bool = False ) -> List[Any]: if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Dict , lowerCAmelCase: Tuple=None ) -> List[str]: if is_numpy_array(lowerCAmelCase ): return np.transpose(lowerCAmelCase , axes=lowerCAmelCase ) elif is_torch_tensor(lowerCAmelCase ): return array.T if axes is None else array.permute(*lowerCAmelCase ) elif is_tf_tensor(lowerCAmelCase ): import tensorflow as tf return tf.transpose(lowerCAmelCase , perm=lowerCAmelCase ) elif is_jax_tensor(lowerCAmelCase ): return jnp.transpose(lowerCAmelCase , axes=lowerCAmelCase ) else: raise ValueError(F'Type not supported for transpose: {type(lowerCAmelCase )}.' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Optional[Any] , lowerCAmelCase: Any ) -> int: if is_numpy_array(lowerCAmelCase ): return np.reshape(lowerCAmelCase , lowerCAmelCase ) elif is_torch_tensor(lowerCAmelCase ): return array.reshape(*lowerCAmelCase ) elif is_tf_tensor(lowerCAmelCase ): import tensorflow as tf return tf.reshape(lowerCAmelCase , lowerCAmelCase ) elif is_jax_tensor(lowerCAmelCase ): return jnp.reshape(lowerCAmelCase , lowerCAmelCase ) else: raise ValueError(F'Type not supported for reshape: {type(lowerCAmelCase )}.' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: str , lowerCAmelCase: Union[str, Any]=None ) -> Union[str, Any]: if is_numpy_array(lowerCAmelCase ): return np.squeeze(lowerCAmelCase , axis=lowerCAmelCase ) elif is_torch_tensor(lowerCAmelCase ): return array.squeeze() if axis is None else array.squeeze(dim=lowerCAmelCase ) elif is_tf_tensor(lowerCAmelCase ): import tensorflow as tf return tf.squeeze(lowerCAmelCase , axis=lowerCAmelCase ) elif is_jax_tensor(lowerCAmelCase ): return jnp.squeeze(lowerCAmelCase , axis=lowerCAmelCase ) else: raise ValueError(F'Type not supported for squeeze: {type(lowerCAmelCase )}.' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Dict , lowerCAmelCase: List[str] ) -> Union[str, Any]: if is_numpy_array(lowerCAmelCase ): return np.expand_dims(lowerCAmelCase , lowerCAmelCase ) elif is_torch_tensor(lowerCAmelCase ): return array.unsqueeze(dim=lowerCAmelCase ) elif is_tf_tensor(lowerCAmelCase ): import tensorflow as tf return tf.expand_dims(lowerCAmelCase , axis=lowerCAmelCase ) elif is_jax_tensor(lowerCAmelCase ): return jnp.expand_dims(lowerCAmelCase , axis=lowerCAmelCase ) else: raise ValueError(F'Type not supported for expand_dims: {type(lowerCAmelCase )}.' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[Any] ) -> int: if is_numpy_array(lowerCAmelCase ): return np.size(lowerCAmelCase ) elif is_torch_tensor(lowerCAmelCase ): return array.numel() elif is_tf_tensor(lowerCAmelCase ): import tensorflow as tf return tf.size(lowerCAmelCase ) elif is_jax_tensor(lowerCAmelCase ): return array.size else: raise ValueError(F'Type not supported for expand_dims: {type(lowerCAmelCase )}.' ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: List[str] , lowerCAmelCase: List[Any] ) -> List[Any]: for key, value in auto_map.items(): if isinstance(lowerCAmelCase , (tuple, list) ): _UpperCAmelCase : List[Any] = [F'{repo_id}--{v}' if (v is not None and "--" not in v) else v for v in value] elif value is not None and "--" not in value: _UpperCAmelCase : Tuple = F'{repo_id}--{value}' return auto_map def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> List[Any]: for base_class in inspect.getmro(lowerCAmelCase ): _UpperCAmelCase : int = base_class.__module__ _UpperCAmelCase : Dict = base_class.__name__ if module.startswith("tensorflow" ) or module.startswith("keras" ) or name == "TFPreTrainedModel": return "tf" elif module.startswith("torch" ) or name == "PreTrainedModel": return "pt" elif module.startswith("flax" ) or module.startswith("jax" ) or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(F'Could not infer framework from class {model_class}.' )
189
1
"""simple docstring""" import os import string import sys __UpperCamelCase : Optional[Any] = 1 << 8 __UpperCamelCase : Dict = { '''tab''': ord('''\t'''), '''newline''': ord('''\r'''), '''esc''': 2_7, '''up''': 6_5 + ARROW_KEY_FLAG, '''down''': 6_6 + ARROW_KEY_FLAG, '''right''': 6_7 + ARROW_KEY_FLAG, '''left''': 6_8 + ARROW_KEY_FLAG, '''mod_int''': 9_1, '''undefined''': sys.maxsize, '''interrupt''': 3, '''insert''': 5_0, '''delete''': 5_1, '''pg_up''': 5_3, '''pg_down''': 5_4, } __UpperCamelCase : Tuple = KEYMAP['''up'''] __UpperCamelCase : List[str] = KEYMAP['''left'''] if sys.platform == "win32": __UpperCamelCase : Optional[int] = [] __UpperCamelCase : Optional[int] = { b'''\xe0H''': KEYMAP['''up'''] - ARROW_KEY_FLAG, b'''\x00H''': KEYMAP['''up'''] - ARROW_KEY_FLAG, b'''\xe0P''': KEYMAP['''down'''] - ARROW_KEY_FLAG, b'''\x00P''': KEYMAP['''down'''] - ARROW_KEY_FLAG, b'''\xe0M''': KEYMAP['''right'''] - ARROW_KEY_FLAG, b'''\x00M''': KEYMAP['''right'''] - ARROW_KEY_FLAG, b'''\xe0K''': KEYMAP['''left'''] - ARROW_KEY_FLAG, b'''\x00K''': KEYMAP['''left'''] - ARROW_KEY_FLAG, } for i in range(1_0): __UpperCamelCase : List[str] = ord(str(i)) def __SCREAMING_SNAKE_CASE ( ): if os.name == "nt": import msvcrt lowerCAmelCase__ : str = '''mbcs''' # Flush the keyboard buffer while msvcrt.kbhit(): msvcrt.getch() if len(A_ ) == 0: # Read the keystroke lowerCAmelCase__ : Optional[Any] = msvcrt.getch() # If it is a prefix char, get second part if ch in (b"\x00", b"\xe0"): lowerCAmelCase__ : Optional[int] = ch + msvcrt.getch() # Translate actual Win chars to bullet char types try: lowerCAmelCase__ : str = chr(WIN_KEYMAP[cha] ) WIN_CH_BUFFER.append(chr(KEYMAP['''mod_int'''] ) ) WIN_CH_BUFFER.append(A_ ) if ord(A_ ) in ( KEYMAP["insert"] - 1 << 9, KEYMAP["delete"] - 1 << 9, KEYMAP["pg_up"] - 1 << 9, KEYMAP["pg_down"] - 1 << 9, ): WIN_CH_BUFFER.append(chr(1_26 ) ) lowerCAmelCase__ : str = chr(KEYMAP['''esc'''] ) except KeyError: lowerCAmelCase__ : List[Any] = cha[1] else: lowerCAmelCase__ : int = ch.decode(A_ ) else: lowerCAmelCase__ : Optional[Any] = WIN_CH_BUFFER.pop(0 ) elif os.name == "posix": import termios import tty lowerCAmelCase__ : Optional[Any] = sys.stdin.fileno() lowerCAmelCase__ : List[Any] = termios.tcgetattr(A_ ) try: tty.setraw(A_ ) lowerCAmelCase__ : Tuple = sys.stdin.read(1 ) finally: termios.tcsetattr(A_ , termios.TCSADRAIN , A_ ) return ch def __SCREAMING_SNAKE_CASE ( ): lowerCAmelCase__ : Tuple = get_raw_chars() if ord(A_ ) in [KEYMAP["interrupt"], KEYMAP["newline"]]: return char elif ord(A_ ) == KEYMAP["esc"]: lowerCAmelCase__ : Optional[int] = get_raw_chars() if ord(A_ ) == KEYMAP["mod_int"]: lowerCAmelCase__ : Dict = get_raw_chars() if ord(A_ ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(A_ ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: return chr(ord(A_ ) + ARROW_KEY_FLAG ) else: return KEYMAP["undefined"] else: return get_raw_chars() else: if char in string.printable: return char else: return KEYMAP["undefined"]
106
"""simple docstring""" from typing import Optional from urllib.parse import quote import huggingface_hub as hfh from packaging import version def snake_case_ ( A_ : str, A_ : str, A_ : Optional[str] = None ): '''simple docstring''' if version.parse(hfh.__version__ ).release < version.parse('''0.11.0''' ).release: # old versions of hfh don't url-encode the file path _lowerCamelCase : Optional[Any] = quote(A_ ) return hfh.hf_hub_url(A_, A_, repo_type='''dataset''', revision=A_ )
72
0
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case_ ( UpperCamelCase__ ): A_ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) A_ = '''CIDAS/clipseg-rd64-refined''' A_ = '''image_segmenter''' A_ = CLIPSegForImageSegmentation A_ = ['''image''', '''text'''] A_ = ['''image'''] def __init__( self : List[str] , *_snake_case : Tuple , **_snake_case : str )->Dict: '''simple docstring''' requires_backends(self , ["""vision"""] ) super().__init__(*UpperCamelCase_ , **UpperCamelCase_ ) def UpperCAmelCase__ ( self : Optional[Any] , _snake_case : "Image" , _snake_case : str )->int: '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=UpperCamelCase_ , return_tensors="""pt""" ) def UpperCAmelCase__ ( self : Optional[int] , _snake_case : List[str] )->Optional[Any]: '''simple docstring''' with torch.no_grad(): __lowerCAmelCase : Optional[int] = self.model(**UpperCamelCase_ ).logits return logits def UpperCAmelCase__ ( self : Any , _snake_case : str )->Dict: '''simple docstring''' __lowerCAmelCase : str = outputs.cpu().detach().numpy() __lowerCAmelCase : Union[str, Any] = 0 __lowerCAmelCase : Union[str, Any] = 1 return Image.fromarray((array * 255).astype(np.uinta ) )
355
_UpperCAmelCase = {0: [2, 3], 1: [0], 2: [1], 3: [4], 4: []} _UpperCAmelCase = {0: [1, 2, 3], 1: [2], 2: [0], 3: [4], 4: [5], 5: [3]} def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :dict[int, list[int]] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :list[bool] ) -> list[int]: __lowerCAmelCase : str = True __lowerCAmelCase : str = [] for neighbour in graph[vert]: if not visited[neighbour]: order += topology_sort(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) order.append(SCREAMING_SNAKE_CASE ) return order def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :dict[int, list[int]] , SCREAMING_SNAKE_CASE :int , SCREAMING_SNAKE_CASE :list[bool] ) -> list[int]: __lowerCAmelCase : Optional[Any] = True __lowerCAmelCase : Union[str, Any] = [vert] for neighbour in reversed_graph[vert]: if not visited[neighbour]: component += find_components(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return component def _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE :dict[int, list[int]] ) -> list[list[int]]: __lowerCAmelCase : Optional[Any] = len(SCREAMING_SNAKE_CASE ) * [False] __lowerCAmelCase : dict[int, list[int]] = {vert: [] for vert in range(len(SCREAMING_SNAKE_CASE ) )} for vert, neighbours in graph.items(): for neighbour in neighbours: reversed_graph[neighbour].append(SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Tuple = [] for i, was_visited in enumerate(SCREAMING_SNAKE_CASE ): if not was_visited: order += topology_sort(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) __lowerCAmelCase : Optional[Any] = [] __lowerCAmelCase : Any = len(SCREAMING_SNAKE_CASE ) * [False] for i in range(len(SCREAMING_SNAKE_CASE ) ): __lowerCAmelCase : Optional[int] = order[len(SCREAMING_SNAKE_CASE ) - i - 1] if not visited[vert]: __lowerCAmelCase : Any = find_components(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) components_list.append(SCREAMING_SNAKE_CASE ) return components_list
232
0
from __future__ import annotations __UpperCAmelCase = [-10, -5, 0, 5, 5.1, 11, 13, 21, 3, 4, -21, -10, -5, -1, 0] __UpperCAmelCase = [-5, 0, 5, 5.1, 11, 13, 21, -1, 4, -1, -10, -5, -1, 0, -1] def A__ ( __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = len(__lowerCamelCase ) for i in range(__lowerCamelCase ): SCREAMING_SNAKE_CASE_ = -1 for j in range(i + 1, __lowerCamelCase ): if arr[i] < arr[j]: SCREAMING_SNAKE_CASE_ = arr[j] break result.append(__lowerCamelCase ) return result def A__ ( __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = [] for i, outer in enumerate(__lowerCamelCase ): SCREAMING_SNAKE_CASE_ = -1 for inner in arr[i + 1 :]: if outer < inner: SCREAMING_SNAKE_CASE_ = inner break result.append(__lowerCamelCase ) return result def A__ ( __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = len(__lowerCamelCase ) SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [-1] * arr_size for index in reversed(range(__lowerCamelCase ) ): if stack: while stack[-1] <= arr[index]: stack.pop() if not stack: break if stack: SCREAMING_SNAKE_CASE_ = 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)) __UpperCAmelCase = ( "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), )
299
def A__ ( __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = { '''^''': 3, '''*''': 2, '''/''': 2, '''%''': 2, '''+''': 1, '''-''': 1, } # Priority of each operator SCREAMING_SNAKE_CASE_ = len(__lowerCamelCase ) if (len(__lowerCamelCase ) > 7) else 7 # Print table header for output print( '''Symbol'''.center(8 ), '''Stack'''.center(__lowerCamelCase ), '''Postfix'''.center(__lowerCamelCase ), sep=''' | ''', ) print('''-''' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(__lowerCamelCase ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(__lowerCamelCase ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(__lowerCamelCase ) == 0: stack.append(__lowerCamelCase ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(__lowerCamelCase ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(__lowerCamelCase ) # push x to stack print( x.center(8 ), (''''''.join(__lowerCamelCase )).ljust(__lowerCamelCase ), (''''''.join(__lowerCamelCase )).ljust(__lowerCamelCase ), sep=''' | ''', ) # Output in tabular format while len(__lowerCamelCase ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ''' '''.center(8 ), (''''''.join(__lowerCamelCase )).ljust(__lowerCamelCase ), (''''''.join(__lowerCamelCase )).ljust(__lowerCamelCase ), sep=''' | ''', ) # Output in tabular format return "".join(__lowerCamelCase ) # return Postfix as str def A__ ( __lowerCamelCase ): SCREAMING_SNAKE_CASE_ = list(infix[::-1] ) # reverse the infix equation for i in range(len(__lowerCamelCase ) ): if infix[i] == "(": SCREAMING_SNAKE_CASE_ = ''')''' # change "(" to ")" elif infix[i] == ")": SCREAMING_SNAKE_CASE_ = '''(''' # change ")" to "(" return (infix_2_postfix(''''''.join(__lowerCamelCase ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": __UpperCAmelCase = input("\nEnter an Infix Equation = ") # Input an Infix equation __UpperCAmelCase = "".join(Infix.split()) # Remove spaces from the input print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
299
1
"""simple docstring""" import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process __snake_case : Optional[int] = logging.getLogger(__name__) __snake_case : Optional[int] = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) __snake_case : List[Any] = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class A__ : '''simple docstring''' SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.' ) } , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(__SCREAMING_SNAKE_CASE )} , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'Override some existing default config settings when a model is trained from scratch. Example: ' 'n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index' ) } , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'} , ) SCREAMING_SNAKE_CASE = field( default='main' , metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'} , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'Will use the token generated when running `huggingface-cli login` (necessary to use this script ' 'with private models).' ) } , ) def _SCREAMING_SNAKE_CASE ( self: Tuple) -> Tuple: """simple docstring""" if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( "--config_overrides can't be used in combination with --config_name or --model_name_or_path") @dataclass class A__ : '''simple docstring''' SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'The name of the dataset to use (via the datasets library).'} ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'} ) SCREAMING_SNAKE_CASE = field(default=__SCREAMING_SNAKE_CASE , metadata={'help': 'The input training data file (a text file).'} ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'} , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'An optional input train ref data file for whole word masking in Chinese.'} , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'An optional input validation ref data file for whole word masking in Chinese.'} , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'Overwrite the cached training and evaluation sets'} ) SCREAMING_SNAKE_CASE = field( default=5 , metadata={ 'help': 'The percentage of the train set used as validation set in case there\'s no validation split' } , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated. Default to the max input length of the model.' ) } , ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , metadata={'help': 'The number of processes to use for the preprocessing.'} , ) SCREAMING_SNAKE_CASE = field( default=0.15 , metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'} ) SCREAMING_SNAKE_CASE = field( default=__SCREAMING_SNAKE_CASE , 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.' ) } , ) def _SCREAMING_SNAKE_CASE ( self: List[Any]) -> List[Any]: """simple docstring""" if self.train_file is not None: __lowerCAmelCase : Union[str, Any] = self.train_file.split(".")[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: __lowerCAmelCase : List[Any] = self.validation_file.split(".")[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def _lowercase ( __snake_case ,__snake_case ) -> int: with open(__snake_case ,"r" ,encoding="utf-8" ) as f: __lowerCAmelCase : List[str] = [json.loads(__snake_case ) for line in f.read().splitlines() if (len(__snake_case ) > 0 and not line.isspace())] assert len(__snake_case ) == len(__snake_case ) __lowerCAmelCase : Tuple = {c: dataset[c] for c in dataset.column_names} __lowerCAmelCase : List[str] = refs return Dataset.from_dict(__snake_case ) def _lowercase ( ) -> Tuple: # 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) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : str = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Union[str, Any] = parser.parse_args_into_dataclasses() # Detecting last checkpoint. __lowerCAmelCase : Tuple = 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." ) # 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 )] ,) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # 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}""" ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("Training/evaluation parameters %s" ,__snake_case ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. __lowerCAmelCase : Dict = load_dataset(data_args.dataset_name ,data_args.dataset_config_name ) if "validation" not in datasets.keys(): __lowerCAmelCase : List[Any] = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=F"""train[:{data_args.validation_split_percentage}%]""" ,) __lowerCAmelCase : Optional[Any] = load_dataset( data_args.dataset_name ,data_args.dataset_config_name ,split=F"""train[{data_args.validation_split_percentage}%:]""" ,) else: __lowerCAmelCase : int = {} if data_args.train_file is not None: __lowerCAmelCase : Dict = data_args.train_file if data_args.validation_file is not None: __lowerCAmelCase : List[Any] = data_args.validation_file __lowerCAmelCase : Tuple = data_args.train_file.split("." )[-1] if extension == "txt": __lowerCAmelCase : int = "text" __lowerCAmelCase : str = load_dataset(__snake_case ,data_files=__snake_case ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __lowerCAmelCase : Union[str, Any] = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name: __lowerCAmelCase : Union[str, Any] = AutoConfig.from_pretrained(model_args.config_name ,**__snake_case ) elif model_args.model_name_or_path: __lowerCAmelCase : int = AutoConfig.from_pretrained(model_args.model_name_or_path ,**__snake_case ) else: __lowerCAmelCase : Dict = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch." ) if model_args.config_overrides is not None: logger.info(F"""Overriding config: {model_args.config_overrides}""" ) config.update_from_string(model_args.config_overrides ) logger.info(F"""New config: {config}""" ) __lowerCAmelCase : Optional[Any] = { "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, } if model_args.tokenizer_name: __lowerCAmelCase : Any = AutoTokenizer.from_pretrained(model_args.tokenizer_name ,**__snake_case ) elif model_args.model_name_or_path: __lowerCAmelCase : Any = AutoTokenizer.from_pretrained(model_args.model_name_or_path ,**__snake_case ) else: raise ValueError( "You are instantiating a new tokenizer from scratch. This is not supported by this script." "You can do it from another script, save it, and load it from here, using --tokenizer_name." ) if model_args.model_name_or_path: __lowerCAmelCase : Dict = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path ,from_tf=bool(".ckpt" in model_args.model_name_or_path ) ,config=__snake_case ,cache_dir=model_args.cache_dir ,revision=model_args.model_revision ,use_auth_token=True if model_args.use_auth_token else None ,) else: logger.info("Training new model from scratch" ) __lowerCAmelCase : Optional[int] = AutoModelForMaskedLM.from_config(__snake_case ) model.resize_token_embeddings(len(__snake_case ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: __lowerCAmelCase : Any = datasets["train"].column_names else: __lowerCAmelCase : Optional[int] = datasets["validation"].column_names __lowerCAmelCase : Dict = "text" if "text" in column_names else column_names[0] __lowerCAmelCase : Union[str, Any] = "max_length" if data_args.pad_to_max_length else False def tokenize_function(__snake_case ): # Remove empty lines __lowerCAmelCase : Union[str, Any] = [line for line in examples["text"] if len(__snake_case ) > 0 and not line.isspace()] return tokenizer(examples["text"] ,padding=__snake_case ,truncation=__snake_case ,max_length=data_args.max_seq_length ) __lowerCAmelCase : Dict = datasets.map( __snake_case ,batched=__snake_case ,num_proc=data_args.preprocessing_num_workers ,remove_columns=[text_column_name] ,load_from_cache_file=not data_args.overwrite_cache ,) # Add the chinese references if provided if data_args.train_ref_file is not None: __lowerCAmelCase : str = add_chinese_references(tokenized_datasets["train"] ,data_args.train_ref_file ) if data_args.validation_ref_file is not None: __lowerCAmelCase : int = add_chinese_references( tokenized_datasets["validation"] ,data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer __lowerCAmelCase : List[str] = data_args.train_ref_file or data_args.validation_ref_file if has_ref: __lowerCAmelCase : List[Any] = False # Data collator # This one will take care of randomly masking the tokens. __lowerCAmelCase : List[Any] = DataCollatorForWholeWordMask(tokenizer=__snake_case ,mlm_probability=data_args.mlm_probability ) # Initialize our Trainer __lowerCAmelCase : Union[str, Any] = Trainer( model=__snake_case ,args=__snake_case ,train_dataset=tokenized_datasets["train"] if training_args.do_train else None ,eval_dataset=tokenized_datasets["validation"] if training_args.do_eval else None ,tokenizer=__snake_case ,data_collator=__snake_case ,) # Training if training_args.do_train: if last_checkpoint is not None: __lowerCAmelCase : List[str] = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): __lowerCAmelCase : Optional[int] = model_args.model_name_or_path else: __lowerCAmelCase : Optional[int] = None __lowerCAmelCase : List[str] = trainer.train(resume_from_checkpoint=__snake_case ) trainer.save_model() # Saves the tokenizer too for easy upload __lowerCAmelCase : int = os.path.join(training_args.output_dir ,"train_results.txt" ) if trainer.is_world_process_zero(): with open(__snake_case ,"w" ) as writer: logger.info("***** Train results *****" ) for key, value in sorted(train_result.metrics.items() ): logger.info(F""" {key} = {value}""" ) writer.write(F"""{key} = {value}\n""" ) # 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" ) ) # Evaluation __lowerCAmelCase : Optional[int] = {} if training_args.do_eval: logger.info("*** Evaluate ***" ) __lowerCAmelCase : int = trainer.evaluate() __lowerCAmelCase : Optional[Any] = math.exp(eval_output["eval_loss"] ) __lowerCAmelCase : Dict = perplexity __lowerCAmelCase : Union[str, Any] = os.path.join(training_args.output_dir ,"eval_results_mlm_wwm.txt" ) if trainer.is_world_process_zero(): with open(__snake_case ,"w" ) as writer: logger.info("***** Eval results *****" ) for key, value in sorted(results.items() ): logger.info(F""" {key} = {value}""" ) writer.write(F"""{key} = {value}\n""" ) return results def _lowercase ( __snake_case ) -> Tuple: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
58
"""simple docstring""" from __future__ import annotations from bisect import bisect_left from functools import total_ordering from heapq import merge @total_ordering class A__ ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __lt__( self: List[Any] , _SCREAMING_SNAKE_CASE: Union[str, Any]) -> Dict: """simple docstring""" return self[-1] < other[-1] def __eq__( self: int , _SCREAMING_SNAKE_CASE: Any) -> Tuple: """simple docstring""" return self[-1] == other[-1] def _lowercase ( __snake_case ) -> list: __lowerCAmelCase : list[Stack] = [] # sort into stacks for element in collection: __lowerCAmelCase : Dict = Stack([element] ) __lowerCAmelCase : str = bisect_left(__snake_case ,__snake_case ) if i != len(__snake_case ): stacks[i].append(__snake_case ) else: stacks.append(__snake_case ) # use a heap-based merge to merge stack efficiently __lowerCAmelCase : Union[str, Any] = merge(*(reversed(__snake_case ) for stack in stacks) ) return collection if __name__ == "__main__": __snake_case : Union[str, Any] = input('Enter numbers separated by a comma:\n').strip() __snake_case : Optional[int] = [int(item) for item in user_input.split(',')] print(patience_sort(unsorted))
58
1
"""simple docstring""" import os import string import sys A_ : Dict = 1 << 8 A_ : Any = { "tab": ord("\t"), "newline": ord("\r"), "esc": 27, "up": 65 + ARROW_KEY_FLAG, "down": 66 + ARROW_KEY_FLAG, "right": 67 + ARROW_KEY_FLAG, "left": 68 + ARROW_KEY_FLAG, "mod_int": 91, "undefined": sys.maxsize, "interrupt": 3, "insert": 50, "delete": 51, "pg_up": 53, "pg_down": 54, } A_ : Optional[Any] = KEYMAP["up"] A_ : int = KEYMAP["left"] if sys.platform == "win32": A_ : Dict = [] A_ : Optional[int] = { b"\xe0H": KEYMAP["up"] - ARROW_KEY_FLAG, b"\x00H": KEYMAP["up"] - ARROW_KEY_FLAG, b"\xe0P": KEYMAP["down"] - ARROW_KEY_FLAG, b"\x00P": KEYMAP["down"] - ARROW_KEY_FLAG, b"\xe0M": KEYMAP["right"] - ARROW_KEY_FLAG, b"\x00M": KEYMAP["right"] - ARROW_KEY_FLAG, b"\xe0K": KEYMAP["left"] - ARROW_KEY_FLAG, b"\x00K": KEYMAP["left"] - ARROW_KEY_FLAG, } for i in range(10): A_ : Optional[Any] = ord(str(i)) def A ( ): '''simple docstring''' if os.name == "nt": import msvcrt SCREAMING_SNAKE_CASE__ = """mbcs""" # Flush the keyboard buffer while msvcrt.kbhit(): msvcrt.getch() if len(_SCREAMING_SNAKE_CASE ) == 0: # Read the keystroke SCREAMING_SNAKE_CASE__ = msvcrt.getch() # If it is a prefix char, get second part if ch in (b"\x00", b"\xe0"): SCREAMING_SNAKE_CASE__ = ch + msvcrt.getch() # Translate actual Win chars to bullet char types try: SCREAMING_SNAKE_CASE__ = chr(WIN_KEYMAP[cha] ) WIN_CH_BUFFER.append(chr(KEYMAP["""mod_int"""] ) ) WIN_CH_BUFFER.append(_SCREAMING_SNAKE_CASE ) if ord(_SCREAMING_SNAKE_CASE ) in ( KEYMAP["insert"] - 1 << 9, KEYMAP["delete"] - 1 << 9, KEYMAP["pg_up"] - 1 << 9, KEYMAP["pg_down"] - 1 << 9, ): WIN_CH_BUFFER.append(chr(1_26 ) ) SCREAMING_SNAKE_CASE__ = chr(KEYMAP["""esc"""] ) except KeyError: SCREAMING_SNAKE_CASE__ = cha[1] else: SCREAMING_SNAKE_CASE__ = ch.decode(_SCREAMING_SNAKE_CASE ) else: SCREAMING_SNAKE_CASE__ = WIN_CH_BUFFER.pop(0 ) elif os.name == "posix": import termios import tty SCREAMING_SNAKE_CASE__ = sys.stdin.fileno() SCREAMING_SNAKE_CASE__ = termios.tcgetattr(_SCREAMING_SNAKE_CASE ) try: tty.setraw(_SCREAMING_SNAKE_CASE ) SCREAMING_SNAKE_CASE__ = sys.stdin.read(1 ) finally: termios.tcsetattr(_SCREAMING_SNAKE_CASE , termios.TCSADRAIN , _SCREAMING_SNAKE_CASE ) return ch def A ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = get_raw_chars() if ord(_SCREAMING_SNAKE_CASE ) in [KEYMAP["interrupt"], KEYMAP["newline"]]: return char elif ord(_SCREAMING_SNAKE_CASE ) == KEYMAP["esc"]: SCREAMING_SNAKE_CASE__ = get_raw_chars() if ord(_SCREAMING_SNAKE_CASE ) == KEYMAP["mod_int"]: SCREAMING_SNAKE_CASE__ = get_raw_chars() if ord(_SCREAMING_SNAKE_CASE ) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(_SCREAMING_SNAKE_CASE ) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: return chr(ord(_SCREAMING_SNAKE_CASE ) + ARROW_KEY_FLAG ) else: return KEYMAP["undefined"] else: return get_raw_chars() else: if char in string.printable: return char else: return KEYMAP["undefined"]
165
'''simple docstring''' import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class _lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def lowercase (self , UpperCAmelCase ) -> Union[str, Any]: for model_result in results.values(): for batch_size, sequence_length in zip(model_result["""bs"""] , model_result["""ss"""] ): _snake_case = model_result["""result"""][batch_size][sequence_length] self.assertIsNotNone(UpperCAmelCase ) def lowercase (self ) -> Optional[int]: _snake_case = """sshleifer/tiny-gpt2""" _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase ) _snake_case = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowercase (self ) -> Dict: _snake_case = """sgugger/tiny-distilbert-classification""" _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase , only_pretrain_model=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase ) _snake_case = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowercase (self ) -> Optional[Any]: _snake_case = """sshleifer/tiny-gpt2""" _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , torchscript=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase ) _snake_case = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(torch_device == """cpu""" , """Cant do half precision""" ) def lowercase (self ) -> Optional[int]: _snake_case = """sshleifer/tiny-gpt2""" _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , fpaa=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase ) _snake_case = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowercase (self ) -> Union[str, Any]: _snake_case = """sshleifer/tiny-gpt2""" _snake_case = AutoConfig.from_pretrained(UpperCAmelCase ) # set architectures equal to `None` _snake_case = None _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase , configs=[config] ) _snake_case = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowercase (self ) -> Optional[int]: _snake_case = """sshleifer/tiny-gpt2""" _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase ) _snake_case = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) @unittest.skipIf(torch_device == """cpu""" , """Can't do half precision""" ) def lowercase (self ) -> Tuple: _snake_case = """sshleifer/tiny-gpt2""" _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , fpaa=UpperCAmelCase , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase ) _snake_case = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def lowercase (self ) -> Union[str, Any]: _snake_case = """sshleifer/tiny-gpt2""" _snake_case = AutoConfig.from_pretrained(UpperCAmelCase ) _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase , configs=[config] ) _snake_case = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowercase (self ) -> Dict: _snake_case = """sshleifer/tinier_bart""" _snake_case = AutoConfig.from_pretrained(UpperCAmelCase ) _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase , configs=[config] ) _snake_case = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowercase (self ) -> Any: _snake_case = """sshleifer/tiny-gpt2""" _snake_case = AutoConfig.from_pretrained(UpperCAmelCase ) _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase , configs=[config] ) _snake_case = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def lowercase (self ) -> int: _snake_case = """sshleifer/tinier_bart""" _snake_case = AutoConfig.from_pretrained(UpperCAmelCase ) _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase , configs=[config] ) _snake_case = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def lowercase (self ) -> str: _snake_case = """sshleifer/tiny-gpt2""" with tempfile.TemporaryDirectory() as tmp_dir: _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , save_to_csv=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(UpperCAmelCase , """inf_time.csv""" ) , train_memory_csv_file=os.path.join(UpperCAmelCase , """train_mem.csv""" ) , inference_memory_csv_file=os.path.join(UpperCAmelCase , """inf_mem.csv""" ) , train_time_csv_file=os.path.join(UpperCAmelCase , """train_time.csv""" ) , env_info_csv_file=os.path.join(UpperCAmelCase , """env.csv""" ) , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase ) benchmark.run() self.assertTrue(Path(os.path.join(UpperCAmelCase , """inf_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(UpperCAmelCase , """train_time.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(UpperCAmelCase , """inf_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(UpperCAmelCase , """train_mem.csv""" ) ).exists() ) self.assertTrue(Path(os.path.join(UpperCAmelCase , """env.csv""" ) ).exists() ) def lowercase (self ) -> int: _snake_case = """sshleifer/tiny-gpt2""" def _check_summary_is_not_empty(UpperCAmelCase ): self.assertTrue(hasattr(UpperCAmelCase , """sequential""" ) ) self.assertTrue(hasattr(UpperCAmelCase , """cumulative""" ) ) self.assertTrue(hasattr(UpperCAmelCase , """current""" ) ) self.assertTrue(hasattr(UpperCAmelCase , """total""" ) ) with tempfile.TemporaryDirectory() as tmp_dir: _snake_case = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=UpperCAmelCase , inference=UpperCAmelCase , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(UpperCAmelCase , """log.txt""" ) , log_print=UpperCAmelCase , trace_memory_line_by_line=UpperCAmelCase , multi_process=UpperCAmelCase , ) _snake_case = PyTorchBenchmark(UpperCAmelCase ) _snake_case = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) _check_summary_is_not_empty(result.train_summary ) self.assertTrue(Path(os.path.join(UpperCAmelCase , """log.txt""" ) ).exists() )
341
0
def A__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) -> List[str]: print("""\nThe shortest path matrix using Floyd Warshall algorithm\n""") for i in range(SCREAMING_SNAKE_CASE__): for j in range(SCREAMING_SNAKE_CASE__): if dist[i][j] != float("""inf"""): print(int(dist[i][j]) , end="""\t""") else: print("""INF""" , end="""\t""") print() def A__ ( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) -> Dict: __snake_case: List[Any] = [[float("""inf""") for _ in range(SCREAMING_SNAKE_CASE__)] for _ in range(SCREAMING_SNAKE_CASE__)] for i in range(SCREAMING_SNAKE_CASE__): for j in range(SCREAMING_SNAKE_CASE__): __snake_case: str = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(SCREAMING_SNAKE_CASE__): # looping through rows of graph array for i in range(SCREAMING_SNAKE_CASE__): # looping through columns of graph array for j in range(SCREAMING_SNAKE_CASE__): if ( dist[i][k] != float("""inf""") and dist[k][j] != float("""inf""") and dist[i][k] + dist[k][j] < dist[i][j] ): __snake_case: Optional[int] = dist[i][k] + dist[k][j] _print_dist(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__) return dist, v if __name__ == "__main__": __UpperCAmelCase : int = int(input("Enter number of vertices: ")) __UpperCAmelCase : Optional[Any] = int(input("Enter number of edges: ")) __UpperCAmelCase : List[str] = [[float("inf") for i in range(v)] for j in range(v)] for i in range(v): __UpperCAmelCase : Union[str, Any] = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print("\nEdge ", i + 1) __UpperCAmelCase : Optional[Any] = int(input("Enter source:")) __UpperCAmelCase : Optional[int] = int(input("Enter destination:")) __UpperCAmelCase : Union[str, Any] = float(input("Enter weight:")) __UpperCAmelCase : str = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
293
from __future__ import annotations import numpy as np def A__ ( SCREAMING_SNAKE_CASE__) -> List[str]: return np.maximum(0 , SCREAMING_SNAKE_CASE__) if __name__ == "__main__": print(np.array(relu([-1, 0, 5]))) # --> [0, 0, 5]
293
1
from dataclasses import dataclass from typing import List, Optional, Union import numpy as np import PIL import torch from transformers import CLIPImageProcessor, CLIPVisionModel from ...models import PriorTransformer from ...pipelines import DiffusionPipeline from ...schedulers import HeunDiscreteScheduler from ...utils import ( BaseOutput, is_accelerate_available, logging, randn_tensor, replace_example_docstring, ) from .renderer import ShapERenderer _snake_case = logging.get_logger(__name__) # pylint: disable=invalid-name _snake_case = "\n Examples:\n ```py\n >>> from PIL import Image\n >>> import torch\n >>> from diffusers import DiffusionPipeline\n >>> from diffusers.utils import export_to_gif, load_image\n\n >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n >>> repo = \"openai/shap-e-img2img\"\n >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n >>> pipe = pipe.to(device)\n\n >>> guidance_scale = 3.0\n >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n >>> image = load_image(image_url).convert(\"RGB\")\n\n >>> images = pipe(\n ... image,\n ... guidance_scale=guidance_scale,\n ... num_inference_steps=64,\n ... frame_size=256,\n ... ).images\n\n >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")\n ```\n" @dataclass class lowercase ( UpperCamelCase__ ): _a = 42 class lowercase ( UpperCamelCase__ ): def __init__( self , _a , _a , _a , _a , _a , ) -> List[Any]: super().__init__() self.register_modules( prior=_a , image_encoder=_a , image_processor=_a , scheduler=_a , renderer=_a , ) def a__ ( self , _a , _a , _a , _a , _a , _a ) -> str: if latents is None: _A : str = randn_tensor(_a , generator=_a , device=_a , dtype=_a ) else: if latents.shape != shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {shape}''' ) _A : Union[str, Any] = latents.to(_a ) _A : int = latents * scheduler.init_noise_sigma return latents def a__ ( self , _a=0 ) -> Optional[Any]: if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("""Please install accelerate via `pip install accelerate`""" ) _A : str = torch.device(F'''cuda:{gpu_id}''' ) _A : Any = [self.image_encoder, self.prior] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(_a , _a ) @property def a__ ( self ) -> List[Any]: if self.device != torch.device("""meta""" ) or not hasattr(self.image_encoder , """_hf_hook""" ): return self.device for module in self.image_encoder.modules(): if ( hasattr(_a , """_hf_hook""" ) and hasattr(module._hf_hook , """execution_device""" ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device def a__ ( self , _a , _a , _a , _a , ) -> Tuple: if isinstance(_a , _a ) and isinstance(image[0] , torch.Tensor ): _A : int = torch.cat(_a , axis=0 ) if image[0].ndim == 4 else torch.stack(_a , axis=0 ) if not isinstance(_a , torch.Tensor ): _A : Dict = self.image_processor(_a , return_tensors="""pt""" ).pixel_values[0].unsqueeze(0 ) _A : int = image.to(dtype=self.image_encoder.dtype , device=_a ) _A : List[Any] = self.image_encoder(_a )["""last_hidden_state"""] _A : List[Any] = image_embeds[:, 1:, :].contiguous() # batch_size, dim, 256 _A : Dict = image_embeds.repeat_interleave(_a , dim=0 ) if do_classifier_free_guidance: _A : str = torch.zeros_like(_a ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes _A : List[str] = torch.cat([negative_image_embeds, image_embeds] ) return image_embeds @torch.no_grad() @replace_example_docstring(_a ) def __call__( self , _a , _a = 1 , _a = 25 , _a = None , _a = None , _a = 4.0 , _a = 64 , _a = "pil" , _a = True , ) -> Union[str, Any]: if isinstance(_a , PIL.Image.Image ): _A : List[Any] = 1 elif isinstance(_a , torch.Tensor ): _A : Any = image.shape[0] elif isinstance(_a , _a ) and isinstance(image[0] , (torch.Tensor, PIL.Image.Image) ): _A : Union[str, Any] = len(_a ) else: raise ValueError( F'''`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_a )}''' ) _A : Optional[int] = self._execution_device _A : Tuple = batch_size * num_images_per_prompt _A : List[Any] = guidance_scale > 1.0 _A : Optional[Any] = self._encode_image(_a , _a , _a , _a ) # prior self.scheduler.set_timesteps(_a , device=_a ) _A : Optional[int] = self.scheduler.timesteps _A : List[str] = self.prior.config.num_embeddings _A : int = self.prior.config.embedding_dim _A : Optional[Any] = self.prepare_latents( (batch_size, num_embeddings * embedding_dim) , image_embeds.dtype , _a , _a , _a , self.scheduler , ) # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim _A : List[Any] = latents.reshape(latents.shape[0] , _a , _a ) for i, t in enumerate(self.progress_bar(_a ) ): # expand the latents if we are doing classifier free guidance _A : List[str] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents _A : int = self.scheduler.scale_model_input(_a , _a ) _A : Tuple = self.prior( _a , timestep=_a , proj_embedding=_a , ).predicted_image_embedding # remove the variance _A , _A : Optional[Any] = noise_pred.split( scaled_model_input.shape[2] , dim=2 ) # batch_size, num_embeddings, embedding_dim if do_classifier_free_guidance is not None: _A , _A : Dict = noise_pred.chunk(2 ) _A : Tuple = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond) _A : int = self.scheduler.step( _a , timestep=_a , sample=_a , ).prev_sample if output_type == "latent": return ShapEPipelineOutput(images=_a ) _A : List[str] = [] for i, latent in enumerate(_a ): print() _A : List[str] = self.renderer.decode( latent[None, :] , _a , size=_a , ray_batch_size=4096 , n_coarse_samples=64 , n_fine_samples=128 , ) images.append(_a ) _A : List[Any] = torch.stack(_a ) if output_type not in ["np", "pil"]: raise ValueError(F'''Only the output types `pil` and `np` are supported not output_type={output_type}''' ) _A : List[str] = images.cpu().numpy() if output_type == "pil": _A : List[Any] = [self.numpy_to_pil(_a ) for image in images] # Offload last model to CPU if hasattr(self , """final_offload_hook""" ) and self.final_offload_hook is not None: self.final_offload_hook.offload() if not return_dict: return (images,) return ShapEPipelineOutput(images=_a )
26
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) lowerCamelCase = {'''configuration_xlnet''': ['''XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLNetConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = ['''XLNetTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = ['''XLNetTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ '''XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLNetForMultipleChoice''', '''XLNetForQuestionAnswering''', '''XLNetForQuestionAnsweringSimple''', '''XLNetForSequenceClassification''', '''XLNetForTokenClassification''', '''XLNetLMHeadModel''', '''XLNetModel''', '''XLNetPreTrainedModel''', '''load_tf_weights_in_xlnet''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ '''TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXLNetForMultipleChoice''', '''TFXLNetForQuestionAnsweringSimple''', '''TFXLNetForSequenceClassification''', '''TFXLNetForTokenClassification''', '''TFXLNetLMHeadModel''', '''TFXLNetMainLayer''', '''TFXLNetModel''', '''TFXLNetPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
188
0
'''simple docstring''' from typing import List, Optional, Union import numpy as np from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging __A =logging.get_logger(__name__) class _snake_case ( a__ ): lowerCAmelCase :Union[str, Any] = ['''input_values''', '''padding_mask'''] def __init__( self , _lowerCamelCase = 1 , _lowerCamelCase = 2_4000 , _lowerCamelCase = 0.0 , _lowerCamelCase = None , _lowerCamelCase = None , **_lowerCamelCase , ): super().__init__(feature_size=_lowerCamelCase , sampling_rate=_lowerCamelCase , padding_value=_lowerCamelCase , **_lowerCamelCase) UpperCAmelCase__ : Tuple = chunk_length_s UpperCAmelCase__ : List[Any] = overlap @property def snake_case__ ( self): if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate) @property def snake_case__ ( self): if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length)) def __call__( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = False , _lowerCamelCase = None , _lowerCamelCase = None , _lowerCamelCase = None , ): if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f'''The model corresponding to this feature extractor: {self} was trained using a sampling rate of''' f''' {self.sampling_rate}. Please make sure that the provided audio input was sampled with''' f''' {self.sampling_rate} and not {sampling_rate}.''') else: logger.warning( """It is strongly recommended to pass the `sampling_rate` argument to this function. """ """Failing to do so can result in silent errors that might be hard to debug.""") if padding and truncation: raise ValueError("""Both padding and truncation were set. Make sure you only set one.""") elif padding is None: # by default let's pad the inputs UpperCAmelCase__ : str = True UpperCAmelCase__ : Optional[Any] = bool( isinstance(_lowerCamelCase , (list, tuple)) and (isinstance(raw_audio[0] , (np.ndarray, tuple, list)))) if is_batched: UpperCAmelCase__ : Optional[Any] = [np.asarray(_lowerCamelCase , dtype=np.floataa).T for audio in raw_audio] elif not is_batched and not isinstance(_lowerCamelCase , np.ndarray): UpperCAmelCase__ : Tuple = np.asarray(_lowerCamelCase , dtype=np.floataa) elif isinstance(_lowerCamelCase , np.ndarray) and raw_audio.dtype is np.dtype(np.floataa): UpperCAmelCase__ : Dict = raw_audio.astype(np.floataa) # always return batch if not is_batched: UpperCAmelCase__ : List[str] = [np.asarray(_lowerCamelCase).T] # verify inputs are valid for idx, example in enumerate(_lowerCamelCase): if example.ndim > 2: raise ValueError(f'''Expected input shape (channels, length) but got shape {example.shape}''') if self.feature_size == 1 and example.ndim != 1: raise ValueError(f'''Expected mono audio but example has {example.shape[-1]} channels''') if self.feature_size == 2 and example.shape[-1] != 2: raise ValueError(f'''Expected stereo audio but example has {example.shape[-1]} channels''') UpperCAmelCase__ : List[str] = None UpperCAmelCase__ : Tuple = BatchFeature({"""input_values""": raw_audio}) if self.chunk_stride is not None and self.chunk_length is not None and max_length is None: if truncation: UpperCAmelCase__ : Union[str, Any] = min(array.shape[0] for array in raw_audio) UpperCAmelCase__ : Any = int(np.floor(max_length / self.chunk_stride)) UpperCAmelCase__ : Optional[int] = (nb_step - 1) * self.chunk_stride + self.chunk_length elif padding: UpperCAmelCase__ : Any = max(array.shape[0] for array in raw_audio) UpperCAmelCase__ : str = int(np.ceil(max_length / self.chunk_stride)) UpperCAmelCase__ : Tuple = (nb_step - 1) * self.chunk_stride + self.chunk_length UpperCAmelCase__ : Dict = """max_length""" else: UpperCAmelCase__ : Optional[Any] = input_values # normal padding on batch if padded_inputs is None: UpperCAmelCase__ : str = self.pad( _lowerCamelCase , max_length=_lowerCamelCase , truncation=_lowerCamelCase , padding=_lowerCamelCase , return_attention_mask=_lowerCamelCase , ) if padding: UpperCAmelCase__ : Union[str, Any] = padded_inputs.pop("""attention_mask""") UpperCAmelCase__ : Any = [] for example in padded_inputs.pop("""input_values"""): if self.feature_size == 1: UpperCAmelCase__ : Any = example[..., None] input_values.append(example.T) UpperCAmelCase__ : List[Any] = input_values if return_tensors is not None: UpperCAmelCase__ : Union[str, Any] = padded_inputs.convert_to_tensors(_lowerCamelCase) return padded_inputs
283
'''simple docstring''' import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets __A ='\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' __A ='\\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' __A ='\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 ( UpperCamelCase__ ): def remove_articles(UpperCamelCase__ ): UpperCAmelCase__ : Tuple = re.compile(R"""\b(a|an|the)\b""" , re.UNICODE ) return re.sub(UpperCamelCase__ , """ """ , UpperCamelCase__ ) def white_space_fix(UpperCamelCase__ ): return " ".join(text.split() ) def remove_punc(UpperCamelCase__ ): UpperCAmelCase__ : int = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(UpperCamelCase__ ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(UpperCamelCase__ ) ) ) ) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): return int(normalize_answer(UpperCamelCase__ ) == normalize_answer(UpperCamelCase__ ) ) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Any = [any(compute_exact(UpperCamelCase__ , UpperCamelCase__ ) for ref in refs ) for pred, refs in zip(UpperCamelCase__ , UpperCamelCase__ )] return (sum(UpperCamelCase__ ) / len(UpperCamelCase__ )) * 1_0_0 def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : List[Any] = [rgram for rgrams in rgramslist for rgram in rgrams] UpperCAmelCase__ : List[Any] = Counter(UpperCamelCase__ ) UpperCAmelCase__ : str = Counter(UpperCamelCase__ ) UpperCAmelCase__ : Dict = Counter() for sgram, scount in sgramcounter.items(): UpperCAmelCase__ : Dict = scount * numref UpperCAmelCase__ : int = Counter(UpperCamelCase__ ) UpperCAmelCase__ : Optional[int] = Counter() for cgram, ccount in cgramcounter.items(): UpperCAmelCase__ : Union[str, Any] = ccount * numref # KEEP UpperCAmelCase__ : str = sgramcounter_rep & cgramcounter_rep UpperCAmelCase__ : List[Any] = keepgramcounter_rep & rgramcounter UpperCAmelCase__ : Dict = sgramcounter_rep & rgramcounter UpperCAmelCase__ : str = 0 UpperCAmelCase__ : Union[str, Any] = 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. UpperCAmelCase__ : List[str] = 1 UpperCAmelCase__ : Optional[Any] = 1 if len(UpperCamelCase__ ) > 0: UpperCAmelCase__ : Optional[int] = keeptmpscorea / len(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) UpperCAmelCase__ : Any = keeptmpscorea / sum(keepgramcounterall_rep.values() ) UpperCAmelCase__ : Any = 0 if keepscore_precision > 0 or keepscore_recall > 0: UpperCAmelCase__ : str = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION UpperCAmelCase__ : str = sgramcounter_rep - cgramcounter_rep UpperCAmelCase__ : Optional[Any] = delgramcounter_rep - rgramcounter UpperCAmelCase__ : List[str] = sgramcounter_rep - rgramcounter UpperCAmelCase__ : str = 0 UpperCAmelCase__ : List[Any] = 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. UpperCAmelCase__ : Union[str, Any] = 1 if len(UpperCamelCase__ ) > 0: UpperCAmelCase__ : Optional[Any] = deltmpscorea / len(UpperCamelCase__ ) # ADDITION UpperCAmelCase__ : Tuple = set(UpperCamelCase__ ) - set(UpperCamelCase__ ) UpperCAmelCase__ : Optional[Any] = set(UpperCamelCase__ ) & set(UpperCamelCase__ ) UpperCAmelCase__ : List[str] = set(UpperCamelCase__ ) - set(UpperCamelCase__ ) UpperCAmelCase__ : str = 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. UpperCAmelCase__ : List[Any] = 1 UpperCAmelCase__ : List[Any] = 1 if len(UpperCamelCase__ ) > 0: UpperCAmelCase__ : Optional[int] = addtmpscore / len(UpperCamelCase__ ) if len(UpperCamelCase__ ) > 0: UpperCAmelCase__ : int = addtmpscore / len(UpperCamelCase__ ) UpperCAmelCase__ : Tuple = 0 if addscore_precision > 0 or addscore_recall > 0: UpperCAmelCase__ : int = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): UpperCAmelCase__ : Dict = len(UpperCamelCase__ ) UpperCAmelCase__ : Tuple = ssent.split(""" """ ) UpperCAmelCase__ : Optional[int] = csent.split(""" """ ) UpperCAmelCase__ : Union[str, Any] = [] UpperCAmelCase__ : Tuple = [] UpperCAmelCase__ : Any = [] UpperCAmelCase__ : Optional[Any] = [] UpperCAmelCase__ : Any = [] UpperCAmelCase__ : Tuple = [] UpperCAmelCase__ : Optional[Any] = [] UpperCAmelCase__ : Union[str, Any] = [] UpperCAmelCase__ : Dict = [] UpperCAmelCase__ : List[Any] = [] for rsent in rsents: UpperCAmelCase__ : List[str] = rsent.split(""" """ ) UpperCAmelCase__ : Dict = [] UpperCAmelCase__ : str = [] UpperCAmelCase__ : Dict = [] ragramslist.append(UpperCamelCase__ ) for i in range(0 , len(UpperCamelCase__ ) - 1 ): if i < len(UpperCamelCase__ ) - 1: UpperCAmelCase__ : Optional[int] = ragrams[i] + """ """ + ragrams[i + 1] ragrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 2: UpperCAmelCase__ : Union[str, Any] = ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2] ragrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 3: UpperCAmelCase__ : Any = ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2] + """ """ + ragrams[i + 3] ragrams.append(UpperCamelCase__ ) ragramslist.append(UpperCamelCase__ ) ragramslist.append(UpperCamelCase__ ) ragramslist.append(UpperCamelCase__ ) for i in range(0 , len(UpperCamelCase__ ) - 1 ): if i < len(UpperCamelCase__ ) - 1: UpperCAmelCase__ : Optional[int] = sagrams[i] + """ """ + sagrams[i + 1] sagrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 2: UpperCAmelCase__ : Dict = sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2] sagrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 3: UpperCAmelCase__ : str = sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2] + """ """ + sagrams[i + 3] sagrams.append(UpperCamelCase__ ) for i in range(0 , len(UpperCamelCase__ ) - 1 ): if i < len(UpperCamelCase__ ) - 1: UpperCAmelCase__ : Dict = cagrams[i] + """ """ + cagrams[i + 1] cagrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 2: UpperCAmelCase__ : int = cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2] cagrams.append(UpperCamelCase__ ) if i < len(UpperCamelCase__ ) - 3: UpperCAmelCase__ : List[Any] = cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2] + """ """ + cagrams[i + 3] cagrams.append(UpperCamelCase__ ) ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) : Optional[Any] = SARIngram(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) : str = SARIngram(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) : Any = SARIngram(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) ((UpperCAmelCase__) , (UpperCAmelCase__) , (UpperCAmelCase__)) : Optional[int] = SARIngram(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) UpperCAmelCase__ : Tuple = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 UpperCAmelCase__ : Union[str, Any] = sum([delascore, delascore, delascore, delascore] ) / 4 UpperCAmelCase__ : Dict = sum([addascore, addascore, addascore, addascore] ) / 4 UpperCAmelCase__ : List[Any] = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ = True , UpperCamelCase__ = "13a" , UpperCamelCase__ = 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: UpperCAmelCase__ : List[str] = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: UpperCAmelCase__ : Tuple = sacrebleu.metrics.bleu._get_tokenizer(UpperCamelCase__ )()(UpperCamelCase__ ) else: UpperCAmelCase__ : Tuple = sacrebleu.TOKENIZERS[tokenizer]()(UpperCamelCase__ ) elif tokenizer == "moses": UpperCAmelCase__ : Union[str, Any] = sacremoses.MosesTokenizer().tokenize(UpperCamelCase__ , return_str=UpperCamelCase__ , escape=UpperCamelCase__ ) elif tokenizer == "penn": UpperCAmelCase__ : Dict = sacremoses.MosesTokenizer().penn_tokenize(UpperCamelCase__ , return_str=UpperCamelCase__ ) else: UpperCAmelCase__ : List[Any] = sentence if not return_str: UpperCAmelCase__ : List[str] = normalized_sent.split() return normalized_sent def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): if not (len(UpperCamelCase__ ) == len(UpperCamelCase__ ) == len(UpperCamelCase__ )): raise ValueError("""Sources length must match predictions and references lengths.""" ) UpperCAmelCase__ : Optional[int] = 0 for src, pred, refs in zip(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): sari_score += SARIsent(normalize(UpperCamelCase__ ) , normalize(UpperCamelCase__ ) , [normalize(UpperCamelCase__ ) for sent in refs] ) UpperCAmelCase__ : Optional[int] = sari_score / len(UpperCamelCase__ ) return 1_0_0 * sari_score def _UpperCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__="exp" , UpperCamelCase__=None , UpperCamelCase__=False , UpperCamelCase__=False , UpperCamelCase__=False , ): UpperCAmelCase__ : int = len(references[0] ) if any(len(UpperCamelCase__ ) != references_per_prediction for refs in references ): raise ValueError("""Sacrebleu requires the same number of references for each prediction""" ) UpperCAmelCase__ : int = [[refs[i] for refs in references] for i in range(UpperCamelCase__ )] UpperCAmelCase__ : int = sacrebleu.corpus_bleu( UpperCamelCase__ , UpperCamelCase__ , smooth_method=UpperCamelCase__ , smooth_value=UpperCamelCase__ , force=UpperCamelCase__ , lowercase=UpperCamelCase__ , use_effective_order=UpperCamelCase__ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _snake_case ( datasets.Metric ): def snake_case__ ( self): 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 , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase): UpperCAmelCase__ : Union[str, Any] = {} result.update({"""sari""": compute_sari(sources=_lowerCamelCase , predictions=_lowerCamelCase , references=_lowerCamelCase)}) result.update({"""sacrebleu""": compute_sacrebleu(predictions=_lowerCamelCase , references=_lowerCamelCase)}) result.update({"""exact""": compute_em(predictions=_lowerCamelCase , references=_lowerCamelCase)}) return result
283
1
import math from ...configuration_utils import PretrainedConfig from ...utils import logging A : Any = logging.get_logger(__name__) A : List[Any] = { 'facebook/data2vec-base-960h': 'https://huggingface.co/facebook/data2vec-audio-base-960h/resolve/main/config.json', # See all Data2VecAudio models at https://huggingface.co/models?filter=data2vec-audio } class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = '''data2vec-audio''' def __init__(self : Dict , _UpperCAmelCase : Optional[int]=32 , _UpperCAmelCase : str=768 , _UpperCAmelCase : Optional[int]=12 , _UpperCAmelCase : Optional[Any]=12 , _UpperCAmelCase : Any=3072 , _UpperCAmelCase : List[Any]="gelu" , _UpperCAmelCase : Union[str, Any]=0.1 , _UpperCAmelCase : Dict=0.1 , _UpperCAmelCase : Optional[int]=0.1 , _UpperCAmelCase : Optional[int]=0.0 , _UpperCAmelCase : Tuple=0.1 , _UpperCAmelCase : List[Any]=0.1 , _UpperCAmelCase : Union[str, Any]=0.02 , _UpperCAmelCase : Tuple=1E-5 , _UpperCAmelCase : Optional[int]="gelu" , _UpperCAmelCase : Any=(512, 512, 512, 512, 512, 512, 512) , _UpperCAmelCase : List[str]=(5, 2, 2, 2, 2, 2, 2) , _UpperCAmelCase : Tuple=(10, 3, 3, 3, 3, 2, 2) , _UpperCAmelCase : Optional[int]=False , _UpperCAmelCase : int=16 , _UpperCAmelCase : Tuple=19 , _UpperCAmelCase : str=5 , _UpperCAmelCase : Union[str, Any]=0.05 , _UpperCAmelCase : Union[str, Any]=10 , _UpperCAmelCase : int=2 , _UpperCAmelCase : int=0.0 , _UpperCAmelCase : Any=10 , _UpperCAmelCase : Any=0 , _UpperCAmelCase : Any="sum" , _UpperCAmelCase : Tuple=False , _UpperCAmelCase : List[str]=False , _UpperCAmelCase : List[str]=256 , _UpperCAmelCase : Tuple=(512, 512, 512, 512, 1500) , _UpperCAmelCase : Optional[int]=(5, 3, 3, 1, 1) , _UpperCAmelCase : List[Any]=(1, 2, 3, 1, 1) , _UpperCAmelCase : Any=512 , _UpperCAmelCase : Any=0 , _UpperCAmelCase : Any=1 , _UpperCAmelCase : Union[str, Any]=2 , _UpperCAmelCase : Any=False , _UpperCAmelCase : Optional[int]=3 , _UpperCAmelCase : Union[str, Any]=2 , _UpperCAmelCase : Any=3 , _UpperCAmelCase : Union[str, Any]=None , **_UpperCAmelCase : str , ) -> Optional[Any]: """simple docstring""" super().__init__(**_UpperCAmelCase , pad_token_id=_UpperCAmelCase , bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase ) lowercase__ = hidden_size lowercase__ = feat_extract_activation lowercase__ = list(_UpperCAmelCase ) lowercase__ = list(_UpperCAmelCase ) lowercase__ = list(_UpperCAmelCase ) lowercase__ = conv_bias lowercase__ = num_conv_pos_embeddings lowercase__ = num_conv_pos_embedding_groups lowercase__ = conv_pos_kernel_size lowercase__ = len(self.conv_dim ) lowercase__ = num_hidden_layers lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = num_attention_heads lowercase__ = hidden_dropout lowercase__ = attention_dropout lowercase__ = activation_dropout lowercase__ = feat_proj_dropout lowercase__ = final_dropout lowercase__ = layerdrop lowercase__ = layer_norm_eps lowercase__ = initializer_range lowercase__ = vocab_size lowercase__ = use_weighted_layer_sum if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( """Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==""" """ `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =""" f''' {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`,''' f''' `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 lowercase__ = mask_time_prob lowercase__ = mask_time_length lowercase__ = mask_time_min_masks lowercase__ = mask_feature_prob lowercase__ = mask_feature_length lowercase__ = mask_feature_min_masks # ctc loss lowercase__ = ctc_loss_reduction lowercase__ = ctc_zero_infinity # adapter lowercase__ = add_adapter lowercase__ = adapter_kernel_size lowercase__ = adapter_stride lowercase__ = num_adapter_layers lowercase__ = output_hidden_size or hidden_size # SequenceClassification-specific parameter. Feel free to ignore for other classes. lowercase__ = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. lowercase__ = list(_UpperCAmelCase ) lowercase__ = list(_UpperCAmelCase ) lowercase__ = list(_UpperCAmelCase ) lowercase__ = xvector_output_dim @property def lowerCamelCase__ (self : Optional[Any] ) -> Dict: """simple docstring""" return math.prod(self.conv_stride )
305
def UpperCamelCase ( __magic_name__ : List[Any] ) -> Optional[int]: """simple docstring""" lowercase__ = [0] * len(__magic_name__ ) lowercase__ = [] lowercase__ = [1] * len(__magic_name__ ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__magic_name__ ) ): if indegree[i] == 0: queue.append(__magic_name__ ) while queue: lowercase__ = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: lowercase__ = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(__magic_name__ ) print(max(__magic_name__ ) ) # Adjacency list of Graph A : Union[str, Any] = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
305
1
import os import time import numpy as np import onnxruntime as ort snake_case_ = '''1''' snake_case_ = '''0''' snake_case_ = '''1''' snake_case_ = ort.SessionOptions() snake_case_ = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print('''Create inference session...''') snake_case_ = ['''TensorrtExecutionProvider''', '''CUDAExecutionProvider'''] snake_case_ = ort.InferenceSession('''model.onnx''', sess_options=sess_opt, providers=execution_provider) snake_case_ = ort.RunOptions() snake_case_ = 128 snake_case_ = 1 snake_case_ = np.ones((batch, sequence), dtype=np.intaa) snake_case_ = np.ones((batch, sequence), dtype=np.intaa) snake_case_ = np.ones((batch, sequence), dtype=np.intaa) print('''Warm up phase...''') sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Start inference...''') snake_case_ = time.time() snake_case_ = 2_000 snake_case_ = {} for iter in range(max_iters): snake_case_ = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print('''Average Inference Time = {:.3f} ms'''.format((time.time() - start_time) * 1_000 / max_iters))
355
import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( '''The `inpainting.py` script is outdated. Please use directly `from diffusers import''' ''' StableDiffusionInpaintPipeline` instead.''' )
216
0
'''simple docstring''' from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A =logging.get_logger(__name__) A ={ "google/efficientnet-b7": "https://huggingface.co/google/efficientnet-b7/resolve/main/config.json", } class _a ( UpperCamelCase__ ): __a : Tuple = """efficientnet""" def __init__( self : Any , lowercase : int = 3 , lowercase : int = 600 , lowercase : float = 2.0 , lowercase : float = 3.1 , lowercase : int = 8 , lowercase : List[int] = [3, 3, 5, 3, 5, 5, 3] , lowercase : List[int] = [32, 16, 24, 40, 80, 112, 192] , lowercase : List[int] = [16, 24, 40, 80, 112, 192, 320] , lowercase : List[int] = [] , lowercase : List[int] = [1, 2, 2, 2, 1, 2, 1] , lowercase : List[int] = [1, 2, 2, 3, 3, 4, 1] , lowercase : List[int] = [1, 6, 6, 6, 6, 6, 6] , lowercase : float = 0.25 , lowercase : str = "swish" , lowercase : int = 2_560 , lowercase : str = "mean" , lowercase : float = 0.02 , lowercase : float = 0.001 , lowercase : float = 0.99 , lowercase : float = 0.5 , lowercase : float = 0.2 , **lowercase : Dict , ): '''simple docstring''' super().__init__(**lowercase_ ) UpperCAmelCase = num_channels UpperCAmelCase = image_size UpperCAmelCase = width_coefficient UpperCAmelCase = depth_coefficient UpperCAmelCase = depth_divisor UpperCAmelCase = kernel_sizes UpperCAmelCase = in_channels UpperCAmelCase = out_channels UpperCAmelCase = depthwise_padding UpperCAmelCase = strides UpperCAmelCase = num_block_repeats UpperCAmelCase = expand_ratios UpperCAmelCase = squeeze_expansion_ratio UpperCAmelCase = hidden_act UpperCAmelCase = hidden_dim UpperCAmelCase = pooling_type UpperCAmelCase = initializer_range UpperCAmelCase = batch_norm_eps UpperCAmelCase = batch_norm_momentum UpperCAmelCase = dropout_rate UpperCAmelCase = drop_connect_rate UpperCAmelCase = sum(lowercase_ ) * 4 class _a ( UpperCamelCase__ ): __a : str = version.parse("""1.11""" ) @property def A ( self : Tuple ): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def A ( self : str ): '''simple docstring''' return 1E-5
34
'''simple docstring''' def UpperCamelCase ( _lowerCamelCase : int | float | str ): try: A__ = float(_lowerCamelCase ) except ValueError: raise ValueError("Please enter a valid number" ) A__ = decimal - int(_lowerCamelCase ) if fractional_part == 0: return int(_lowerCamelCase ), 1 else: A__ = len(str(_lowerCamelCase ).split("." )[1] ) A__ = int(decimal * (10**number_of_frac_digits) ) A__ = 10**number_of_frac_digits A__, A__ = denominator, numerator while True: A__ = dividend % divisor if remainder == 0: break A__, A__ = divisor, remainder A__, A__ = numerator / divisor, denominator / divisor return int(_lowerCamelCase ), int(_lowerCamelCase ) if __name__ == "__main__": print(f"""{decimal_to_fraction(2) = }""") print(f"""{decimal_to_fraction(89.0) = }""") print(f"""{decimal_to_fraction("67") = }""") print(f"""{decimal_to_fraction("45.0") = }""") print(f"""{decimal_to_fraction(1.5) = }""") print(f"""{decimal_to_fraction("6.25") = }""") print(f"""{decimal_to_fraction("78td") = }""")
237
0
import requests def _lowerCAmelCase ( A__: str , A__: str ): '''simple docstring''' UpperCAmelCase = {'''Content-Type''': '''application/json'''} UpperCAmelCase = requests.post(A__ , json={'''text''': message_body} , headers=A__ ) if response.status_code != 200: UpperCAmelCase = ( '''Request to slack returned an error ''' F"""{response.status_code}, the response is:\n{response.text}""" ) raise ValueError(A__ ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
354
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) __magic_name__ = {"configuration_beit": ["BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "BeitConfig", "BeitOnnxConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = ["BeitFeatureExtractor"] __magic_name__ = ["BeitImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ "BEIT_PRETRAINED_MODEL_ARCHIVE_LIST", "BeitForImageClassification", "BeitForMaskedImageModeling", "BeitForSemanticSegmentation", "BeitModel", "BeitPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __magic_name__ = [ "FlaxBeitForImageClassification", "FlaxBeitForMaskedImageModeling", "FlaxBeitModel", "FlaxBeitPreTrainedModel", ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys __magic_name__ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
152
0
import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class A_ ( unittest.TestCase ): '''simple docstring''' def lowerCAmelCase_ (self ) -> Any: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase_ (self ) -> Tuple: __UpperCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained('''CompVis/stable-diffusion-v1-4''' ) __UpperCAmelCase = sd_pipe.to(lowercase__ ) sd_pipe.set_progress_bar_config(disable=lowercase__ ) sd_pipe.set_scheduler('''sample_euler''' ) __UpperCAmelCase = '''A painting of a squirrel eating a burger''' __UpperCAmelCase = torch.manual_seed(0 ) __UpperCAmelCase = sd_pipe([prompt] , generator=lowercase__ , guidance_scale=9.0 , num_inference_steps=20 , output_type='''np''' ) __UpperCAmelCase = output.images __UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __UpperCAmelCase = np.array([0.0447, 0.0492, 0.0468, 0.0408, 0.0383, 0.0408, 0.0354, 0.0380, 0.0339] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCAmelCase_ (self ) -> Dict: __UpperCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) __UpperCAmelCase = sd_pipe.to(lowercase__ ) sd_pipe.set_progress_bar_config(disable=lowercase__ ) sd_pipe.set_scheduler('''sample_euler''' ) __UpperCAmelCase = '''A painting of a squirrel eating a burger''' __UpperCAmelCase = torch.manual_seed(0 ) __UpperCAmelCase = sd_pipe([prompt] , generator=lowercase__ , guidance_scale=9.0 , num_inference_steps=20 , output_type='''np''' ) __UpperCAmelCase = output.images __UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __UpperCAmelCase = np.array([0.1237, 0.1320, 0.1438, 0.1359, 0.1390, 0.1132, 0.1277, 0.1175, 0.1112] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def lowerCAmelCase_ (self ) -> Optional[int]: __UpperCAmelCase = StableDiffusionKDiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-1-base''' ) __UpperCAmelCase = sd_pipe.to(lowercase__ ) sd_pipe.set_progress_bar_config(disable=lowercase__ ) sd_pipe.set_scheduler('''sample_dpmpp_2m''' ) __UpperCAmelCase = '''A painting of a squirrel eating a burger''' __UpperCAmelCase = torch.manual_seed(0 ) __UpperCAmelCase = sd_pipe( [prompt] , generator=lowercase__ , guidance_scale=7.5 , num_inference_steps=15 , output_type='''np''' , use_karras_sigmas=lowercase__ , ) __UpperCAmelCase = output.images __UpperCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) __UpperCAmelCase = np.array( [0.11381689, 0.12112921, 0.1389457, 0.12549606, 0.1244964, 0.10831517, 0.11562866, 0.10867816, 0.10499048] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
333
import copy import inspect import unittest from transformers import PretrainedConfig, SwiftFormerConfig 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 SwiftFormerForImageClassification, SwiftFormerModel from transformers.models.swiftformer.modeling_swiftformer import SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class A_ : '''simple docstring''' def __init__(self , lowercase__ , lowercase__=13 , lowercase__=3 , lowercase__=True , lowercase__=True , lowercase__=0.1 , lowercase__=0.1 , lowercase__=224 , lowercase__=1_000 , lowercase__=[3, 3, 6, 4] , lowercase__=[48, 56, 112, 220] , ) -> int: __UpperCAmelCase = parent __UpperCAmelCase = batch_size __UpperCAmelCase = num_channels __UpperCAmelCase = is_training __UpperCAmelCase = use_labels __UpperCAmelCase = hidden_dropout_prob __UpperCAmelCase = attention_probs_dropout_prob __UpperCAmelCase = num_labels __UpperCAmelCase = image_size __UpperCAmelCase = layer_depths __UpperCAmelCase = embed_dims def lowerCAmelCase_ (self ) -> str: __UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCAmelCase = None if self.use_labels: __UpperCAmelCase = ids_tensor([self.batch_size] , self.num_labels ) __UpperCAmelCase = self.get_config() return config, pixel_values, labels def lowerCAmelCase_ (self ) -> Optional[Any]: return SwiftFormerConfig( depths=self.layer_depths , embed_dims=self.embed_dims , mlp_ratio=4 , downsamples=[True, True, True, True] , hidden_act='''gelu''' , num_labels=self.num_labels , down_patch_size=3 , down_stride=2 , down_pad=1 , drop_rate=0.0 , drop_path_rate=0.0 , use_layer_scale=lowercase__ , layer_scale_init_value=1E-5 , ) def lowerCAmelCase_ (self , lowercase__ , lowercase__ , lowercase__ ) -> int: __UpperCAmelCase = SwiftFormerModel(config=lowercase__ ) model.to(lowercase__ ) model.eval() __UpperCAmelCase = model(lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dims[-1], 7, 7) ) def lowerCAmelCase_ (self , lowercase__ , lowercase__ , lowercase__ ) -> List[Any]: __UpperCAmelCase = self.num_labels __UpperCAmelCase = SwiftFormerForImageClassification(lowercase__ ) model.to(lowercase__ ) model.eval() __UpperCAmelCase = model(lowercase__ , labels=lowercase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) __UpperCAmelCase = SwiftFormerForImageClassification(lowercase__ ) model.to(lowercase__ ) model.eval() __UpperCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __UpperCAmelCase = model(lowercase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase_ (self ) -> Optional[int]: ((__UpperCAmelCase) , (__UpperCAmelCase) , (__UpperCAmelCase)) = self.prepare_config_and_inputs() __UpperCAmelCase = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class A_ ( _a , _a , unittest.TestCase ): '''simple docstring''' a__ = (SwiftFormerModel, SwiftFormerForImageClassification) if is_torch_available() else () a__ = ( {"feature-extraction": SwiftFormerModel, "image-classification": SwiftFormerForImageClassification} if is_torch_available() else {} ) a__ = False a__ = False a__ = False a__ = False a__ = False def lowerCAmelCase_ (self ) -> List[str]: __UpperCAmelCase = SwiftFormerModelTester(self ) __UpperCAmelCase = ConfigTester( self , config_class=lowercase__ , has_text_modality=lowercase__ , hidden_size=37 , num_attention_heads=12 , num_hidden_layers=12 , ) def lowerCAmelCase_ (self ) -> Dict: self.config_tester.run_common_tests() @unittest.skip(reason='''SwiftFormer does not use inputs_embeds''' ) def lowerCAmelCase_ (self ) -> List[Any]: pass def lowerCAmelCase_ (self ) -> Any: __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase = model_class(lowercase__ ) __UpperCAmelCase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase__ , nn.Linear ) ) def lowerCAmelCase_ (self ) -> Optional[int]: __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase = model_class(lowercase__ ) __UpperCAmelCase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __UpperCAmelCase = [*signature.parameters.keys()] __UpperCAmelCase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase__ ) def lowerCAmelCase_ (self ) -> Optional[int]: __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase__ ) def lowerCAmelCase_ (self ) -> Optional[int]: __UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowercase__ ) @slow def lowerCAmelCase_ (self ) -> Any: for model_name in SWIFTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCAmelCase = SwiftFormerModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) @unittest.skip(reason='''SwiftFormer does not output attentions''' ) def lowerCAmelCase_ (self ) -> List[str]: pass def lowerCAmelCase_ (self ) -> Union[str, Any]: def check_hidden_states_output(lowercase__ , lowercase__ , lowercase__ ): __UpperCAmelCase = model_class(lowercase__ ) model.to(lowercase__ ) model.eval() with torch.no_grad(): __UpperCAmelCase = model(**self._prepare_for_class(lowercase__ , lowercase__ ) ) __UpperCAmelCase = outputs.hidden_states __UpperCAmelCase = 8 self.assertEqual(len(lowercase__ ) , lowercase__ ) # TODO # SwiftFormer's feature maps are of shape (batch_size, embed_dims, height, width) # with the width and height being successively divided by 2, after every 2 blocks for i in range(len(lowercase__ ) ): self.assertEqual( hidden_states[i].shape , torch.Size( [ self.model_tester.batch_size, self.model_tester.embed_dims[i // 2], (self.model_tester.image_size // 4) // 2 ** (i // 2), (self.model_tester.image_size // 4) // 2 ** (i // 2), ] ) , ) __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __UpperCAmelCase = True check_hidden_states_output(lowercase__ , lowercase__ , lowercase__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __UpperCAmelCase = True check_hidden_states_output(lowercase__ , lowercase__ , lowercase__ ) def lowerCAmelCase_ (self ) -> Tuple: def _config_zero_init(lowercase__ ): __UpperCAmelCase = copy.deepcopy(lowercase__ ) for key in configs_no_init.__dict__.keys(): if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: setattr(lowercase__ , lowercase__ , 1E-10 ) if isinstance(getattr(lowercase__ , lowercase__ , lowercase__ ) , lowercase__ ): __UpperCAmelCase = _config_zero_init(getattr(lowercase__ , lowercase__ ) ) setattr(lowercase__ , lowercase__ , lowercase__ ) return configs_no_init __UpperCAmelCase , __UpperCAmelCase = self.model_tester.prepare_config_and_inputs_for_common() __UpperCAmelCase = _config_zero_init(lowercase__ ) for model_class in self.all_model_classes: __UpperCAmelCase = model_class(config=lowercase__ ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9) / 1E9).round().item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def lowerCAmelCase_ (self ) -> Optional[Any]: pass def __a ( ) -> Any: '''simple docstring''' __UpperCAmelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class A_ ( unittest.TestCase ): '''simple docstring''' @cached_property def lowerCAmelCase_ (self ) -> str: return ViTImageProcessor.from_pretrained('''MBZUAI/swiftformer-xs''' ) if is_vision_available() else None @slow def lowerCAmelCase_ (self ) -> Tuple: __UpperCAmelCase = SwiftFormerForImageClassification.from_pretrained('''MBZUAI/swiftformer-xs''' ).to(lowercase__ ) __UpperCAmelCase = self.default_image_processor __UpperCAmelCase = prepare_img() __UpperCAmelCase = image_processor(images=lowercase__ , return_tensors='''pt''' ).to(lowercase__ ) # forward pass with torch.no_grad(): __UpperCAmelCase = model(**lowercase__ ) # verify the logits __UpperCAmelCase = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , lowercase__ ) __UpperCAmelCase = torch.tensor([[-2.1703E00, 2.1107E00, -2.0811E00]] ).to(lowercase__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) )
333
1
from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case : Optional[Any] = logging.get_logger(__name__) _snake_case : Union[str, Any] = { "transfo-xl-wt103": "https://huggingface.co/transfo-xl-wt103/resolve/main/config.json", } class a (_lowerCAmelCase ): """simple docstring""" __UpperCAmelCase : Optional[Any] = "transfo-xl" __UpperCAmelCase : Union[str, Any] = ["mems"] __UpperCAmelCase : str = { "n_token": "vocab_size", "hidden_size": "d_model", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : Optional[Any] , lowerCamelCase : List[Any]=267735 , lowerCamelCase : Dict=[20000, 40000, 200000] , lowerCamelCase : Tuple=1024 , lowerCamelCase : List[str]=1024 , lowerCamelCase : Optional[int]=16 , lowerCamelCase : Optional[int]=64 , lowerCamelCase : Tuple=4096 , lowerCamelCase : Union[str, Any]=4 , lowerCamelCase : List[str]=False , lowerCamelCase : Optional[Any]=18 , lowerCamelCase : Optional[int]=1600 , lowerCamelCase : Tuple=1000 , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Dict=True , lowerCamelCase : List[Any]=0 , lowerCamelCase : List[str]=-1 , lowerCamelCase : Tuple=True , lowerCamelCase : List[str]=0.1 , lowerCamelCase : Optional[int]=0.0 , lowerCamelCase : List[str]=True , lowerCamelCase : Union[str, Any]="normal" , lowerCamelCase : int=0.01 , lowerCamelCase : Dict=0.01 , lowerCamelCase : Tuple=0.02 , lowerCamelCase : List[str]=1E-5 , lowerCamelCase : List[Any]=0 , **lowerCamelCase : str , ) -> Optional[Any]: __snake_case : List[Any] = vocab_size __snake_case : Dict = [] self.cutoffs.extend(_a ) if proj_share_all_but_first: __snake_case : List[str] = [False] + [True] * len(self.cutoffs ) else: __snake_case : Optional[Any] = [False] + [False] * len(self.cutoffs ) __snake_case : Optional[int] = d_model __snake_case : str = d_embed __snake_case : Optional[Any] = d_head __snake_case : Optional[int] = d_inner __snake_case : List[str] = div_val __snake_case : List[str] = pre_lnorm __snake_case : Union[str, Any] = n_layer __snake_case : Optional[int] = n_head __snake_case : str = mem_len __snake_case : int = same_length __snake_case : Dict = attn_type __snake_case : int = clamp_len __snake_case : Optional[int] = sample_softmax __snake_case : List[Any] = adaptive __snake_case : Optional[int] = dropout __snake_case : Optional[int] = dropatt __snake_case : Optional[Any] = untie_r __snake_case : List[str] = init __snake_case : Any = init_range __snake_case : Optional[int] = proj_init_std __snake_case : List[Any] = init_std __snake_case : List[Any] = layer_norm_epsilon super().__init__(eos_token_id=_a , **_a ) @property def __snake_case ( self : Dict ) -> List[str]: # Message copied from Transformer-XL documentation logger.info(F'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def __snake_case ( self : List[Any] , lowerCamelCase : Optional[Any] ) -> Tuple: # Message copied from Transformer-XL documentation raise NotImplementedError( F'The model {self.model_type} is one of the few models that has no sequence length limit.' )
369
def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): if index == r: for j in range(__lowerCamelCase ): print(data[j] , end=" " ) print(" " ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location __snake_case : Union[str, Any] = arr[i] combination_util(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , index + 1 , __lowerCamelCase , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): # A temporary array to store all combination one by one __snake_case : Union[str, Any] = [0] * r # Print all combination using temporary array 'data[]' combination_util(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , 0 , __lowerCamelCase , 0 ) if __name__ == "__main__": # Driver code to check the function above _snake_case : List[str] = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
134
0
from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def __UpperCAmelCase ( __a : str ,__a : float | Decimal ,__a : float = 10**-10 ) -> float: """simple docstring""" _a : Any = a while True: _a : int = Decimal(__a ) - ( Decimal(eval(__a ) ) / Decimal(eval(str(diff(__a ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(__a ) ) < precision: # noqa: S307 return float(__a ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(f'''The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}''') # Find root of polynomial print(f'''The root of x**2 - 5*x + 2 = 0 is {newton_raphson("x**2 - 5*x + 2", 0.4)}''') # Find Square Root of 5 print(f'''The root of log(x) - 1 = 0 is {newton_raphson("log(x) - 1", 2)}''') # Exponential Roots print(f'''The root of exp(x) - 1 = 0 is {newton_raphson("exp(x) - 1", 0)}''')
235
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a__ = {'''configuration_mmbt''': ['''MMBTConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = ['''MMBTForClassification''', '''MMBTModel''', '''ModalEmbeddings'''] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys a__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
235
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices lowerCAmelCase : Any = logging.get_logger(__name__) lowerCAmelCase : Tuple = { """microsoft/focalnet-tiny""": """https://huggingface.co/microsoft/focalnet-tiny/resolve/main/config.json""", } class __magic_name__ ( UpperCAmelCase__ , UpperCAmelCase__ ): '''simple docstring''' __UpperCamelCase = "focalnet" def __init__( self , _a=224 , _a=4 , _a=3 , _a=96 , _a=False , _a=[192, 384, 768, 768] , _a=[2, 2, 6, 2] , _a=[2, 2, 2, 2] , _a=[3, 3, 3, 3] , _a="gelu" , _a=4.0 , _a=0.0 , _a=0.1 , _a=False , _a=1e-4 , _a=False , _a=False , _a=False , _a=0.02 , _a=1e-5 , _a=32 , _a=None , _a=None , **_a , ): """simple docstring""" super().__init__(**_a ) lowerCamelCase = image_size lowerCamelCase = patch_size lowerCamelCase = num_channels lowerCamelCase = embed_dim lowerCamelCase = use_conv_embed lowerCamelCase = hidden_sizes lowerCamelCase = depths lowerCamelCase = focal_levels lowerCamelCase = focal_windows lowerCamelCase = hidden_act lowerCamelCase = mlp_ratio lowerCamelCase = hidden_dropout_prob lowerCamelCase = drop_path_rate lowerCamelCase = use_layerscale lowerCamelCase = layerscale_value lowerCamelCase = use_post_layernorm lowerCamelCase = use_post_layernorm_in_modulation lowerCamelCase = normalize_modulator lowerCamelCase = initializer_range lowerCamelCase = layer_norm_eps lowerCamelCase = encoder_stride lowerCamelCase = ["""stem"""] + [f'stage{idx}' for idx in range(1 , len(self.depths ) + 1 )] lowerCamelCase , lowerCamelCase = get_aligned_output_features_output_indices( out_features=_a , out_indices=_a , stage_names=self.stage_names )
168
"""simple docstring""" from __future__ import annotations class __magic_name__ : '''simple docstring''' def __init__( self , _a ): """simple docstring""" lowerCamelCase = TypeError( """Matrices must be formed from a list of zero or more lists containing at """ """least one and the same number of values, each of which must be of type """ """int or float.""" ) if len(_a ) != 0: lowerCamelCase = len(rows[0] ) if cols == 0: raise error for row in rows: if len(_a ) != cols: raise error for value in row: if not isinstance(_a , (int, float) ): raise error lowerCamelCase = rows else: lowerCamelCase = [] def _lowerCAmelCase ( self ): """simple docstring""" return [[row[i] for row in self.rows] for i in range(len(self.rows[0] ) )] @property def _lowerCAmelCase ( self ): """simple docstring""" return len(self.rows ) @property def _lowerCAmelCase ( self ): """simple docstring""" return len(self.rows[0] ) @property def _lowerCAmelCase ( self ): """simple docstring""" return (self.num_rows, self.num_columns) @property def _lowerCAmelCase ( self ): """simple docstring""" return self.order[0] == self.order[1] def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = [ [0 if column_num != row_num else 1 for column_num in range(self.num_rows )] for row_num in range(self.num_rows ) ] return Matrix(_a ) def _lowerCAmelCase ( self ): """simple docstring""" if not self.is_square: return 0 if self.order == (0, 0): return 1 if self.order == (1, 1): return int(self.rows[0][0] ) if self.order == (2, 2): return int( (self.rows[0][0] * self.rows[1][1]) - (self.rows[0][1] * self.rows[1][0]) ) else: return sum( self.rows[0][column] * self.cofactors().rows[0][column] for column in range(self.num_columns ) ) def _lowerCAmelCase ( self ): """simple docstring""" return bool(self.determinant() ) def _lowerCAmelCase ( self , _a , _a ): """simple docstring""" lowerCamelCase = [ [ self.rows[other_row][other_column] for other_column in range(self.num_columns ) if other_column != column ] for other_row in range(self.num_rows ) if other_row != row ] return Matrix(_a ).determinant() def _lowerCAmelCase ( self , _a , _a ): """simple docstring""" if (row + column) % 2 == 0: return self.get_minor(_a , _a ) return -1 * self.get_minor(_a , _a ) def _lowerCAmelCase ( self ): """simple docstring""" return Matrix( [ [self.get_minor(_a , _a ) for column in range(self.num_columns )] for row in range(self.num_rows ) ] ) def _lowerCAmelCase ( self ): """simple docstring""" return Matrix( [ [ self.minors().rows[row][column] if (row + column) % 2 == 0 else self.minors().rows[row][column] * -1 for column in range(self.minors().num_columns ) ] for row in range(self.minors().num_rows ) ] ) def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = [ [self.cofactors().rows[column][row] for column in range(self.num_columns )] for row in range(self.num_rows ) ] return Matrix(_a ) def _lowerCAmelCase ( self ): """simple docstring""" lowerCamelCase = self.determinant() if not determinant: raise TypeError("""Only matrices with a non-zero determinant have an inverse""" ) return self.adjugate() * (1 / determinant) def __repr__( self ): """simple docstring""" return str(self.rows ) def __str__( self ): """simple docstring""" if self.num_rows == 0: return "[]" if self.num_rows == 1: return "[[" + ". ".join(str(self.rows[0] ) ) + "]]" return ( "[" + "\n ".join( [ """[""" + """. """.join([str(_a ) for value in row] ) + """.]""" for row in self.rows ] ) + "]" ) def _lowerCAmelCase ( self , _a , _a = None ): """simple docstring""" lowerCamelCase = TypeError("""Row must be a list containing all ints and/or floats""" ) if not isinstance(_a , _a ): raise type_error for value in row: if not isinstance(_a , (int, float) ): raise type_error if len(_a ) != self.num_columns: raise ValueError( """Row must be equal in length to the other rows in the matrix""" ) if position is None: self.rows.append(_a ) else: lowerCamelCase = self.rows[0:position] + [row] + self.rows[position:] def _lowerCAmelCase ( self , _a , _a = None ): """simple docstring""" lowerCamelCase = TypeError( """Column must be a list containing all ints and/or floats""" ) if not isinstance(_a , _a ): raise type_error for value in column: if not isinstance(_a , (int, float) ): raise type_error if len(_a ) != self.num_rows: raise ValueError( """Column must be equal in length to the other columns in the matrix""" ) if position is None: lowerCamelCase = [self.rows[i] + [column[i]] for i in range(self.num_rows )] else: lowerCamelCase = [ self.rows[i][0:position] + [column[i]] + self.rows[i][position:] for i in range(self.num_rows ) ] def __eq__( self , _a ): """simple docstring""" if not isinstance(_a , _a ): return NotImplemented return self.rows == other.rows def __ne__( self , _a ): """simple docstring""" return not self == other def __neg__( self ): """simple docstring""" return self * -1 def __add__( self , _a ): """simple docstring""" if self.order != other.order: raise ValueError("""Addition requires matrices of the same order""" ) return Matrix( [ [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __sub__( self , _a ): """simple docstring""" if self.order != other.order: raise ValueError("""Subtraction requires matrices of the same order""" ) return Matrix( [ [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns )] for i in range(self.num_rows ) ] ) def __mul__( self , _a ): """simple docstring""" if isinstance(_a , (int, float) ): return Matrix( [[int(element * other ) for element in row] for row in self.rows] ) elif isinstance(_a , _a ): if self.num_columns != other.num_rows: raise ValueError( """The number of columns in the first matrix must """ """be equal to the number of rows in the second""" ) return Matrix( [ [Matrix.dot_product(_a , _a ) for column in other.columns()] for row in self.rows ] ) else: raise TypeError( """A Matrix can only be multiplied by an int, float, or another matrix""" ) def __pow__( self , _a ): """simple docstring""" if not isinstance(_a , _a ): raise TypeError("""A Matrix can only be raised to the power of an int""" ) if not self.is_square: raise ValueError("""Only square matrices can be raised to a power""" ) if other == 0: return self.identity() if other < 0: if self.is_invertable(): return self.inverse() ** (-other) raise ValueError( """Only invertable matrices can be raised to a negative power""" ) lowerCamelCase = self for _ in range(other - 1 ): result *= self return result @classmethod def _lowerCAmelCase ( cls , _a , _a ): """simple docstring""" return sum(row[i] * column[i] for i in range(len(_a ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
168
1
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL UpperCAmelCase : Optional[Any] = logging.get_logger(__name__) def lowerCamelCase ( _UpperCamelCase : Any , _UpperCamelCase : Optional[Any] ) -> int: '''simple docstring''' __UpperCAmelCase : int = b.T __UpperCAmelCase : Union[str, Any] = np.sum(np.square(_UpperCamelCase ) , axis=1 ) __UpperCAmelCase : List[Any] = np.sum(np.square(_UpperCamelCase ) , axis=0 ) __UpperCAmelCase : int = np.matmul(_UpperCamelCase , _UpperCamelCase ) __UpperCAmelCase : Tuple = aa[:, None] - 2 * ab + ba[None, :] return d def lowerCamelCase ( _UpperCamelCase : Tuple , _UpperCamelCase : Optional[Any] ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Tuple = x.reshape(-1 , 3 ) __UpperCAmelCase : Optional[Any] = squared_euclidean_distance(_UpperCamelCase , _UpperCamelCase ) return np.argmin(_UpperCamelCase , axis=1 ) class lowerCamelCase__ ( A ): """simple docstring""" __a = ["""pixel_values"""] def __init__( self : List[str] , UpperCamelCase : Optional[Union[List[List[int]], np.ndarray]] = None , UpperCamelCase : bool = True , UpperCamelCase : Dict[str, int] = None , UpperCamelCase : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase : bool = True , UpperCamelCase : bool = True , **UpperCamelCase : int , ): '''simple docstring''' super().__init__(**UpperCamelCase ) __UpperCAmelCase : Optional[Any] = size if size is not None else {"""height""": 256, """width""": 256} __UpperCAmelCase : Tuple = get_size_dict(UpperCamelCase ) __UpperCAmelCase : Union[str, Any] = np.array(UpperCamelCase ) if clusters is not None else None __UpperCAmelCase : int = do_resize __UpperCAmelCase : List[str] = size __UpperCAmelCase : Dict = resample __UpperCAmelCase : int = do_normalize __UpperCAmelCase : List[Any] = do_color_quantize def lowerCamelCase__ ( self : List[str] , UpperCamelCase : np.ndarray , UpperCamelCase : Dict[str, int] , UpperCamelCase : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase : str , ): '''simple docstring''' __UpperCAmelCase : Any = get_size_dict(UpperCamelCase ) if "height" not in size or "width" not in size: raise ValueError(f'''Size dictionary must contain both height and width keys. Got {size.keys()}''' ) return resize( UpperCamelCase , size=(size["""height"""], size["""width"""]) , resample=UpperCamelCase , data_format=UpperCamelCase , **UpperCamelCase ) def lowerCamelCase__ ( self : Dict , UpperCamelCase : np.ndarray , UpperCamelCase : Optional[Union[str, ChannelDimension]] = None , ): '''simple docstring''' __UpperCAmelCase : Optional[Any] = rescale(image=UpperCamelCase , scale=1 / 127.5 , data_format=UpperCamelCase ) __UpperCAmelCase : Optional[Any] = image - 1 return image def lowerCamelCase__ ( self : Dict , UpperCamelCase : ImageInput , UpperCamelCase : bool = None , UpperCamelCase : Dict[str, int] = None , UpperCamelCase : PILImageResampling = None , UpperCamelCase : bool = None , UpperCamelCase : Optional[bool] = None , UpperCamelCase : Optional[Union[List[List[int]], np.ndarray]] = None , UpperCamelCase : Optional[Union[str, TensorType]] = None , UpperCamelCase : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **UpperCamelCase : Optional[int] , ): '''simple docstring''' __UpperCAmelCase : List[str] = do_resize if do_resize is not None else self.do_resize __UpperCAmelCase : Any = size if size is not None else self.size __UpperCAmelCase : Any = get_size_dict(UpperCamelCase ) __UpperCAmelCase : Optional[Any] = resample if resample is not None else self.resample __UpperCAmelCase : Any = do_normalize if do_normalize is not None else self.do_normalize __UpperCAmelCase : Any = do_color_quantize if do_color_quantize is not None else self.do_color_quantize __UpperCAmelCase : Tuple = clusters if clusters is not None else self.clusters __UpperCAmelCase : Tuple = np.array(UpperCamelCase ) __UpperCAmelCase : int = make_list_of_images(UpperCamelCase ) if not valid_images(UpperCamelCase ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None or resample is None: raise ValueError("""Size and resample must be specified if do_resize is True.""" ) if do_color_quantize and clusters is None: raise ValueError("""Clusters must be specified if do_color_quantize is True.""" ) # All transformations expect numpy arrays. __UpperCAmelCase : Tuple = [to_numpy_array(UpperCamelCase ) for image in images] if do_resize: __UpperCAmelCase : Dict = [self.resize(image=UpperCamelCase , size=UpperCamelCase , resample=UpperCamelCase ) for image in images] if do_normalize: __UpperCAmelCase : Any = [self.normalize(image=UpperCamelCase ) for image in images] if do_color_quantize: __UpperCAmelCase : str = [to_channel_dimension_format(UpperCamelCase , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) __UpperCAmelCase : Optional[int] = np.array(UpperCamelCase ) __UpperCAmelCase : Any = color_quantize(UpperCamelCase , UpperCamelCase ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) __UpperCAmelCase : Dict = images.shape[0] __UpperCAmelCase : Optional[Any] = images.reshape(UpperCamelCase , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. __UpperCAmelCase : int = list(UpperCamelCase ) else: __UpperCAmelCase : List[Any] = [to_channel_dimension_format(UpperCamelCase , UpperCamelCase ) for image in images] __UpperCAmelCase : List[str] = {"""input_ids""": images} return BatchFeature(data=UpperCamelCase , tensor_type=UpperCamelCase )
115
"""simple docstring""" import re def lowerCamelCase ( _UpperCamelCase : str ) -> str: '''simple docstring''' if len(re.findall("""[ATCG]""" , _UpperCamelCase ) ) != len(_UpperCamelCase ): raise ValueError("""Invalid Strand""" ) return dna.translate(dna.maketrans("""ATCG""" , """TAGC""" ) ) if __name__ == "__main__": import doctest doctest.testmod()
115
1
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class snake_case__ : def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=13 , lowerCAmelCase__=7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=99 , lowerCAmelCase__=32 , lowerCAmelCase__=2 , lowerCAmelCase__=4 , lowerCAmelCase__=37 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_12 , lowerCAmelCase__=16 , lowerCAmelCase__=2 , lowerCAmelCase__=0.0_2 , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=None , lowerCAmelCase__=0 , ) -> Optional[Any]: __magic_name__ : Dict = parent __magic_name__ : Union[str, Any] = batch_size __magic_name__ : Optional[Any] = seq_length __magic_name__ : Optional[Any] = is_training __magic_name__ : Union[str, Any] = use_input_mask __magic_name__ : List[Any] = use_token_type_ids __magic_name__ : int = use_labels __magic_name__ : Optional[int] = vocab_size __magic_name__ : Dict = hidden_size __magic_name__ : Any = num_hidden_layers __magic_name__ : Optional[Any] = num_attention_heads __magic_name__ : Any = intermediate_size __magic_name__ : List[str] = hidden_act __magic_name__ : List[Any] = hidden_dropout_prob __magic_name__ : Tuple = attention_probs_dropout_prob __magic_name__ : Optional[Any] = max_position_embeddings __magic_name__ : Optional[int] = type_vocab_size __magic_name__ : Optional[Any] = type_sequence_label_size __magic_name__ : Optional[Any] = initializer_range __magic_name__ : List[str] = num_labels __magic_name__ : List[Any] = num_choices __magic_name__ : List[str] = scope __magic_name__ : str = projection_dim def __magic_name__( self ) -> int: __magic_name__ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ : str = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py __magic_name__ : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ : Any = None if self.use_token_type_ids: __magic_name__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ : int = None __magic_name__ : Optional[int] = None __magic_name__ : Any = None if self.use_labels: __magic_name__ : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ : Tuple = ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ : Dict = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCAmelCase__ , initializer_range=self.initializer_range , ) __magic_name__ : Optional[int] = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __magic_name__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: __magic_name__ : Any = TFDPRContextEncoder(config=lowerCAmelCase__ ) __magic_name__ : Any = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ ) __magic_name__ : Dict = model(lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ ) __magic_name__ : Dict = model(lowerCAmelCase__ ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def __magic_name__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> int: __magic_name__ : Any = TFDPRQuestionEncoder(config=lowerCAmelCase__ ) __magic_name__ : Any = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ ) __magic_name__ : Optional[int] = model(lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ ) __magic_name__ : Tuple = model(lowerCAmelCase__ ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def __magic_name__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> List[Any]: __magic_name__ : Any = TFDPRReader(config=lowerCAmelCase__ ) __magic_name__ : Optional[int] = model(lowerCAmelCase__ , attention_mask=lowerCAmelCase__ ) 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) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def __magic_name__( self ) -> int: __magic_name__ : Optional[int] = self.prepare_config_and_inputs() ( __magic_name__ ) : Union[str, Any] = config_and_inputs __magic_name__ : List[Any] = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class snake_case__ ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): lowercase__ : Union[str, Any] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) lowercase__ : Tuple = {'''feature-extraction''': TFDPRQuestionEncoder} if is_tf_available() else {} lowercase__ : Optional[int] = False lowercase__ : str = False lowercase__ : Dict = False lowercase__ : int = False lowercase__ : List[str] = False def __magic_name__( self ) -> Optional[Any]: __magic_name__ : Optional[Any] = TFDPRModelTester(self ) __magic_name__ : str = ConfigTester(self , config_class=lowerCAmelCase__ , hidden_size=37 ) def __magic_name__( self ) -> Dict: self.config_tester.run_common_tests() def __magic_name__( self ) -> str: __magic_name__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*lowerCAmelCase__ ) def __magic_name__( self ) -> Any: __magic_name__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*lowerCAmelCase__ ) def __magic_name__( self ) -> List[str]: __magic_name__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*lowerCAmelCase__ ) @slow def __magic_name__( self ) -> Tuple: for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ : Optional[int] = TFDPRContextEncoder.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ : Dict = TFDPRContextEncoder.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __magic_name__ : Union[str, Any] = TFDPRReader.from_pretrained(lowerCAmelCase__ ) self.assertIsNotNone(lowerCAmelCase__ ) @require_tf class snake_case__ ( unittest.TestCase ): @slow def __magic_name__( self ) -> str: __magic_name__ : Any = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) __magic_name__ : List[str] = tf.constant( [[1_01, 75_92, 10_10, 20_03, 20_26, 38_99, 1_01_40, 10_29, 1_02]] ) # [CLS] hello, is my dog cute? [SEP] __magic_name__ : Optional[int] = model(lowerCAmelCase__ )[0] # embedding shape = (1, 768) # compare the actual values for a slice. __magic_name__ : Any = tf.constant( [ [ 0.0_3_2_3_6_2_5_3, 0.1_2_7_5_3_3_3_5, 0.1_6_8_1_8_5_0_9, 0.0_0_2_7_9_7_8_6, 0.3_8_9_6_9_3_3, 0.2_4_2_6_4_9_4_5, 0.2_1_7_8_9_7_1, -0.0_2_3_3_5_2_2_7, -0.0_8_4_8_1_9_5_9, -0.1_4_3_2_4_1_1_7, ] ] ) self.assertTrue(numpy.allclose(output[:, :10].numpy() , expected_slice.numpy() , atol=1e-4 ) )
366
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: __magic_name__: Any = None __magic_name__: Dict = logging.get_logger(__name__) __magic_name__: Any = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} __magic_name__: str = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", }, "tokenizer_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json", }, } __magic_name__: Optional[Any] = { "xlnet-base-cased": None, "xlnet-large-cased": None, } __magic_name__: Optional[Any] = "▁" # Segments (not really needed) __magic_name__: List[Any] = 0 __magic_name__: Dict = 1 __magic_name__: List[str] = 2 __magic_name__: List[Any] = 3 __magic_name__: Optional[int] = 4 class snake_case__ ( _lowerCAmelCase ): lowercase__ : Dict = VOCAB_FILES_NAMES lowercase__ : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP lowercase__ : Tuple = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ : List[str] = '''left''' lowercase__ : List[str] = XLNetTokenizer def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__=False , lowerCAmelCase__="<s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__="<unk>" , lowerCAmelCase__="<sep>" , lowerCAmelCase__="<pad>" , lowerCAmelCase__="<cls>" , lowerCAmelCase__="<mask>" , lowerCAmelCase__=["<eop>", "<eod>"] , **lowerCAmelCase__ , ) -> Tuple: # Mask token behave like a normal word, i.e. include the space before it __magic_name__ : Optional[int] = AddedToken(lowerCAmelCase__ , lstrip=lowerCAmelCase__ , rstrip=lowerCAmelCase__ ) if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else mask_token super().__init__( vocab_file=lowerCAmelCase__ , tokenizer_file=lowerCAmelCase__ , do_lower_case=lowerCAmelCase__ , remove_space=lowerCAmelCase__ , keep_accents=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , cls_token=lowerCAmelCase__ , mask_token=lowerCAmelCase__ , additional_special_tokens=lowerCAmelCase__ , **lowerCAmelCase__ , ) __magic_name__ : List[str] = 3 __magic_name__ : str = do_lower_case __magic_name__ : Union[str, Any] = remove_space __magic_name__ : str = keep_accents __magic_name__ : Tuple = vocab_file __magic_name__ : List[Any] = False if not self.vocab_file else True def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: __magic_name__ : Any = [self.sep_token_id] __magic_name__ : Any = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: __magic_name__ : List[str] = [self.sep_token_id] __magic_name__ : Optional[Any] = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __magic_name__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: if not self.can_save_slow_tokenizer: raise ValueError( """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """ """tokenizer.""" ) if not os.path.isdir(lowerCAmelCase__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return __magic_name__ : List[str] = os.path.join( lowerCAmelCase__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase__ ): copyfile(self.vocab_file , lowerCAmelCase__ ) return (out_vocab_file,)
138
0
"""simple docstring""" def a__ ( lowerCAmelCase , lowerCAmelCase ) -> Optional[Any]: UpperCAmelCase__ : str = 0 while b > 0: if b & 1: res += a a += a b >>= 1 return res def a__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> Tuple: UpperCAmelCase__ : List[str] = 0 while b > 0: if b & 1: UpperCAmelCase__ : Optional[Any] = ((res % c) + (a % c)) % c a += a b >>= 1 return res
171
"""simple docstring""" import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class lowerCamelCase : '''simple docstring''' def __init__(self , _lowerCamelCase , _lowerCamelCase=99 , _lowerCamelCase=13 , _lowerCamelCase=16 , _lowerCamelCase=7 , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=True , _lowerCamelCase=False , _lowerCamelCase=True , _lowerCamelCase=2 , _lowerCamelCase=32 , _lowerCamelCase=4 , _lowerCamelCase=4 , _lowerCamelCase=30 , _lowerCamelCase=0 , _lowerCamelCase=1 , _lowerCamelCase=2 , _lowerCamelCase=None , ): """simple docstring""" UpperCAmelCase__ : int = parent UpperCAmelCase__ : Optional[Any] = batch_size UpperCAmelCase__ : Union[str, Any] = decoder_seq_length # For common tests UpperCAmelCase__ : int = self.decoder_seq_length UpperCAmelCase__ : Optional[Any] = is_training UpperCAmelCase__ : Optional[Any] = use_attention_mask UpperCAmelCase__ : List[Any] = use_labels UpperCAmelCase__ : Optional[Any] = vocab_size UpperCAmelCase__ : List[Any] = d_model UpperCAmelCase__ : List[str] = d_model UpperCAmelCase__ : Dict = decoder_layers UpperCAmelCase__ : Any = decoder_layers UpperCAmelCase__ : Tuple = decoder_ffn_dim UpperCAmelCase__ : Any = decoder_attention_heads UpperCAmelCase__ : List[str] = decoder_attention_heads UpperCAmelCase__ : List[str] = eos_token_id UpperCAmelCase__ : int = bos_token_id UpperCAmelCase__ : Optional[int] = pad_token_id UpperCAmelCase__ : Any = decoder_start_token_id UpperCAmelCase__ : Dict = use_cache UpperCAmelCase__ : Optional[Any] = max_position_embeddings UpperCAmelCase__ : Optional[int] = None UpperCAmelCase__ : Dict = decoder_seq_length UpperCAmelCase__ : str = 2 UpperCAmelCase__ : List[str] = 1 def _a (self ): """simple docstring""" UpperCAmelCase__ : List[str] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) UpperCAmelCase__ : List[str] = None if self.use_attention_mask: UpperCAmelCase__ : Union[str, Any] = ids_tensor([self.batch_size, self.decoder_seq_length] , vocab_size=2 ) UpperCAmelCase__ : Any = None if self.use_labels: UpperCAmelCase__ : List[Any] = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) UpperCAmelCase__ : Union[str, Any] = TrOCRConfig( vocab_size=self.vocab_size , d_model=self.d_model , decoder_layers=self.decoder_layers , decoder_ffn_dim=self.decoder_ffn_dim , decoder_attention_heads=self.decoder_attention_heads , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , use_cache=self.use_cache , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , max_position_embeddings=self.max_position_embeddings , ) return (config, input_ids, attention_mask, lm_labels) def _a (self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ): """simple docstring""" UpperCAmelCase__ : List[str] = True UpperCAmelCase__ : str = TrOCRDecoder(config=_lowerCamelCase ).to(_lowerCamelCase ).eval() UpperCAmelCase__ : Any = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass UpperCAmelCase__ : Optional[Any] = model(_lowerCamelCase , use_cache=_lowerCamelCase ) UpperCAmelCase__ : str = model(_lowerCamelCase ) UpperCAmelCase__ : Optional[int] = model(_lowerCamelCase , use_cache=_lowerCamelCase ) self.parent.assertTrue(len(_lowerCamelCase ) == len(_lowerCamelCase ) ) self.parent.assertTrue(len(_lowerCamelCase ) == len(_lowerCamelCase ) + 1 ) UpperCAmelCase__ : List[Any] = outputs["""past_key_values"""] # create hypothetical next token and extent to next_input_ids UpperCAmelCase__ : List[str] = ids_tensor((2, 1) , config.vocab_size - 1 ) + 1 # append to next input_ids and UpperCAmelCase__ : Any = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase__ : int = model(_lowerCamelCase )["""last_hidden_state"""] UpperCAmelCase__ : Dict = model(_lowerCamelCase , past_key_values=_lowerCamelCase )["""last_hidden_state"""] # select random slice UpperCAmelCase__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase__ : int = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() UpperCAmelCase__ : Dict = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(_lowerCamelCase , _lowerCamelCase , atol=1e-3 ) def _a (self ): """simple docstring""" UpperCAmelCase__ : Tuple = self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Any = config_and_inputs UpperCAmelCase__ : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": attention_mask} return config, inputs_dict @require_torch class lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () SCREAMING_SNAKE_CASE = (TrOCRForCausalLM,) if is_torch_available() else () SCREAMING_SNAKE_CASE = {'text-generation': TrOCRForCausalLM} if is_torch_available() else {} SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = False def _a (self ): """simple docstring""" UpperCAmelCase__ : Union[str, Any] = TrOCRStandaloneDecoderModelTester(self , is_training=_lowerCamelCase ) UpperCAmelCase__ : Union[str, Any] = ConfigTester(self , config_class=_lowerCamelCase ) def _a (self ): """simple docstring""" pass def _a (self ): """simple docstring""" pass def _a (self ): """simple docstring""" pass def _a (self ): """simple docstring""" self.config_tester.run_common_tests() def _a (self ): """simple docstring""" UpperCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*_lowerCamelCase ) def _a (self ): """simple docstring""" return @unittest.skip("""The model doesn't support left padding""" ) # and it's not used enough to be worth fixing :) def _a (self ): """simple docstring""" pass
171
1
"""simple docstring""" # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position __lowercase = """2.13.1""" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("""3.7"""): raise ImportWarning( """To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition.""" ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( """To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n""" """If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.""" ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip __lowercase = concatenate_datasets __lowercase = DownloadConfig __lowercase = DownloadManager __lowercase = DownloadMode __lowercase = DownloadConfig __lowercase = DownloadMode __lowercase = DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
226
"""simple docstring""" import inspect import os import re from transformers.configuration_utils import PretrainedConfig 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 __lowercase = { # used to compute the property `self.chunk_length` """EncodecConfig""": ["""overlap"""], # used as `self.bert_model = BertModel(config, ...)` """DPRConfig""": True, # not used in modeling files, but it's an important information """FSMTConfig""": ["""langs"""], # used internally in the configuration class file """GPTNeoConfig""": ["""attention_types"""], # used internally in the configuration class file """EsmConfig""": ["""is_folding_model"""], # used during training (despite we don't have training script for these models yet) """Mask2FormerConfig""": ["""ignore_value"""], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) """OneFormerConfig""": ["""ignore_value""", """norm"""], # used during preprocessing and collation, see `collating_graphormer.py` """GraphormerConfig""": ["""spatial_pos_max"""], # used internally in the configuration class file """T5Config""": ["""feed_forward_proj"""], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally """MT5Config""": ["""feed_forward_proj""", """tokenizer_class"""], """UMT5Config""": ["""feed_forward_proj""", """tokenizer_class"""], # used internally in the configuration class file """LongT5Config""": ["""feed_forward_proj"""], # used internally in the configuration class file """SwitchTransformersConfig""": ["""feed_forward_proj"""], # having default values other than `1e-5` - we can't fix them without breaking """BioGptConfig""": ["""layer_norm_eps"""], # having default values other than `1e-5` - we can't fix them without breaking """GLPNConfig""": ["""layer_norm_eps"""], # having default values other than `1e-5` - we can't fix them without breaking """SegformerConfig""": ["""layer_norm_eps"""], # having default values other than `1e-5` - we can't fix them without breaking """CvtConfig""": ["""layer_norm_eps"""], # having default values other than `1e-5` - we can't fix them without breaking """PerceiverConfig""": ["""layer_norm_eps"""], # used internally to calculate the feature size """InformerConfig""": ["""num_static_real_features""", """num_time_features"""], # used internally to calculate the feature size """TimeSeriesTransformerConfig""": ["""num_static_real_features""", """num_time_features"""], # used internally to calculate the feature size """AutoformerConfig""": ["""num_static_real_features""", """num_time_features"""], # used internally to calculate `mlp_dim` """SamVisionConfig""": ["""mlp_ratio"""], # For (head) training, but so far not implemented """ClapAudioConfig""": ["""num_classes"""], # Not used, but providing useful information to users """SpeechT5HifiGanConfig""": ["""sampling_rate"""], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { """CLIPSegConfig""": True, """DeformableDetrConfig""": True, """DetaConfig""": True, """DinatConfig""": True, """DonutSwinConfig""": True, """EfficientFormerConfig""": True, """FSMTConfig""": True, """JukeboxConfig""": True, """LayoutLMv2Config""": True, """MaskFormerSwinConfig""": True, """MT5Config""": True, """NatConfig""": True, """OneFormerConfig""": True, """PerceiverConfig""": True, """RagConfig""": True, """SpeechT5Config""": True, """SwinConfig""": True, """Swin2SRConfig""": True, """Swinv2Config""": True, """SwitchTransformersConfig""": True, """TableTransformerConfig""": True, """TapasConfig""": True, """TransfoXLConfig""": True, """UniSpeechConfig""": True, """UniSpeechSatConfig""": True, """WavLMConfig""": True, """WhisperConfig""": True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) """JukeboxPriorConfig""": True, # TODO: @Younes (for `is_decoder`) """Pix2StructTextConfig""": True, } ) def lowercase ( A_ , A_ , A_ , A_ )-> Optional[Any]: '''simple docstring''' a : List[str] = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( F'''config.{attribute}''' in modeling_source or F'''getattr(config, "{attribute}"''' in modeling_source or F'''getattr(self.config, "{attribute}"''' in modeling_source ): a : str = True # Deal with multi-line cases elif ( re.search( RF'''getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"''' , A_ , ) is not None ): a : List[Any] = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: a : str = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files a : Tuple = [ "bos_index", "eos_index", "pad_index", "unk_index", "mask_index", "image_size", "use_cache", "out_features", "out_indices", ] a : str = ["encoder_no_repeat_ngram_size"] # Special cases to be allowed a : int = True if not attribute_used: a : Dict = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: a : Optional[int] = True elif attribute in ["tie_word_embeddings"] and default_value is False: a : List[Any] = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: a : str = True elif attribute.endswith("_token_id" ): a : str = True # configuration class specific cases if not case_allowed: a : Union[str, Any] = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) a : Optional[Any] = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def lowercase ( A_ )-> Tuple: '''simple docstring''' a : Optional[int] = dict(inspect.signature(config_class.__init__ ).parameters ) a : Any = [x for x in list(signature.keys() ) if x not in ["self", "kwargs"]] a : str = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass a : Dict = {} if len(config_class.attribute_map ) > 0: a : int = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files a : int = inspect.getsourcefile(A_ ) a : Union[str, Any] = os.path.dirname(A_ ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. a : Optional[Any] = [os.path.join(A_ , A_ ) for fn in os.listdir(A_ ) if fn.startswith("modeling_" )] # Get the source code strings a : Tuple = [] for path in modeling_paths: if os.path.isfile(A_ ): with open(A_ ) as fp: modeling_sources.append(fp.read() ) a : Optional[Any] = [] for config_param, default_value in zip(A_ , A_ ): # `attributes` here is all the variant names for `config_param` a : str = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(A_ , A_ , A_ , A_ ): unused_attributes.append(attributes[0] ) return sorted(A_ ) def lowercase ( )-> str: '''simple docstring''' a : List[Any] = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) a : str = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda A_ : inspect.isclass(A_ ) and issubclass(A_ , A_ ) and inspect.getmodule(A_ ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: a : Union[str, Any] = check_config_attributes_being_used(A_ ) if len(A_ ) > 0: a : Dict = unused_attributes if len(A_ ) > 0: a : Union[str, Any] = "The following configuration classes contain unused attributes in the corresponding modeling files:\n" for name, attributes in configs_with_unused_attributes.items(): error += F'''{name}: {attributes}\n''' raise ValueError(A_ ) if __name__ == "__main__": check_config_attributes()
226
1
'''simple docstring''' from math import factorial, radians def a__ ( lowerCAmelCase__ , lowerCAmelCase__ = 18 , lowerCAmelCase__ = 10 ) -> float: UpperCAmelCase__ : int = angle_in_degrees - ((angle_in_degrees // 3_6_0.0) * 3_6_0.0) # Converting from degrees to radians UpperCAmelCase__ : int = radians(lowerCAmelCase__ ) UpperCAmelCase__ : str = angle_in_radians UpperCAmelCase__ : Dict = 3 UpperCAmelCase__ : Dict = -1 for _ in range(lowerCAmelCase__ ): result += (b * (angle_in_radians**a)) / factorial(lowerCAmelCase__ ) UpperCAmelCase__ : Dict = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": __import__('''doctest''').testmod()
181
'''simple docstring''' from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCamelCase_ ( __a ): def lowercase_ ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : str = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(_A , '''embed_dim''' ) ) self.parent.assertTrue(hasattr(_A , '''num_heads''' ) ) class lowerCamelCase_ : def __init__( self : int , _A : Tuple , _A : Any=13 , _A : Optional[int]=64 , _A : Optional[Any]=3 , _A : List[str]=[16, 48, 96] , _A : int=[1, 3, 6] , _A : Optional[int]=[1, 2, 10] , _A : int=[7, 3, 3] , _A : Union[str, Any]=[4, 2, 2] , _A : Dict=[2, 1, 1] , _A : Optional[Any]=[2, 2, 2] , _A : Optional[Any]=[False, False, True] , _A : List[Any]=[0.0, 0.0, 0.0] , _A : str=0.0_2 , _A : Tuple=1e-12 , _A : Union[str, Any]=True , _A : Optional[Any]=True , _A : Optional[int]=2 , ): '''simple docstring''' UpperCAmelCase__ : Dict = parent UpperCAmelCase__ : List[str] = batch_size UpperCAmelCase__ : Optional[int] = image_size UpperCAmelCase__ : List[str] = patch_sizes UpperCAmelCase__ : Any = patch_stride UpperCAmelCase__ : Tuple = patch_padding UpperCAmelCase__ : int = is_training UpperCAmelCase__ : Dict = use_labels UpperCAmelCase__ : List[Any] = num_labels UpperCAmelCase__ : Optional[Any] = num_channels UpperCAmelCase__ : Optional[int] = embed_dim UpperCAmelCase__ : int = num_heads UpperCAmelCase__ : Any = stride_kv UpperCAmelCase__ : str = depth UpperCAmelCase__ : List[Any] = cls_token UpperCAmelCase__ : List[Any] = attention_drop_rate UpperCAmelCase__ : Optional[int] = initializer_range UpperCAmelCase__ : Optional[int] = layer_norm_eps def lowercase_ ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase__ : int = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase__ : Any = None if self.use_labels: # create a random int32 tensor of given shape UpperCAmelCase__ : List[Any] = ids_tensor([self.batch_size] , self.num_labels ) UpperCAmelCase__ : List[Any] = self.get_config() return config, pixel_values, labels def lowercase_ ( self : Any ): '''simple docstring''' return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def lowercase_ ( self : Optional[int] , _A : List[Any] , _A : Tuple , _A : Dict ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = TFCvtModel(config=_A ) UpperCAmelCase__ : List[str] = model(_A , training=_A ) UpperCAmelCase__ : int = (self.image_size, self.image_size) UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = image_size[0], image_size[1] for i in range(len(self.depth ) ): UpperCAmelCase__ : Union[str, Any] = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) UpperCAmelCase__ : Optional[Any] = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def lowercase_ ( self : Optional[Any] , _A : Optional[Any] , _A : List[Any] , _A : int ): '''simple docstring''' UpperCAmelCase__ : str = self.num_labels UpperCAmelCase__ : Union[str, Any] = TFCvtForImageClassification(_A ) UpperCAmelCase__ : Any = model(_A , labels=_A , training=_A ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowercase_ ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase__ : List[Any] = self.prepare_config_and_inputs() UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ : Dict = config_and_inputs UpperCAmelCase__ : Optional[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_tf class lowerCamelCase_ ( __a , __a , unittest.TestCase ): lowerCAmelCase__ = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () lowerCAmelCase__ = ( {'feature-extraction': TFCvtModel, 'image-classification': TFCvtForImageClassification} if is_tf_available() else {} ) lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False lowerCAmelCase__ = False def lowercase_ ( self : Any ): '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = TFCvtModelTester(self ) UpperCAmelCase__ : Tuple = TFCvtConfigTester(self , config_class=_A , has_text_modality=_A , hidden_size=37 ) def lowercase_ ( self : Any ): '''simple docstring''' self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason='''Cvt does not output attentions''' ) def lowercase_ ( self : Any ): '''simple docstring''' pass @unittest.skip(reason='''Cvt does not use inputs_embeds''' ) def lowercase_ ( self : str ): '''simple docstring''' pass @unittest.skip(reason='''Cvt does not support input and output embeddings''' ) def lowercase_ ( self : Optional[Any] ): '''simple docstring''' pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , ) def lowercase_ ( self : List[str] ): '''simple docstring''' super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , ) @slow def lowercase_ ( self : Optional[int] ): '''simple docstring''' super().test_keras_fit() @unittest.skip(reason='''Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8''' ) def lowercase_ ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : List[Any] = tf.keras.mixed_precision.Policy('''mixed_float16''' ) tf.keras.mixed_precision.set_global_policy(_A ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy('''float32''' ) def lowercase_ ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : str = model_class(_A ) UpperCAmelCase__ : Optional[int] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase__ : List[Any] = [*signature.parameters.keys()] UpperCAmelCase__ : Any = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _A ) def lowercase_ ( self : Any ): '''simple docstring''' def check_hidden_states_output(_A : Dict , _A : Optional[Any] , _A : Dict ): UpperCAmelCase__ : str = model_class(_A ) UpperCAmelCase__ : List[str] = model(**self._prepare_for_class(_A , _A ) ) UpperCAmelCase__ : Tuple = outputs.hidden_states UpperCAmelCase__ : int = len(self.model_tester.depth ) self.assertEqual(len(_A ) , _A ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) UpperCAmelCase__ , UpperCAmelCase__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase__ : Tuple = True check_hidden_states_output(_A , _A , _A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase__ : List[str] = True check_hidden_states_output(_A , _A , _A ) def lowercase_ ( self : Tuple ): '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_A ) def lowercase_ ( self : str ): '''simple docstring''' UpperCAmelCase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_A ) @slow def lowercase_ ( self : Optional[Any] ): '''simple docstring''' for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase__ : Optional[int] = TFCvtModel.from_pretrained(_A ) self.assertIsNotNone(_A ) def a__ ( ) -> Any: UpperCAmelCase__ : str = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_tf @require_vision class lowerCamelCase_ ( unittest.TestCase ): @cached_property def lowercase_ ( self : Union[str, Any] ): '''simple docstring''' return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def lowercase_ ( self : Any ): '''simple docstring''' UpperCAmelCase__ : Dict = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) UpperCAmelCase__ : Union[str, Any] = self.default_image_processor UpperCAmelCase__ : Optional[Any] = prepare_img() UpperCAmelCase__ : Tuple = image_processor(images=_A , return_tensors='''tf''' ) # forward pass UpperCAmelCase__ : Optional[Any] = model(**_A ) # verify the logits UpperCAmelCase__ : Union[str, Any] = tf.TensorShape((1, 1_000) ) self.assertEqual(outputs.logits.shape , _A ) UpperCAmelCase__ : Union[str, Any] = tf.constant([0.9_2_8_5, 0.9_0_1_5, -0.3_1_5_0] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , _A , atol=1e-4 ) )
181
1
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 __lowerCamelCase ( a__ ): '''simple docstring''' A_ : List[Any] = 'char' A_ : Optional[int] = 'bpe' A_ : Optional[int] = 'wp' __snake_case = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class __lowerCamelCase ( a__ ): '''simple docstring''' A_ : str = ['image_processor', 'char_tokenizer'] A_ : List[str] = 'ViTImageProcessor' A_ : int = 'MgpstrTokenizer' def __init__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ) -> Dict: _a = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , __UpperCAmelCase , ) _a = kwargs.pop('''feature_extractor''' ) _a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) _a = tokenizer _a = AutoTokenizer.from_pretrained('''gpt2''' ) _a = AutoTokenizer.from_pretrained('''bert-base-uncased''' ) super().__init__(__UpperCAmelCase , __UpperCAmelCase ) def __call__( self , __UpperCAmelCase=None , __UpperCAmelCase=None , __UpperCAmelCase=None , **__UpperCAmelCase ) -> int: if images is None and text is None: raise ValueError('''You need to specify either an `images` or `text` input to process.''' ) if images is not None: _a = self.image_processor(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if text is not None: _a = self.char_tokenizer(__UpperCAmelCase , return_tensors=__UpperCAmelCase , **__UpperCAmelCase ) if text is None: return inputs elif images is None: return encodings else: _a = encodings['''input_ids'''] return inputs def _UpperCAmelCase ( self , __UpperCAmelCase ) -> Union[str, Any]: _a , _a , _a = sequences _a = char_preds.size(0 ) _a , _a = self._decode_helper(__UpperCAmelCase , '''char''' ) _a , _a = self._decode_helper(__UpperCAmelCase , '''bpe''' ) _a , _a = self._decode_helper(__UpperCAmelCase , '''wp''' ) _a = [] _a = [] for i in range(__UpperCAmelCase ): _a = [char_scores[i], bpe_scores[i], wp_scores[i]] _a = [char_strs[i], bpe_strs[i], wp_strs[i]] _a = scores.index(max(__UpperCAmelCase ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) _a = {} _a = final_strs _a = final_scores _a = char_strs _a = bpe_strs _a = wp_strs return out def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase ) -> str: if format == DecodeType.CHARACTER: _a = self.char_decode _a = 1 _a = '''[s]''' elif format == DecodeType.BPE: _a = self.bpe_decode _a = 2 _a = '''#''' elif format == DecodeType.WORDPIECE: _a = self.wp_decode _a = 102 _a = '''[SEP]''' else: raise ValueError(F'Format {format} is not supported.' ) _a , _a = [], [] _a = pred_logits.size(0 ) _a = pred_logits.size(1 ) _a , _a = pred_logits.topk(1 , dim=-1 , largest=__UpperCAmelCase , sorted=__UpperCAmelCase ) _a = preds_index.view(-1 , __UpperCAmelCase )[:, 1:] _a = decoder(__UpperCAmelCase ) _a , _a = torch.nn.functional.softmax(__UpperCAmelCase , dim=2 ).max(dim=2 ) _a = preds_max_prob[:, 1:] for index in range(__UpperCAmelCase ): _a = preds_str[index].find(__UpperCAmelCase ) _a = preds_str[index][:pred_eos] _a = preds_index[index].cpu().tolist() _a = pred_index.index(__UpperCAmelCase ) if eos_token in pred_index else -1 _a = preds_max_prob[index][: pred_eos_index + 1] _a = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(__UpperCAmelCase ) conf_scores.append(__UpperCAmelCase ) return dec_strs, conf_scores def _UpperCAmelCase ( self , __UpperCAmelCase ) -> Optional[Any]: _a = [seq.replace(''' ''' , '''''' ) for seq in self.char_tokenizer.batch_decode(__UpperCAmelCase )] return decode_strs def _UpperCAmelCase ( self , __UpperCAmelCase ) -> Dict: return self.bpe_tokenizer.batch_decode(__UpperCAmelCase ) def _UpperCAmelCase ( self , __UpperCAmelCase ) -> Union[str, Any]: _a = [seq.replace(''' ''' , '''''' ) for seq in self.wp_tokenizer.batch_decode(__UpperCAmelCase )] return decode_strs
353
"""simple docstring""" from pathlib import Path import fire from tqdm import tqdm def A_ ( _lowerCAmelCase : str="ro", _lowerCAmelCase : Optional[Any]="en", _lowerCAmelCase : Union[str, Any]="wmt16", _lowerCAmelCase : int=None ): """simple docstring""" try: import datasets except (ModuleNotFoundError, ImportError): raise ImportError('''run pip install datasets''' ) _a = f'{src_lang}-{tgt_lang}' print(f'Converting {dataset}-{pair}' ) _a = datasets.load_dataset(_lowerCAmelCase, _lowerCAmelCase ) if save_dir is None: _a = f'{dataset}-{pair}' _a = Path(_lowerCAmelCase ) save_dir.mkdir(exist_ok=_lowerCAmelCase ) for split in ds.keys(): print(f'Splitting {split} with {ds[split].num_rows} records' ) # to save to val.source, val.target like summary datasets _a = '''val''' if split == '''validation''' else split _a = save_dir.joinpath(f'{fn}.source' ) _a = save_dir.joinpath(f'{fn}.target' ) _a = src_path.open('''w+''' ) _a = tgt_path.open('''w+''' ) # reader is the bottleneck so writing one record at a time doesn't slow things down for x in tqdm(ds[split] ): _a = x['''translation'''] src_fp.write(ex[src_lang] + '''\n''' ) tgt_fp.write(ex[tgt_lang] + '''\n''' ) print(f'Saved {dataset} dataset to {save_dir}' ) if __name__ == "__main__": fire.Fire(download_wmt_dataset)
153
0
"""simple docstring""" import argparse import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## __lowerCamelCase = 16 __lowerCamelCase = 32 def UpperCAmelCase ( UpperCamelCase__ , UpperCamelCase__ = 16 ): """simple docstring""" A__ = AutoTokenizer.from_pretrained('bert-base-cased' ) A__ = load_dataset('glue' , 'mrpc' ) def tokenize_function(UpperCamelCase__ ): # max_length=None => use the model max length (it's actually the default) A__ = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=UpperCamelCase__ , max_length=UpperCamelCase__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): A__ = datasets.map( UpperCamelCase__ , batched=UpperCamelCase__ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library A__ = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(UpperCamelCase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. A__ = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": A__ = 16 elif accelerator.mixed_precision != "no": A__ = 8 else: A__ = None return tokenizer.pad( UpperCamelCase__ , padding='longest' , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors='pt' , ) # Instantiate dataloaders. A__ = DataLoader( tokenized_datasets['train'] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ , drop_last=UpperCamelCase__ ) A__ = DataLoader( tokenized_datasets['validation'] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ , drop_last=(accelerator.mixed_precision == 'fp8') , ) return train_dataloader, eval_dataloader def UpperCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" A__ = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs A__ = config['lr'] A__ = int(config['num_epochs'] ) A__ = int(config['seed'] ) A__ = int(config['batch_size'] ) A__ = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation A__ = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: A__ = batch_size // MAX_GPU_BATCH_SIZE A__ = MAX_GPU_BATCH_SIZE set_seed(UpperCamelCase__ ) A__ , A__ = get_dataloaders(UpperCamelCase__ , UpperCamelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) A__ = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=UpperCamelCase__ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). A__ = model.to(accelerator.device ) # Instantiate optimizer A__ = AdamW(params=model.parameters() , lr=UpperCamelCase__ ) # Instantiate scheduler A__ = get_linear_schedule_with_warmup( optimizer=UpperCamelCase__ , num_warmup_steps=100 , num_training_steps=(len(UpperCamelCase__ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. A__ , A__ , A__ , A__ , A__ = accelerator.prepare( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Now we train the model for epoch in range(UpperCamelCase__ ): model.train() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) A__ = model(**UpperCamelCase__ ) A__ = outputs.loss A__ = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(UpperCamelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): A__ = model(**UpperCamelCase__ ) A__ = outputs.logits.argmax(dim=-1 ) A__ , A__ = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=UpperCamelCase__ , references=UpperCamelCase__ , ) A__ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F'''epoch {epoch}:''' , UpperCamelCase__ ) def UpperCAmelCase ( ): """simple docstring""" A__ = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=UpperCamelCase__ , default=UpperCamelCase__ , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) A__ = parser.parse_args() A__ = {'lr': 2E-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": main()
221
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available __lowerCamelCase = { "configuration_vivit": ["VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP", "VivitConfig"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = ["VivitImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase = [ "VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST", "VivitModel", "VivitPreTrainedModel", "VivitForVideoClassification", ] if TYPE_CHECKING: from .configuration_vivit import VIVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, VivitConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_vivit import VivitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vivit import ( VIVIT_PRETRAINED_MODEL_ARCHIVE_LIST, VivitForVideoClassification, VivitModel, VivitPreTrainedModel, ) else: import sys __lowerCamelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
221
1
'''simple docstring''' import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() snake_case_ : List[Any] = logging.get_logger('transformers.models.speecht5') def A__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ): hf_model.apply_weight_norm() _UpperCamelCase : Any = checkpoint['input_conv.weight_g'] _UpperCamelCase : Optional[int] = checkpoint['input_conv.weight_v'] _UpperCamelCase : str = checkpoint['input_conv.bias'] for i in range(len(config.upsample_rates ) ): _UpperCamelCase : List[str] = checkpoint[f'upsamples.{i}.1.weight_g'] _UpperCamelCase : List[str] = checkpoint[f'upsamples.{i}.1.weight_v'] _UpperCamelCase : Optional[Any] = checkpoint[f'upsamples.{i}.1.bias'] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): _UpperCamelCase : Optional[Any] = checkpoint[f'blocks.{i}.convs1.{j}.1.weight_g'] _UpperCamelCase : List[Any] = checkpoint[f'blocks.{i}.convs1.{j}.1.weight_v'] _UpperCamelCase : Any = checkpoint[f'blocks.{i}.convs1.{j}.1.bias'] _UpperCamelCase : Union[str, Any] = checkpoint[f'blocks.{i}.convs2.{j}.1.weight_g'] _UpperCamelCase : Optional[int] = checkpoint[f'blocks.{i}.convs2.{j}.1.weight_v'] _UpperCamelCase : str = checkpoint[f'blocks.{i}.convs2.{j}.1.bias'] _UpperCamelCase : int = checkpoint['output_conv.1.weight_g'] _UpperCamelCase : List[str] = checkpoint['output_conv.1.weight_v'] _UpperCamelCase : List[Any] = checkpoint['output_conv.1.bias'] hf_model.remove_weight_norm() @torch.no_grad() def A__ ( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_=None , UpperCAmelCase_=None , ): if config_path is not None: _UpperCamelCase : List[Any] = SpeechTaHifiGanConfig.from_pretrained(UpperCAmelCase_ ) else: _UpperCamelCase : Tuple = SpeechTaHifiGanConfig() _UpperCamelCase : int = SpeechTaHifiGan(UpperCAmelCase_ ) _UpperCamelCase : Optional[int] = torch.load(UpperCAmelCase_ ) load_weights(orig_checkpoint['model']['generator'] , UpperCAmelCase_ , UpperCAmelCase_ ) _UpperCamelCase : int = np.load(UpperCAmelCase_ ) _UpperCamelCase : Any = stats[0].reshape(-1 ) _UpperCamelCase : Dict = stats[1].reshape(-1 ) _UpperCamelCase : Tuple = torch.from_numpy(UpperCAmelCase_ ).float() _UpperCamelCase : int = torch.from_numpy(UpperCAmelCase_ ).float() model.save_pretrained(UpperCAmelCase_ ) if repo_id: print('Pushing to the hub...' ) model.push_to_hub(UpperCAmelCase_ ) if __name__ == "__main__": snake_case_ : Optional[int] = argparse.ArgumentParser() parser.add_argument('--checkpoint_path', required=True, default=None, type=str, help='Path to original checkpoint') parser.add_argument('--stats_path', required=True, default=None, type=str, help='Path to stats.npy file') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument( '--pytorch_dump_folder_path', required=True, default=None, type=str, help='Path to the output PyTorch model.' ) parser.add_argument( '--push_to_hub', default=None, type=str, help='Where to upload the converted model on the 🤗 hub.' ) snake_case_ : List[str] = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
236
'''simple docstring''' from __future__ import annotations def A__ ( UpperCAmelCase_ ): if not nums: return 0 _UpperCamelCase : Any = nums[0] _UpperCamelCase : Optional[int] = 0 for num in nums[1:]: _UpperCamelCase , _UpperCamelCase : Optional[Any] = ( max_excluding + num, max(UpperCAmelCase_ , UpperCAmelCase_ ), ) return max(UpperCAmelCase_ , UpperCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod()
236
1
'''simple docstring''' def a ( __a , __a , __a , __a ) -> str: '''simple docstring''' if height >= 1: move_tower(height - 1 , __a , __a , __a ) move_disk(__a , __a ) move_tower(height - 1 , __a , __a , __a ) def a ( __a , __a ) -> str: '''simple docstring''' print('''moving disk from''' , __a , '''to''' , __a ) def a ( ) -> Optional[Any]: '''simple docstring''' UpperCamelCase__ :Optional[int] = int(input('''Height of hanoi: ''' ).strip() ) move_tower(__a , '''A''' , '''B''' , '''C''' ) if __name__ == "__main__": main()
97
'''simple docstring''' import unittest from dataclasses import dataclass import pytest from accelerate.commands.config.config_args import SageMakerConfig from accelerate.utils import ComputeEnvironment from accelerate.utils.launch import _convert_nargs_to_dict @dataclass class lowercase ( A__ ): """simple docstring""" _a = ComputeEnvironment.AMAZON_SAGEMAKER _a = True _a = 'ml.p3.2xlarge' _a = 'accelerate_sagemaker_execution_role' _a = 'hf-sm' _a = 'us-east-1' _a = 1 _a = 'accelerate-sagemaker-1' _a = '1.6' _a = '4.4' _a = 'train.py' _a = [ '--model_name_or_path', 'bert', '--do_train', 'False', '--epochs', '3', '--learning_rate', '5e-5', '--max_steps', '50.5', ] _a = [ '--model_name_or_path', 'bert', '--do_train', '--do_test', 'False', '--do_predict', '--epochs', '3', '--learning_rate', '5e-5', '--max_steps', '50.5', ] class lowercase ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Union[str, Any] = _convert_nargs_to_dict(MockLaunchConfig.success_training_script_args ) assert isinstance(converted_args['''model_name_or_path'''] , UpperCamelCase_ ) assert isinstance(converted_args['''do_train'''] , UpperCamelCase_ ) assert isinstance(converted_args['''epochs'''] , UpperCamelCase_ ) assert isinstance(converted_args['''learning_rate'''] , UpperCamelCase_ ) assert isinstance(converted_args['''max_steps'''] , UpperCamelCase_ ) with pytest.raises(UpperCamelCase_ ): _convert_nargs_to_dict(MockLaunchConfig.fail_training_script_args )
97
1
def __lowerCAmelCase ( ): lowercase__ = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] lowercase__ = 6 lowercase__ = 1 lowercase__ = 1901 lowercase__ = 0 while year < 2001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 lowercase__ = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 lowercase__ = day - 29 else: if day > days_per_month[month - 1]: month += 1 lowercase__ = day - days_per_month[month - 2] if month > 12: year += 1 lowercase__ = 1 if year < 2001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
224
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() lowercase_ = logging.get_logger(__name__) def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ ): lowercase__ = "huggingface/label-files" lowercase__ = "imagenet-1k-id2label.json" lowercase__ = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , repo_type="dataset" ) , "r" ) ) lowercase__ = {int(SCREAMING_SNAKE_CASE_ ): v for k, v in idalabel.items()} lowercase__ = {v: k for k, v in idalabel.items()} lowercase__ = "std_conv" if "bit" in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" lowercase__ = BitConfig( conv_layer=SCREAMING_SNAKE_CASE_ , num_labels=1000 , idalabel=SCREAMING_SNAKE_CASE_ , labelaid=SCREAMING_SNAKE_CASE_ , ) return config def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ ): if "stem.conv" in name: lowercase__ = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: lowercase__ = name.replace("blocks" , "layers" ) if "head.fc" in name: lowercase__ = name.replace("head.fc" , "classifier.1" ) if name.startswith("norm" ): lowercase__ = "bit." + name if "bit" not in name and "classifier" not in name: lowercase__ = "bit.encoder." + name return name def __lowerCAmelCase ( ): lowercase__ = "http://images.cocodataset.org/val2017/000000039769.jpg" lowercase__ = Image.open(requests.get(SCREAMING_SNAKE_CASE_ , stream=SCREAMING_SNAKE_CASE_ ).raw ) return im @torch.no_grad() def __lowerCAmelCase ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=False ): lowercase__ = get_config(SCREAMING_SNAKE_CASE_ ) # load original model from timm lowercase__ = create_model(SCREAMING_SNAKE_CASE_ , pretrained=SCREAMING_SNAKE_CASE_ ) timm_model.eval() # load state_dict of original model lowercase__ = timm_model.state_dict() for key in state_dict.copy().keys(): lowercase__ = state_dict.pop(SCREAMING_SNAKE_CASE_ ) lowercase__ = val.squeeze() if "head" in key else val # load HuggingFace model lowercase__ = BitForImageClassification(SCREAMING_SNAKE_CASE_ ) model.eval() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # create image processor lowercase__ = create_transform(**resolve_data_config({} , model=SCREAMING_SNAKE_CASE_ ) ) lowercase__ = transform.transforms lowercase__ = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } lowercase__ = BitImageProcessor( do_resize=SCREAMING_SNAKE_CASE_ , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=SCREAMING_SNAKE_CASE_ , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=SCREAMING_SNAKE_CASE_ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) lowercase__ = prepare_img() lowercase__ = transform(SCREAMING_SNAKE_CASE_ ).unsqueeze(0 ) lowercase__ = processor(SCREAMING_SNAKE_CASE_ , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # verify logits with torch.no_grad(): lowercase__ = model(SCREAMING_SNAKE_CASE_ ) lowercase__ = outputs.logits print("Logits:" , logits[0, :3] ) print("Predicted class:" , model.config.idalabel[logits.argmax(-1 ).item()] ) lowercase__ = timm_model(SCREAMING_SNAKE_CASE_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(SCREAMING_SNAKE_CASE_ , outputs.logits , atol=1e-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) print(f'''Saving model {model_name} and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) processor.save_pretrained(SCREAMING_SNAKE_CASE_ ) if push_to_hub: print(f'''Pushing model {model_name} and processor to the hub''' ) model.push_to_hub(f'''ybelkada/{model_name}''' ) processor.push_to_hub(f'''ybelkada/{model_name}''' ) if __name__ == "__main__": lowercase_ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""resnetv2_50x1_bitm""", type=str, help="""Name of the BiT timm model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether to push the model to the hub.""", ) lowercase_ = parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
224
1
from math import ceil, sqrt def UpperCamelCase__( UpperCamelCase__ : int = 1_00_00_00 )->Union[str, Any]: A__ = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: A__ = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: A__ = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(F"{solution() = }")
193
from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline lowerCamelCase__ = logging.get_logger(__name__) @add_end_docstrings(lowerCamelCase__ ) class SCREAMING_SNAKE_CASE ( lowerCamelCase__ ): def __init__( self : Optional[int] , **__lowercase : Dict ): '''simple docstring''' super().__init__(**__lowercase ) if self.framework != "pt": raise ValueError(F"The {self.__class__} is only available in PyTorch." ) # No specific FOR_XXX available yet def __call__( self : str , __lowercase : Union[np.ndarray, bytes, str] , **__lowercase : int ): '''simple docstring''' return super().__call__(__lowercase , **__lowercase ) def UpperCamelCase_ ( self : List[Any] , **__lowercase : Union[str, Any] ): '''simple docstring''' __a = {} if "candidate_labels" in kwargs: __a = kwargs["""candidate_labels"""] if "hypothesis_template" in kwargs: __a = kwargs["""hypothesis_template"""] return preprocess_params, {}, {} def UpperCamelCase_ ( self : int , __lowercase : Dict , __lowercase : Dict=None , __lowercase : str="This is a sound of {}." ): '''simple docstring''' if isinstance(__lowercase , __lowercase ): if audio.startswith("""http://""" ) or audio.startswith("""https://""" ): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(__lowercase ).content else: with open(__lowercase , """rb""" ) as f: __a = f.read() if isinstance(__lowercase , __lowercase ): __a = ffmpeg_read(__lowercase , self.feature_extractor.sampling_rate ) if not isinstance(__lowercase , np.ndarray ): raise ValueError("""We expect a numpy ndarray as input""" ) if len(audio.shape ) != 1: raise ValueError("""We expect a single channel audio input for ZeroShotAudioClassificationPipeline""" ) __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors="""pt""" ) __a = candidate_labels __a = [hypothesis_template.format(__lowercase ) for x in candidate_labels] __a = self.tokenizer(__lowercase , return_tensors=self.framework , padding=__lowercase ) __a = [text_inputs] return inputs def UpperCamelCase_ ( self : Any , __lowercase : Any ): '''simple docstring''' __a = model_inputs.pop("""candidate_labels""" ) __a = model_inputs.pop("""text_inputs""" ) if isinstance(text_inputs[0] , __lowercase ): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**__lowercase , **__lowercase ) __a = { """candidate_labels""": candidate_labels, """logits""": outputs.logits_per_audio, } return model_outputs def UpperCamelCase_ ( self : Optional[Any] , __lowercase : Dict ): '''simple docstring''' __a = model_outputs.pop("""candidate_labels""" ) __a = model_outputs["""logits"""][0] if self.framework == "pt": __a = logits.softmax(dim=0 ) __a = probs.tolist() else: raise ValueError("""`tf` framework not supported.""" ) __a = [ {"""score""": score, """label""": candidate_label} for score, candidate_label in sorted(zip(__lowercase , __lowercase ) , key=lambda __lowercase : -x[0] ) ] return result
302
0
from __future__ import annotations def __lowerCamelCase (UpperCAmelCase__ : list[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ): if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = array[indexa], array[indexa] def __lowerCamelCase (UpperCAmelCase__ : list[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ): if length > 1: SCREAMING_SNAKE_CASE = int(length / 2 ) for i in range(UpperCAmelCase__ , low + middle ): comp_and_swap(UpperCAmelCase__ , UpperCAmelCase__ , i + middle , UpperCAmelCase__ ) bitonic_merge(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) bitonic_merge(UpperCAmelCase__ , low + middle , UpperCAmelCase__ , UpperCAmelCase__ ) def __lowerCamelCase (UpperCAmelCase__ : list[int] , UpperCAmelCase__ : int , UpperCAmelCase__ : int , UpperCAmelCase__ : int ): if length > 1: SCREAMING_SNAKE_CASE = int(length / 2 ) bitonic_sort(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , 1 ) bitonic_sort(UpperCAmelCase__ , low + middle , UpperCAmelCase__ , 0 ) bitonic_merge(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) if __name__ == "__main__": _lowerCamelCase : List[Any] = input('''Enter numbers separated by a comma:\n''').strip() _lowerCamelCase : Union[str, Any] = [int(item.strip()) for item in user_input.split(''',''')] bitonic_sort(unsorted, 0, len(unsorted), 1) print('''\nSorted array in ascending order is: ''', end='''''') print(*unsorted, sep=''', ''') bitonic_merge(unsorted, 0, len(unsorted), 0) print('''Sorted array in descending order is: ''', end='''''') print(*unsorted, sep=''', ''')
206
import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer _lowerCamelCase : Union[str, Any] = logging.get_logger(__name__) _lowerCamelCase : str = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} _lowerCamelCase : int = { '''vocab_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json''', }, '''merges_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json''', }, } _lowerCamelCase : List[Any] = { '''allenai/led-base-16384''': 1_63_84, } class lowercase ( a ): lowercase__ : Tuple = VOCAB_FILES_NAMES lowercase__ : Any = PRETRAINED_VOCAB_FILES_MAP lowercase__ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ : Optional[Any] = LEDTokenizer lowercase__ : str = ["""input_ids""", """attention_mask"""] def __init__( self : Union[str, Any] , _UpperCamelCase : Tuple=None , _UpperCamelCase : str=None , _UpperCamelCase : Tuple=None , _UpperCamelCase : List[str]="replace" , _UpperCamelCase : str="<s>" , _UpperCamelCase : List[Any]="</s>" , _UpperCamelCase : List[Any]="</s>" , _UpperCamelCase : List[str]="<s>" , _UpperCamelCase : Tuple="<unk>" , _UpperCamelCase : List[Any]="<pad>" , _UpperCamelCase : Tuple="<mask>" , _UpperCamelCase : List[str]=False , _UpperCamelCase : List[Any]=True , **_UpperCamelCase : Optional[Any] , ) -> Tuple: '''simple docstring''' super().__init__( _UpperCamelCase , _UpperCamelCase , tokenizer_file=_UpperCamelCase , errors=_UpperCamelCase , bos_token=_UpperCamelCase , eos_token=_UpperCamelCase , sep_token=_UpperCamelCase , cls_token=_UpperCamelCase , unk_token=_UpperCamelCase , pad_token=_UpperCamelCase , mask_token=_UpperCamelCase , add_prefix_space=_UpperCamelCase , trim_offsets=_UpperCamelCase , **_UpperCamelCase , ) SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , _UpperCamelCase ) != add_prefix_space: SCREAMING_SNAKE_CASE = getattr(_UpperCamelCase , pre_tok_state.pop("type" ) ) SCREAMING_SNAKE_CASE = add_prefix_space SCREAMING_SNAKE_CASE = pre_tok_class(**_UpperCamelCase ) SCREAMING_SNAKE_CASE = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` SCREAMING_SNAKE_CASE = "post_processor" SCREAMING_SNAKE_CASE = getattr(self.backend_tokenizer , _UpperCamelCase , _UpperCamelCase ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE = 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: SCREAMING_SNAKE_CASE = tuple(state["sep"] ) if "cls" in state: SCREAMING_SNAKE_CASE = tuple(state["cls"] ) SCREAMING_SNAKE_CASE = False if state.get("add_prefix_space" , _UpperCamelCase ) != add_prefix_space: SCREAMING_SNAKE_CASE = add_prefix_space SCREAMING_SNAKE_CASE = True if state.get("trim_offsets" , _UpperCamelCase ) != trim_offsets: SCREAMING_SNAKE_CASE = trim_offsets SCREAMING_SNAKE_CASE = True if changes_to_apply: SCREAMING_SNAKE_CASE = getattr(_UpperCamelCase , state.pop("type" ) ) SCREAMING_SNAKE_CASE = component_class(**_UpperCamelCase ) setattr(self.backend_tokenizer , _UpperCamelCase , _UpperCamelCase ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def __snake_case( self : int ) -> str: '''simple docstring''' 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 : Optional[int] , _UpperCamelCase : Optional[int] ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = AddedToken(_UpperCamelCase , lstrip=_UpperCamelCase , rstrip=_UpperCamelCase ) if isinstance(_UpperCamelCase , _UpperCamelCase ) else value SCREAMING_SNAKE_CASE = value def __snake_case( self : List[Any] , *_UpperCamelCase : Optional[int] , **_UpperCamelCase : Union[str, Any] ) -> BatchEncoding: '''simple docstring''' SCREAMING_SNAKE_CASE = kwargs.get("is_split_into_words" , _UpperCamelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : int , *_UpperCamelCase : Dict , **_UpperCamelCase : Tuple ) -> BatchEncoding: '''simple docstring''' SCREAMING_SNAKE_CASE = kwargs.get("is_split_into_words" , _UpperCamelCase ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*_UpperCamelCase , **_UpperCamelCase ) def __snake_case( self : List[Any] , _UpperCamelCase : str , _UpperCamelCase : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' SCREAMING_SNAKE_CASE = self._tokenizer.model.save(_UpperCamelCase , name=_UpperCamelCase ) return tuple(_UpperCamelCase ) def __snake_case( self : List[Any] , _UpperCamelCase : List[Any] , _UpperCamelCase : int=None ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = [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 , _UpperCamelCase : List[int] , _UpperCamelCase : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = [self.sep_token_id] SCREAMING_SNAKE_CASE = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __snake_case( self : Optional[Any] , _UpperCamelCase : Union[Dict[str, EncodedInput], BatchEncoding] , _UpperCamelCase : Optional[int] = None , _UpperCamelCase : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , _UpperCamelCase : Optional[int] = None , _UpperCamelCase : Optional[bool] = None , ) -> dict: '''simple docstring''' SCREAMING_SNAKE_CASE = super()._pad( encoded_inputs=_UpperCamelCase , max_length=_UpperCamelCase , padding_strategy=_UpperCamelCase , pad_to_multiple_of=_UpperCamelCase , return_attention_mask=_UpperCamelCase , ) # Load from model defaults if return_attention_mask is None: SCREAMING_SNAKE_CASE = "attention_mask" in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: SCREAMING_SNAKE_CASE = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. SCREAMING_SNAKE_CASE = len(encoded_inputs["global_attention_mask"] ) != len(_UpperCamelCase ) if needs_to_be_padded: SCREAMING_SNAKE_CASE = len(_UpperCamelCase ) - len(encoded_inputs["global_attention_mask"] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` SCREAMING_SNAKE_CASE = ( encoded_inputs["global_attention_mask"] + [-1] * difference ) elif self.padding_side == "left": SCREAMING_SNAKE_CASE = [-1] * difference + encoded_inputs[ "global_attention_mask" ] else: raise ValueError("Invalid padding strategy:" + str(self.padding_side ) ) return encoded_inputs
206
1
import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class A_ : def __init__( self , _A=2 , _A=3 , _A=6_4 , _A=None ): '''simple docstring''' UpperCAmelCase = np.random.default_rng(_A ) UpperCAmelCase = length UpperCAmelCase = rng.normal(size=(length,) ).astype(np.floataa ) UpperCAmelCase = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ): '''simple docstring''' return self.length def __getitem__( self , _A ): '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class A_ (torch.nn.Module ): def __init__( self , _A=0 , _A=0 , _A=False ): '''simple docstring''' super().__init__() UpperCAmelCase = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) UpperCAmelCase = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) UpperCAmelCase = True def _lowercase ( self , _A=None ): '''simple docstring''' if self.first_batch: print(F"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}""" ) UpperCAmelCase = False return x * self.a[0] + self.b[0] class A_ (torch.nn.Module ): def __init__( self , _A=0 , _A=0 , _A=False ): '''simple docstring''' super().__init__() UpperCAmelCase = torch.nn.Parameter(torch.tensor(_A ).float() ) UpperCAmelCase = torch.nn.Parameter(torch.tensor(_A ).float() ) UpperCAmelCase = True def _lowercase ( self , _A=None ): '''simple docstring''' if self.first_batch: print(F"""Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}""" ) UpperCAmelCase = False return x * self.a + self.b def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ = 16 ) -> Union[str, Any]: '''simple docstring''' from datasets import load_dataset from transformers import AutoTokenizer UpperCAmelCase = AutoTokenizer.from_pretrained('''bert-base-cased''' ) UpperCAmelCase = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} UpperCAmelCase = load_dataset('''csv''' , data_files=UpperCamelCase__ ) UpperCAmelCase = datasets['''train'''].unique('''label''' ) UpperCAmelCase = {v: i for i, v in enumerate(UpperCamelCase__ )} def tokenize_function(UpperCamelCase__ ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=UpperCamelCase__ , max_length=UpperCamelCase__ , padding='''max_length''' ) if "label" in examples: UpperCAmelCase = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase = datasets.map( UpperCamelCase__ , batched=UpperCamelCase__ , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(UpperCamelCase__ ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(UpperCamelCase__ , padding='''max_length''' , max_length=128 , return_tensors='''pt''' ) return tokenizer.pad(UpperCamelCase__ , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. UpperCAmelCase = DataLoader(tokenized_datasets['''train'''] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=2 ) UpperCAmelCase = DataLoader(tokenized_datasets['''validation'''] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=1 ) return train_dataloader, eval_dataloader
273
import argparse import torch from transformers import YosoConfig, YosoForMaskedLM def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ ) -> Union[str, Any]: '''simple docstring''' if "model" in orig_key: UpperCAmelCase = orig_key.replace('''model.''' , '''''' ) if "norm1" in orig_key: UpperCAmelCase = orig_key.replace('''norm1''' , '''attention.output.LayerNorm''' ) if "norm2" in orig_key: UpperCAmelCase = orig_key.replace('''norm2''' , '''output.LayerNorm''' ) if "norm" in orig_key: UpperCAmelCase = orig_key.replace('''norm''' , '''LayerNorm''' ) if "transformer" in orig_key: UpperCAmelCase = orig_key.split('''.''' )[0].split('''_''' )[-1] UpperCAmelCase = orig_key.replace(F"""transformer_{layer_num}""" , F"""encoder.layer.{layer_num}""" ) if "mha.attn" in orig_key: UpperCAmelCase = orig_key.replace('''mha.attn''' , '''attention.self''' ) if "mha" in orig_key: UpperCAmelCase = orig_key.replace('''mha''' , '''attention''' ) if "W_q" in orig_key: UpperCAmelCase = orig_key.replace('''W_q''' , '''self.query''' ) if "W_k" in orig_key: UpperCAmelCase = orig_key.replace('''W_k''' , '''self.key''' ) if "W_v" in orig_key: UpperCAmelCase = orig_key.replace('''W_v''' , '''self.value''' ) if "ff1" in orig_key: UpperCAmelCase = orig_key.replace('''ff1''' , '''intermediate.dense''' ) if "ff2" in orig_key: UpperCAmelCase = orig_key.replace('''ff2''' , '''output.dense''' ) if "ff" in orig_key: UpperCAmelCase = orig_key.replace('''ff''' , '''output.dense''' ) if "mlm_class" in orig_key: UpperCAmelCase = orig_key.replace('''mlm.mlm_class''' , '''cls.predictions.decoder''' ) if "mlm" in orig_key: UpperCAmelCase = orig_key.replace('''mlm''' , '''cls.predictions.transform''' ) if "cls" not in orig_key: UpperCAmelCase = '''yoso.''' + orig_key return orig_key def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ ) -> Dict: '''simple docstring''' for key in orig_state_dict.copy().keys(): UpperCAmelCase = orig_state_dict.pop(UpperCamelCase__ ) if ("pooler" in key) or ("sen_class" in key): continue else: UpperCAmelCase = val UpperCAmelCase = orig_state_dict['''cls.predictions.decoder.bias'''] UpperCAmelCase = torch.arange(UpperCamelCase__ ).expand((1, -1) ) + 2 return orig_state_dict def __SCREAMING_SNAKE_CASE ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> int: '''simple docstring''' UpperCAmelCase = torch.load(UpperCamelCase__ , map_location='''cpu''' )['''model_state_dict'''] UpperCAmelCase = YosoConfig.from_json_file(UpperCamelCase__ ) UpperCAmelCase = YosoForMaskedLM(UpperCamelCase__ ) UpperCAmelCase = convert_checkpoint_helper(config.max_position_embeddings , UpperCamelCase__ ) print(model.load_state_dict(UpperCamelCase__ ) ) model.eval() model.save_pretrained(UpperCamelCase__ ) print(F"""Checkpoint successfuly converted. Model saved at {pytorch_dump_path}""" ) if __name__ == "__main__": __A : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--pytorch_model_path", default=None, type=str, required=True, help="Path to YOSO pytorch checkpoint." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The json file for YOSO model config.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) __A : List[str] = parser.parse_args() convert_yoso_checkpoint(args.pytorch_model_path, args.config_file, args.pytorch_dump_path)
273
1
"""simple docstring""" def UpperCamelCase_ ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : str ) -> List[Any]: """simple docstring""" return (pointa[0] - pointa[0]) ** 2 + (pointa[1] - pointa[1]) ** 2 def UpperCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str=0 ) -> Union[str, Any]: """simple docstring""" return sorted(lowerCAmelCase__ , key=lambda lowerCAmelCase__ : x[column] ) def UpperCamelCase_ ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any]=float('inf' ) ) -> Optional[int]: """simple docstring""" for i in range(points_counts - 1 ): for j in range(i + 1 , lowerCAmelCase__ ): lowerCAmelCase_ : Union[str, Any] = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: lowerCAmelCase_ : Optional[int] = current_dis return min_dis def UpperCamelCase_ ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Union[str, Any]=float('inf' ) ) -> Dict: """simple docstring""" for i in range(min(6 , points_counts - 1 ) , lowerCAmelCase__ ): for j in range(max(0 , i - 6 ) , lowerCAmelCase__ ): lowerCAmelCase_ : Any = euclidean_distance_sqr(points[i] , points[j] ) if current_dis < min_dis: lowerCAmelCase_ : Union[str, Any] = current_dis return min_dis def UpperCamelCase_ ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[int] ) -> Dict: """simple docstring""" if points_counts <= 3: return dis_between_closest_pair(lowerCAmelCase__ , lowerCAmelCase__ ) # recursion lowerCAmelCase_ : int = points_counts // 2 lowerCAmelCase_ : Optional[Any] = closest_pair_of_points_sqr( lowerCAmelCase__ , points_sorted_on_y[:mid] , lowerCAmelCase__ ) lowerCAmelCase_ : Optional[Any] = closest_pair_of_points_sqr( lowerCAmelCase__ , points_sorted_on_y[mid:] , points_counts - mid ) lowerCAmelCase_ : Any = min(lowerCAmelCase__ , lowerCAmelCase__ ) lowerCAmelCase_ : str = [] for point in points_sorted_on_x: if abs(point[0] - points_sorted_on_x[mid][0] ) < closest_pair_dis: cross_strip.append(lowerCAmelCase__ ) lowerCAmelCase_ : List[Any] = dis_between_closest_in_strip( lowerCAmelCase__ , len(lowerCAmelCase__ ) , lowerCAmelCase__ ) return min(lowerCAmelCase__ , lowerCAmelCase__ ) def UpperCamelCase_ ( lowerCAmelCase__ : str , lowerCAmelCase__ : Tuple ) -> List[Any]: """simple docstring""" lowerCAmelCase_ : List[str] = column_based_sort(lowerCAmelCase__ , column=0 ) lowerCAmelCase_ : Dict = column_based_sort(lowerCAmelCase__ , column=1 ) return ( closest_pair_of_points_sqr( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) ) ** 0.5 if __name__ == "__main__": lowercase__ : List[str] = [(2, 3), (1_2, 3_0), (4_0, 5_0), (5, 1), (1_2, 1_0), (3, 4)] print("""Distance:""", closest_pair_of_points(points, len(points)))
289
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase__ : List[Any] = logging.get_logger(__name__) lowercase__ : List[str] = { """s-JoL/Open-Llama-V1""": """https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json""", } class UpperCamelCase__ ( lowercase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = """open-llama""" def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE_ : Tuple=1_0_0_0_0_0 , SCREAMING_SNAKE_CASE_ : Optional[int]=4_0_9_6 , SCREAMING_SNAKE_CASE_ : List[Any]=1_1_0_0_8 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=3_2 , SCREAMING_SNAKE_CASE_ : Optional[Any]=3_2 , SCREAMING_SNAKE_CASE_ : str="silu" , SCREAMING_SNAKE_CASE_ : Optional[Any]=2_0_4_8 , SCREAMING_SNAKE_CASE_ : Union[str, Any]=0.02 , SCREAMING_SNAKE_CASE_ : int=1E-6 , SCREAMING_SNAKE_CASE_ : List[str]=True , SCREAMING_SNAKE_CASE_ : Dict=0 , SCREAMING_SNAKE_CASE_ : Dict=1 , SCREAMING_SNAKE_CASE_ : Optional[Any]=2 , SCREAMING_SNAKE_CASE_ : str=False , SCREAMING_SNAKE_CASE_ : Optional[int]=True , SCREAMING_SNAKE_CASE_ : List[Any]=0.1 , SCREAMING_SNAKE_CASE_ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE_ : Dict=True , SCREAMING_SNAKE_CASE_ : Any=True , SCREAMING_SNAKE_CASE_ : Tuple=None , **SCREAMING_SNAKE_CASE_ : Optional[int] , ): lowerCAmelCase_ : Union[str, Any] = vocab_size lowerCAmelCase_ : int = max_position_embeddings lowerCAmelCase_ : Union[str, Any] = hidden_size lowerCAmelCase_ : Optional[Any] = intermediate_size lowerCAmelCase_ : List[Any] = num_hidden_layers lowerCAmelCase_ : Optional[int] = num_attention_heads lowerCAmelCase_ : List[Any] = hidden_act lowerCAmelCase_ : List[Any] = initializer_range lowerCAmelCase_ : List[str] = rms_norm_eps lowerCAmelCase_ : List[Any] = use_cache lowerCAmelCase_ : Optional[int] = kwargs.pop( 'use_memorry_efficient_attention' , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : List[Any] = hidden_dropout_prob lowerCAmelCase_ : List[str] = attention_dropout_prob lowerCAmelCase_ : Tuple = use_stable_embedding lowerCAmelCase_ : Optional[Any] = shared_input_output_embedding lowerCAmelCase_ : Optional[Any] = rope_scaling self._rope_scaling_validation() super().__init__( pad_token_id=SCREAMING_SNAKE_CASE_ , bos_token_id=SCREAMING_SNAKE_CASE_ , eos_token_id=SCREAMING_SNAKE_CASE_ , tie_word_embeddings=SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ , ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): if self.rope_scaling is None: return if not isinstance(self.rope_scaling , SCREAMING_SNAKE_CASE_ ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' F"got {self.rope_scaling}" ) lowerCAmelCase_ : int = self.rope_scaling.get('type' , SCREAMING_SNAKE_CASE_ ) lowerCAmelCase_ : Union[str, Any] = self.rope_scaling.get('factor' , SCREAMING_SNAKE_CASE_ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F"`rope_scaling`'s name field must be one of ['linear', 'dynamic'], got {rope_scaling_type}" ) if rope_scaling_factor is None or not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) or rope_scaling_factor <= 1.0: raise ValueError(F"`rope_scaling`'s factor field must be an float > 1, got {rope_scaling_factor}" )
289
1
'''simple docstring''' import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import SPIECE_UNDERLINE, logging a_ : str = logging.get_logger(__name__) a_ : int = {"""vocab_file""": """spiece.model"""} a_ : Dict = { """vocab_file""": { """TsinghuaAI/CPM-Generate""": """https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model""", } } class __UpperCamelCase ( lowerCamelCase__ ): def __init__( self, lowerCAmelCase, lowerCAmelCase=False, lowerCAmelCase=True, lowerCAmelCase=False, lowerCAmelCase="<s>", lowerCAmelCase="</s>", lowerCAmelCase="<unk>", lowerCAmelCase="<sep>", lowerCAmelCase="<pad>", lowerCAmelCase="<cls>", lowerCAmelCase="<mask>", lowerCAmelCase=["<eop>", "<eod>"], lowerCAmelCase = None, **lowerCAmelCase, ): """simple docstring""" lowerCamelCase_ =AddedToken(lowerCAmelCase, lstrip=lowerCAmelCase, rstrip=lowerCAmelCase ) if isinstance(lowerCAmelCase, lowerCAmelCase ) else mask_token lowerCamelCase_ ={} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=lowerCAmelCase, remove_space=lowerCAmelCase, keep_accents=lowerCAmelCase, bos_token=lowerCAmelCase, eos_token=lowerCAmelCase, unk_token=lowerCAmelCase, sep_token=lowerCAmelCase, pad_token=lowerCAmelCase, cls_token=lowerCAmelCase, mask_token=lowerCAmelCase, additional_special_tokens=lowerCAmelCase, sp_model_kwargs=self.sp_model_kwargs, **lowerCAmelCase, ) lowerCamelCase_ =3 lowerCamelCase_ =do_lower_case lowerCamelCase_ =remove_space lowerCamelCase_ =keep_accents lowerCamelCase_ =vocab_file lowerCamelCase_ =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(lowerCAmelCase ) try: import jieba except ModuleNotFoundError as error: raise error.__class__( '''You need to install jieba to use CpmTokenizer or CpmTokenizerFast. ''' '''See https://pypi.org/project/jieba/ for installation.''' ) lowerCamelCase_ =jieba lowerCamelCase_ =str.maketrans(''' \n''', '''\u2582\u2583''' ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def lowercase__ ( self ): """simple docstring""" return len(self.sp_model ) def lowercase__ ( self ): """simple docstring""" lowerCamelCase_ ={self.convert_ids_to_tokens(lowerCAmelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): """simple docstring""" lowerCamelCase_ =self.__dict__.copy() lowerCamelCase_ =None return state def __setstate__( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =d # for backward compatibility if not hasattr(self, '''sp_model_kwargs''' ): lowerCamelCase_ ={} lowerCamelCase_ =spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" if self.remove_space: lowerCamelCase_ =''' '''.join(inputs.strip().split() ) else: lowerCamelCase_ =inputs lowerCamelCase_ =outputs.replace('''``''', '''"''' ).replace('''\'\'''', '''"''' ) if not self.keep_accents: lowerCamelCase_ =unicodedata.normalize('''NFKD''', lowerCAmelCase ) lowerCamelCase_ =''''''.join([c for c in outputs if not unicodedata.combining(lowerCAmelCase )] ) if self.do_lower_case: lowerCamelCase_ =outputs.lower() return outputs def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =self.preprocess_text(lowerCAmelCase ) lowerCamelCase_ =self.sp_model.encode(lowerCAmelCase, out_type=lowerCAmelCase ) lowerCamelCase_ =[] for piece in pieces: if len(lowerCAmelCase ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): lowerCamelCase_ =self.sp_model.EncodeAsPieces(piece[:-1].replace(lowerCAmelCase, '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowerCamelCase_ =cur_pieces[1:] else: lowerCamelCase_ =cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(lowerCAmelCase ) else: new_pieces.append(lowerCAmelCase ) return new_pieces def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" return self.sp_model.PieceToId(lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" return self.sp_model.IdToPiece(lowerCAmelCase ) def lowercase__ ( self, lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =''''''.join(lowerCAmelCase ).replace(lowerCAmelCase, ''' ''' ).strip() return out_string def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase = None ): """simple docstring""" lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase = None, lowerCAmelCase = False ): """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCAmelCase, token_ids_a=lowerCAmelCase, already_has_special_tokens=lowerCAmelCase ) if token_ids_a is not None: return ([0] * len(lowerCAmelCase )) + [1] + ([0] * len(lowerCAmelCase )) + [1, 1] return ([0] * len(lowerCAmelCase )) + [1, 1] def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase = None ): """simple docstring""" lowerCamelCase_ =[self.sep_token_id] lowerCamelCase_ =[2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase = None ): """simple docstring""" if not os.path.isdir(lowerCAmelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCamelCase_ =os.path.join( lowerCAmelCase, (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(lowerCAmelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file, lowerCAmelCase ) elif not os.path.isfile(self.vocab_file ): with open(lowerCAmelCase, '''wb''' ) as fi: lowerCamelCase_ =self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase ) return (out_vocab_file,) def lowercase__ ( self, *lowerCAmelCase, **lowerCAmelCase ): """simple docstring""" lowerCamelCase_ =super()._decode(*lowerCAmelCase, **lowerCAmelCase ) lowerCamelCase_ =text.replace(''' ''', '''''' ).replace('''\u2582''', ''' ''' ).replace('''\u2583''', '''\n''' ) return text
75
'''simple docstring''' 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 a_ ( __snake_case : Any ) -> int: """simple docstring""" lowerCamelCase_ =checkpoints.load_tax_checkpoint(__snake_case ) lowerCamelCase_ =flatten_dict(__snake_case ) return flax_params def a_ ( __snake_case : Dict ) -> Optional[int]: """simple docstring""" lowerCamelCase_ ={} lowerCamelCase_ ={ '''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_ ={ '''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_ ='''.'''.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): lowerCamelCase_ =new_key.replace(__snake_case , __snake_case ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): lowerCamelCase_ =new_key.replace(__snake_case , __snake_case ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number lowerCamelCase_ =re.sub(r'''layers_(\d+)''' , r'''layer.\1''' , __snake_case ) lowerCamelCase_ =new_key.replace('''encoder''' , '''encoder.encoder''' ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number lowerCamelCase_ =re.sub(r'''layers_(\d+)''' , r'''layer.\1''' , __snake_case ) lowerCamelCase_ =flax_dict[key] lowerCamelCase_ ={} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): lowerCamelCase_ =torch.from_numpy(converted_dict[key].T ) else: lowerCamelCase_ =torch.from_numpy(converted_dict[key] ) return converted_torch_dict def a_ ( __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : Any=False , __snake_case : Optional[int]=False ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ =get_flax_param(__snake_case ) if not use_large: lowerCamelCase_ =PixaStructVisionConfig() lowerCamelCase_ =PixaStructTextConfig() else: lowerCamelCase_ =PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) lowerCamelCase_ =PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) lowerCamelCase_ =PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=__snake_case ) lowerCamelCase_ =PixaStructForConditionalGeneration(__snake_case ) lowerCamelCase_ =rename_and_convert_flax_params(__snake_case ) model.load_state_dict(__snake_case ) lowerCamelCase_ =AutoTokenizer.from_pretrained('''ybelkada/test-pix2struct-tokenizer''' ) lowerCamelCase_ =PixaStructImageProcessor() lowerCamelCase_ =PixaStructProcessor(image_processor=__snake_case , tokenizer=__snake_case ) if use_large: lowerCamelCase_ =4096 lowerCamelCase_ =True # mkdir if needed os.makedirs(__snake_case , exist_ok=__snake_case ) model.save_pretrained(__snake_case ) processor.save_pretrained(__snake_case ) print('''Model saved in {}'''.format(__snake_case ) ) if __name__ == "__main__": a_ : Optional[int] = 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.""") a_ : Tuple = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
75
1
"""simple docstring""" from __future__ import annotations def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Optional[Any], UpperCAmelCase__ : List[Any] ) ->List[str]: # noqa: E741 while r - l > 1: A__ : List[str] = (l + r) // 2 if v[m] >= key: A__ : Any = m else: A__ : List[str] = m # noqa: E741 return r def _lowerCAmelCase ( UpperCAmelCase__ : list[int] ) ->int: if len(UpperCAmelCase__ ) == 0: return 0 A__ : Optional[Any] = [0] * len(UpperCAmelCase__ ) A__ : Tuple = 1 A__ : int = v[0] for i in range(1, len(UpperCAmelCase__ ) ): if v[i] < tail[0]: A__ : List[Any] = v[i] elif v[i] > tail[length - 1]: A__ : Dict = v[i] length += 1 else: A__ : Optional[int] = v[i] return length if __name__ == "__main__": import doctest doctest.testmod()
296
"""simple docstring""" import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py A_ = '''src/diffusers''' A_ = '''.''' # This is to make sure the diffusers module imported is the one in the repo. A_ = importlib.util.spec_from_file_location( '''diffusers''', os.path.join(DIFFUSERS_PATH, '''__init__.py'''), submodule_search_locations=[DIFFUSERS_PATH], ) A_ = spec.loader.load_module() def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Optional[Any] ) ->Any: return line.startswith(UpperCAmelCase__ ) or len(UpperCAmelCase__ ) <= 1 or re.search(R"""^\s*\)(\s*->.*:|:)\s*$""", UpperCAmelCase__ ) is not None def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Union[str, Any]: A__ : Any = object_name.split(""".""" ) A__ : int = 0 # First let's find the module where our object lives. A__ : str = parts[i] while i < len(UpperCAmelCase__ ) and not os.path.isfile(os.path.join(UpperCAmelCase__, f'{module}.py' ) ): i += 1 if i < len(UpperCAmelCase__ ): A__ : Union[str, Any] = os.path.join(UpperCAmelCase__, parts[i] ) if i >= len(UpperCAmelCase__ ): raise ValueError(f'`object_name` should begin with the name of a module of diffusers but got {object_name}.' ) with open(os.path.join(UpperCAmelCase__, f'{module}.py' ), """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : List[Any] = f.readlines() # Now let's find the class / func in the code! A__ : Optional[Any] = """""" A__ : Any = 0 for name in parts[i + 1 :]: while ( line_index < len(UpperCAmelCase__ ) and re.search(Rf'^{indent}(class|def)\s+{name}(\(|\:)', lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(UpperCAmelCase__ ): raise ValueError(f' {object_name} does not match any function or class in {module}.' ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). A__ : List[Any] = line_index while line_index < len(UpperCAmelCase__ ) and _should_continue(lines[line_index], UpperCAmelCase__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : List[Any] = lines[start_index:line_index] return "".join(UpperCAmelCase__ ) A_ = re.compile(r'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''') A_ = re.compile(r'''^\s*(\S+)->(\S+)(\s+.*|$)''') A_ = re.compile(r'''<FILL\s+[^>]*>''') def _lowerCAmelCase ( UpperCAmelCase__ : List[str] ) ->Optional[Any]: A__ : Dict = code.split("""\n""" ) A__ : List[Any] = 0 while idx < len(UpperCAmelCase__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(UpperCAmelCase__ ): return re.search(R"""^(\s*)\S""", lines[idx] ).groups()[0] return "" def _lowerCAmelCase ( UpperCAmelCase__ : Optional[Any] ) ->int: A__ : str = len(get_indent(UpperCAmelCase__ ) ) > 0 if has_indent: A__ : Union[str, Any] = f'class Bla:\n{code}' A__ : Optional[Any] = black.Mode(target_versions={black.TargetVersion.PYaa}, line_length=1_1_9, preview=UpperCAmelCase__ ) A__ : Tuple = black.format_str(UpperCAmelCase__, mode=UpperCAmelCase__ ) A__ , A__ : List[Any] = style_docstrings_in_code(UpperCAmelCase__ ) return result[len("""class Bla:\n""" ) :] if has_indent else result def _lowerCAmelCase ( UpperCAmelCase__ : Any, UpperCAmelCase__ : Dict=False ) ->List[Any]: with open(UpperCAmelCase__, """r""", encoding="""utf-8""", newline="""\n""" ) as f: A__ : int = f.readlines() A__ : Dict = [] A__ : List[str] = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(UpperCAmelCase__ ): A__ : Dict = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. A__ , A__ , A__ : Dict = search.groups() A__ : Tuple = find_code_in_diffusers(UpperCAmelCase__ ) A__ : int = get_indent(UpperCAmelCase__ ) A__ : List[str] = line_index + 1 if indent == theoretical_indent else line_index + 2 A__ : Tuple = theoretical_indent A__ : Optional[Any] = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. A__ : Tuple = True while line_index < len(UpperCAmelCase__ ) and should_continue: line_index += 1 if line_index >= len(UpperCAmelCase__ ): break A__ : Optional[int] = lines[line_index] A__ : Tuple = _should_continue(UpperCAmelCase__, UpperCAmelCase__ ) and re.search(f'^{indent}# End copy', UpperCAmelCase__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 A__ : Dict = lines[start_index:line_index] A__ : Tuple = """""".join(UpperCAmelCase__ ) # Remove any nested `Copied from` comments to avoid circular copies A__ : Optional[int] = [line for line in theoretical_code.split("""\n""" ) if _re_copy_warning.search(UpperCAmelCase__ ) is None] A__ : Optional[Any] = """\n""".join(UpperCAmelCase__ ) # Before comparing, use the `replace_pattern` on the original code. if len(UpperCAmelCase__ ) > 0: A__ : int = replace_pattern.replace("""with""", """""" ).split(""",""" ) A__ : List[Any] = [_re_replace_pattern.search(UpperCAmelCase__ ) for p in patterns] for pattern in patterns: if pattern is None: continue A__ , A__ , A__ : Union[str, Any] = pattern.groups() A__ : Union[str, Any] = re.sub(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) if option.strip() == "all-casing": A__ : List[Any] = re.sub(obja.lower(), obja.lower(), UpperCAmelCase__ ) A__ : Tuple = re.sub(obja.upper(), obja.upper(), UpperCAmelCase__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line A__ : Optional[int] = blackify(lines[start_index - 1] + theoretical_code ) A__ : List[Any] = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: A__ : List[Any] = lines[:start_index] + [theoretical_code] + lines[line_index:] A__ : Tuple = start_index + 1 if overwrite and len(UpperCAmelCase__ ) > 0: # Warn the user a file has been modified. print(f'Detected changes, rewriting {filename}.' ) with open(UpperCAmelCase__, """w""", encoding="""utf-8""", newline="""\n""" ) as f: f.writelines(UpperCAmelCase__ ) return diffs def _lowerCAmelCase ( UpperCAmelCase__ : bool = False ) ->Any: A__ : Dict = glob.glob(os.path.join(UpperCAmelCase__, """**/*.py""" ), recursive=UpperCAmelCase__ ) A__ : str = [] for filename in all_files: A__ : Any = is_copy_consistent(UpperCAmelCase__, UpperCAmelCase__ ) diffs += [f'- {filename}: copy does not match {d[0]} at line {d[1]}' for d in new_diffs] if not overwrite and len(UpperCAmelCase__ ) > 0: A__ : Any = """\n""".join(UpperCAmelCase__ ) raise Exception( """Found the following copy inconsistencies:\n""" + diff + """\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') A_ = parser.parse_args() check_copies(args.fix_and_overwrite)
296
1
"""simple docstring""" import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() __A = logging.get_logger() @dataclass class _lowerCAmelCase : """simple docstring""" __magic_name__ :nn.Module __magic_name__ :List[nn.Module] = field(default_factory=lowerCamelCase__ ) __magic_name__ :list = field(default_factory=lowerCamelCase__ ) def snake_case ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :str = len(list(m.modules() ) ) == 1 or isinstance(lowerCAmelCase__ , nn.Convad ) or isinstance(lowerCAmelCase__ , nn.BatchNormad ) if has_not_submodules: self.traced.append(lowerCAmelCase__ ) def __call__( self , __UpperCAmelCase ): '''simple docstring''' for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(lowerCAmelCase__ ) [x.remove() for x in self.handles] return self @property def snake_case ( self ): '''simple docstring''' return list(filter(lambda __UpperCAmelCase : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class _lowerCAmelCase : """simple docstring""" __magic_name__ :nn.Module __magic_name__ :nn.Module __magic_name__ :int = 1 __magic_name__ :List = field(default_factory=lowerCamelCase__ ) __magic_name__ :List = field(default_factory=lowerCamelCase__ ) __magic_name__ :bool = True def __call__( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Any = Tracker(self.dest )(lowerCAmelCase__ ).parametrized lowerCAmelCase__ :Dict = Tracker(self.src )(lowerCAmelCase__ ).parametrized lowerCAmelCase__ :Any = list(filter(lambda __UpperCAmelCase : type(lowerCAmelCase__ ) not in self.src_skip , lowerCAmelCase__ ) ) lowerCAmelCase__ :Tuple = list(filter(lambda __UpperCAmelCase : type(lowerCAmelCase__ ) not in self.dest_skip , lowerCAmelCase__ ) ) if len(lowerCAmelCase__ ) != len(lowerCAmelCase__ ) and self.raise_if_mismatch: raise Exception( F"Numbers of operations are different. Source module has {len(lowerCAmelCase__ )} operations while" F" destination module has {len(lowerCAmelCase__ )}." ) for dest_m, src_m in zip(lowerCAmelCase__ , lowerCAmelCase__ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F"Transfered from={src_m} to={dest_m}" ) class _lowerCAmelCase ( nn.Module ): """simple docstring""" def __init__( self , __UpperCAmelCase ): '''simple docstring''' super().__init__() lowerCAmelCase__ :List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F"Unexpected layer name {k}" lowerCAmelCase__ :Any = len(lowerCAmelCase__ ) + 1 feature_blocks.append((F"res{block_index}", v) ) lowerCAmelCase__ :Optional[Any] = nn.ModuleDict(lowerCAmelCase__ ) def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' return get_trunk_forward_outputs( lowerCAmelCase__ , out_feat_keys=lowerCAmelCase__ , feature_blocks=self._feature_blocks , ) class _lowerCAmelCase ( lowerCamelCase__ ): """simple docstring""" def snake_case ( self , __UpperCAmelCase ): '''simple docstring''' lowerCAmelCase__ :Union[str, Any] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' if x not in self: lowerCAmelCase__ :Tuple = self.convert_name_to_timm(lowerCAmelCase__ ) lowerCAmelCase__ :int = partial(lambda: (timm.create_model(lowerCAmelCase__ , pretrained=lowerCAmelCase__ ).eval(), None) ) else: lowerCAmelCase__ :Dict = super().__getitem__(lowerCAmelCase__ ) return val class _lowerCAmelCase ( lowerCamelCase__ ): """simple docstring""" def __getitem__( self , __UpperCAmelCase ): '''simple docstring''' if "seer" in x and "in1k" not in x: lowerCAmelCase__ :Optional[int] = RegNetModel else: lowerCAmelCase__ :int = RegNetForImageClassification return val def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ->Optional[Any]: """simple docstring""" for from_key, to_key in keys: lowerCAmelCase__ :Any = from_state_dict[from_key].clone() print(F"Copied key={from_key} to={to_key}" ) return to_state_dict def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = True , ) ->List[str]: """simple docstring""" print(F"Converting {name}..." ) with torch.no_grad(): lowerCAmelCase__ :int = from_model_func() lowerCAmelCase__ :int = our_model_func(_lowerCamelCase ).eval() lowerCAmelCase__ :Optional[int] = ModuleTransfer(src=_lowerCamelCase , dest=_lowerCamelCase , raise_if_mismatch=_lowerCamelCase ) lowerCAmelCase__ :str = torch.randn((1, 3, 224, 224) ) module_transfer(_lowerCamelCase ) if from_state_dict is not None: lowerCAmelCase__ :str = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: lowerCAmelCase__ :List[str] = [("""0.clf.0.weight""", """classifier.1.weight"""), ("""0.clf.0.bias""", """classifier.1.bias""")] lowerCAmelCase__ :List[str] = manually_copy_vissl_head(_lowerCamelCase , our_model.state_dict() , _lowerCamelCase ) our_model.load_state_dict(_lowerCamelCase ) lowerCAmelCase__ :str = our_model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) lowerCAmelCase__ :str = ( our_outputs.logits if isinstance(_lowerCamelCase , _lowerCamelCase ) else our_outputs.last_hidden_state ) lowerCAmelCase__ :str = from_model(_lowerCamelCase ) lowerCAmelCase__ :List[str] = from_output[-1] if type(_lowerCamelCase ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: lowerCAmelCase__ :Dict = our_outputs.hidden_states[-1] assert torch.allclose(_lowerCamelCase , _lowerCamelCase ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=_lowerCamelCase , ) lowerCAmelCase__ :List[Any] = 224 if """seer""" not in name else 384 # we can use the convnext one lowerCAmelCase__ :Any = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=_lowerCamelCase ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=_lowerCamelCase , ) print(F"Pushed {name}" ) def __A (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = True ) ->List[str]: """simple docstring""" lowerCAmelCase__ :List[str] = """imagenet-1k-id2label.json""" lowerCAmelCase__ :Optional[int] = 1000 lowerCAmelCase__ :str = (1, num_labels) lowerCAmelCase__ :Tuple = """huggingface/label-files""" lowerCAmelCase__ :Union[str, Any] = num_labels lowerCAmelCase__ :Tuple = json.load(open(cached_download(hf_hub_url(_lowerCamelCase , _lowerCamelCase , repo_type='dataset' ) ) , 'r' ) ) lowerCAmelCase__ :List[Any] = {int(_lowerCamelCase ): v for k, v in idalabel.items()} lowerCAmelCase__ :Dict = idalabel lowerCAmelCase__ :Union[str, Any] = {v: k for k, v in idalabel.items()} lowerCAmelCase__ :Optional[int] = partial(_lowerCamelCase , num_labels=_lowerCamelCase , idalabel=_lowerCamelCase , labelaid=_lowerCamelCase ) lowerCAmelCase__ :int = { """regnet-x-002""": ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 , layer_type='x' ), """regnet-x-004""": ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 160, 384] , groups_width=16 , layer_type='x' ), """regnet-x-006""": ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 240, 528] , groups_width=24 , layer_type='x' ), """regnet-x-008""": ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 128, 288, 672] , groups_width=16 , layer_type='x' ), """regnet-x-016""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 168, 408, 912] , groups_width=24 , layer_type='x' ), """regnet-x-032""": ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 192, 432, 1008] , groups_width=48 , layer_type='x' ), """regnet-x-040""": ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 240, 560, 1360] , groups_width=40 , layer_type='x' ), """regnet-x-064""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 392, 784, 1624] , groups_width=56 , layer_type='x' ), """regnet-x-080""": ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 240, 720, 1920] , groups_width=120 , layer_type='x' ), """regnet-x-120""": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 , layer_type='x' ), """regnet-x-160""": ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[256, 512, 896, 2048] , groups_width=128 , layer_type='x' ), """regnet-x-320""": ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[336, 672, 1344, 2520] , groups_width=168 , layer_type='x' ), # y variant """regnet-y-002""": ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 152, 368] , groups_width=8 ), """regnet-y-004""": ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 104, 208, 440] , groups_width=8 ), """regnet-y-006""": ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 112, 256, 608] , groups_width=16 ), """regnet-y-008""": ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 128, 320, 768] , groups_width=16 ), """regnet-y-016""": ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 120, 336, 888] , groups_width=24 ), """regnet-y-032""": ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 216, 576, 1512] , groups_width=24 ), """regnet-y-040""": ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[128, 192, 512, 1088] , groups_width=64 ), """regnet-y-064""": ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[144, 288, 576, 1296] , groups_width=72 ), """regnet-y-080""": ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[168, 448, 896, 2016] , groups_width=56 ), """regnet-y-120""": ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[224, 448, 896, 2240] , groups_width=112 ), """regnet-y-160""": ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[224, 448, 1232, 3024] , groups_width=112 ), """regnet-y-320""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 """regnet-y-320-seer""": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), """regnet-y-640-seer""": RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), """regnet-y-1280-seer""": RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), """regnet-y-2560-seer""": RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), """regnet-y-10b-seer""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ), # finetuned on imagenet """regnet-y-320-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[232, 696, 1392, 3712] , groups_width=232 ), """regnet-y-640-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[328, 984, 1968, 4920] , groups_width=328 ), """regnet-y-1280-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[528, 1056, 2904, 7392] , groups_width=264 ), """regnet-y-2560-seer-in1k""": ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[640, 1696, 2544, 5088] , groups_width=640 ), """regnet-y-10b-seer-in1k""": ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[2020, 4040, 1_1110, 2_8280] , groups_width=1010 ), } lowerCAmelCase__ :List[Any] = NameToOurModelFuncMap() lowerCAmelCase__ :str = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Tuple[nn.Module, Dict]: lowerCAmelCase__ :int = torch.hub.load_state_dict_from_url(_lowerCamelCase , model_dir=str(_lowerCamelCase ) , map_location='cpu' ) lowerCAmelCase__ :List[str] = model_func() # check if we have a head, if yes add it lowerCAmelCase__ :List[Any] = files["""classy_state_dict"""]["""base_model"""]["""model"""] lowerCAmelCase__ :List[Any] = model_state_dict["""trunk"""] model.load_state_dict(_lowerCamelCase ) return model.eval(), model_state_dict["heads"] # pretrained lowerCAmelCase__ :Any = partial( _lowerCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ :str = partial( _lowerCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ :Optional[int] = partial( _lowerCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) lowerCAmelCase__ :int = partial( _lowerCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.5_2 ) ) ) , ) # IN1K finetuned lowerCAmelCase__ :List[Any] = partial( _lowerCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ :int = partial( _lowerCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) lowerCAmelCase__ :str = partial( _lowerCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) lowerCAmelCase__ :Optional[int] = partial( _lowerCamelCase , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=1010 , w_a=1744 , w_a=620.83 , w_m=2.5_2 ) ) ) , ) if model_name: convert_weight_and_push( _lowerCamelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , _lowerCamelCase , _lowerCamelCase , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( _lowerCamelCase , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , ) return config, expected_shape if __name__ == "__main__": __A = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default=None, type=str, help=( """The name of the model you wish to convert, it must be one of the supported regnet* architecture,""" """ currently: regnetx-*, regnety-*. If `None`, all of them will the converted.""" ), ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=Path, required=True, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", default=True, type=bool, required=False, help="""If True, push model and image processor to the hub.""", ) __A = parser.parse_args() __A = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
293
'''simple docstring''' import string def lowerCAmelCase_ ( _lowerCamelCase: str ): __SCREAMING_SNAKE_CASE : Dict = """""" for i in sequence: __SCREAMING_SNAKE_CASE : Any = ord(_lowerCamelCase ) if 65 <= extract <= 90: output += chr(1_55 - extract ) elif 97 <= extract <= 1_22: output += chr(2_19 - extract ) else: output += i return output def lowerCAmelCase_ ( _lowerCamelCase: str ): __SCREAMING_SNAKE_CASE : Optional[Any] = string.ascii_letters __SCREAMING_SNAKE_CASE : Union[str, Any] = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(_lowerCamelCase )] if c in letters else c for c in sequence ) def lowerCAmelCase_ ( ): from timeit import timeit print("""Running performance benchmarks...""" ) __SCREAMING_SNAKE_CASE : Union[str, Any] = """from string import printable ; from __main__ import atbash, atbash_slow""" print(F"> atbash_slow(): {timeit('atbash_slow(printable)' , setup=_lowerCamelCase )} seconds" ) print(F"> atbash(): {timeit('atbash(printable)' , setup=_lowerCamelCase )} seconds" ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(f"{example} encrypted in atbash: {atbash(example)}") benchmark()
112
0
"""simple docstring""" import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 A_ = 0b101_100_111_110_110_010_010_000_011_110_111_011_000_110_011_110 # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1 A_ = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class __SCREAMING_SNAKE_CASE : def __init__( self : List[str] ): '''simple docstring''' A__ : List[Any] = WATERMARK_BITS A__ : int = WatermarkEncoder() self.encoder.set_watermark("""bits""" , self.watermark ) def _UpperCamelCase ( self : str , snake_case : torch.FloatTensor ): '''simple docstring''' if images.shape[-1] < 256: return images A__ : Tuple = (255 * (images / 2 + 0.5)).cpu().permute(0 , 2 , 3 , 1 ).float().numpy() A__ : Any = [self.encoder.encode(_a , """dwtDct""" ) for image in images] A__ : Optional[Any] = torch.from_numpy(np.array(_a ) ).permute(0 , 3 , 1 , 2 ) A__ : str = torch.clamp(2 * (images / 255 - 0.5) , min=-1.0 , max=1.0 ) return images
355
"""simple docstring""" from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING A_ = logging.get_logger(__name__) A_ = Dict[str, Any] A_ = List[Prediction] @add_end_docstrings(UpperCamelCase ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): def __init__( self : str , *snake_case : Tuple , **snake_case : Tuple ): '''simple docstring''' super().__init__(*snake_case , **snake_case ) if self.framework == "tf": raise ValueError(F'The {self.__class__} is only available in PyTorch.' ) requires_backends(self , """vision""" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def _UpperCamelCase ( self : List[Any] , **snake_case : Optional[int] ): '''simple docstring''' A__ : Dict = {} if "threshold" in kwargs: A__ : int = kwargs["""threshold"""] return {}, {}, postprocess_kwargs def __call__( self : Tuple , *snake_case : Union[str, Any] , **snake_case : Union[str, Any] ): '''simple docstring''' return super().__call__(*snake_case , **snake_case ) def _UpperCamelCase ( self : str , snake_case : int ): '''simple docstring''' A__ : List[str] = load_image(snake_case ) A__ : int = torch.IntTensor([[image.height, image.width]] ) A__ : Union[str, Any] = self.image_processor(images=[image] , return_tensors="""pt""" ) if self.tokenizer is not None: A__ : str = self.tokenizer(text=inputs["""words"""] , boxes=inputs["""boxes"""] , return_tensors="""pt""" ) A__ : List[str] = target_size return inputs def _UpperCamelCase ( self : Optional[int] , snake_case : List[Any] ): '''simple docstring''' A__ : str = model_inputs.pop("""target_size""" ) A__ : Dict = self.model(**snake_case ) A__ : Optional[Any] = outputs.__class__({"""target_size""": target_size, **outputs} ) if self.tokenizer is not None: A__ : str = model_inputs["""bbox"""] return model_outputs def _UpperCamelCase ( self : Tuple , snake_case : Optional[int] , snake_case : int=0.9 ): '''simple docstring''' A__ : Any = model_outputs["""target_size"""] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. A__ , A__ : Tuple = target_size[0].tolist() def unnormalize(snake_case : Optional[int] ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) A__ , A__ : Optional[int] = model_outputs["""logits"""].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) A__ : Optional[Any] = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] A__ : List[str] = [unnormalize(snake_case ) for bbox in model_outputs["""bbox"""].squeeze(0 )] A__ : Tuple = ["""score""", """label""", """box"""] A__ : Any = [dict(zip(snake_case , snake_case ) ) for vals in zip(scores.tolist() , snake_case , snake_case ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel A__ : Union[str, Any] = self.image_processor.post_process_object_detection(snake_case , snake_case , snake_case ) A__ : str = raw_annotations[0] A__ : str = raw_annotation["""scores"""] A__ : List[Any] = raw_annotation["""labels"""] A__ : int = raw_annotation["""boxes"""] A__ : str = scores.tolist() A__ : Any = [self.model.config.idalabel[label.item()] for label in labels] A__ : int = [self._get_bounding_box(snake_case ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] A__ : str = ["""score""", """label""", """box"""] A__ : Dict = [ dict(zip(snake_case , snake_case ) ) for vals in zip(raw_annotation["""scores"""] , raw_annotation["""labels"""] , raw_annotation["""boxes"""] ) ] return annotation def _UpperCamelCase ( self : Union[str, Any] , snake_case : "torch.Tensor" ): '''simple docstring''' if self.framework != "pt": raise ValueError("""The ObjectDetectionPipeline is only available in PyTorch.""" ) A__ , A__ , A__ , A__ : Any = box.int().tolist() A__ : Any = { """xmin""": xmin, """ymin""": ymin, """xmax""": xmax, """ymax""": ymax, } return bbox
296
0
"""simple docstring""" from math import asin, atan, cos, radians, sin, sqrt, tan _a : Any = 6_37_81_37.0 _a : List[str] = 6_35_67_52.31_42_45 _a : Tuple = 6_378_137 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : float ,_lowerCamelCase : float ,_lowerCamelCase : float ,_lowerCamelCase : float ) -> float: _lowerCAmelCase : Any = (AXIS_A - AXIS_B) / AXIS_A _lowerCAmelCase : List[str] = atan((1 - flattening) * tan(radians(_lowerCamelCase ) ) ) _lowerCAmelCase : Dict = atan((1 - flattening) * tan(radians(_lowerCamelCase ) ) ) _lowerCAmelCase : Optional[Any] = radians(_lowerCamelCase ) _lowerCAmelCase : int = radians(_lowerCamelCase ) # Equation _lowerCAmelCase : Dict = sin((phi_a - phi_a) / 2 ) _lowerCAmelCase : Tuple = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda _lowerCAmelCase : int = sqrt(sin_sq_phi + (cos(_lowerCamelCase ) * cos(_lowerCamelCase ) * sin_sq_lambda) ) return 2 * RADIUS * asin(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
44
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __SCREAMING_SNAKE_CASE = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __SCREAMING_SNAKE_CASE = 1 if upper_limit > 0: __SCREAMING_SNAKE_CASE = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(lowerCAmelCase_ ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''') print('''\n*** Enter -1 at any time to quit ***''') print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''') try: while True: a__ : List[str] = int(input().strip()) if N < 0: print('''\n********* Goodbye!! ************''') break else: print(F"The Catalan numbers from 0 through {N} are:") print(catalan_numbers(N)) print('''Try another upper limit for the sequence: ''', end='''''') except (NameError, ValueError): print('''\n********* Invalid input, goodbye! ************\n''') import doctest doctest.testmod()
54
0
"""simple docstring""" import argparse import os import shutil from pathlib import Path import onnx import torch from packaging import version from torch.onnx import export from diffusers import OnnxRuntimeModel, OnnxStableDiffusionPipeline, StableDiffusionPipeline A_ = version.parse(version.parse(torch.__version__).base_version) < version.parse('''1.11''') def UpperCAmelCase__ (snake_case__ : Tuple , snake_case__ : tuple , snake_case__ : Path , snake_case__ : Tuple , snake_case__ : List[str] , snake_case__ : int , snake_case__ : Union[str, Any] , snake_case__ : Dict=False , ): """simple docstring""" output_path.parent.mkdir(parents=snake_case__ , exist_ok=snake_case__ ) # PyTorch deprecated the `enable_onnx_checker` and `use_external_data_format` arguments in v1.11, # so we check the torch version for backwards compatibility if is_torch_less_than_1_11: export( snake_case__ , snake_case__ , f=output_path.as_posix() , input_names=snake_case__ , output_names=snake_case__ , dynamic_axes=snake_case__ , do_constant_folding=snake_case__ , use_external_data_format=snake_case__ , enable_onnx_checker=snake_case__ , opset_version=snake_case__ , ) else: export( snake_case__ , snake_case__ , f=output_path.as_posix() , input_names=snake_case__ , output_names=snake_case__ , dynamic_axes=snake_case__ , do_constant_folding=snake_case__ , opset_version=snake_case__ , ) @torch.no_grad() def UpperCAmelCase__ (snake_case__ : str , snake_case__ : str , snake_case__ : int , snake_case__ : bool = False ): """simple docstring""" _snake_case : str = torch.floataa if fpaa else torch.floataa if fpaa and torch.cuda.is_available(): _snake_case : List[Any] = """cuda""" elif fpaa and not torch.cuda.is_available(): raise ValueError("""`float16` model export is only supported on GPUs with CUDA""" ) else: _snake_case : Optional[int] = """cpu""" _snake_case : Dict = StableDiffusionPipeline.from_pretrained(snake_case__ , torch_dtype=snake_case__ ).to(snake_case__ ) _snake_case : List[Any] = Path(snake_case__ ) # TEXT ENCODER _snake_case : Dict = pipeline.text_encoder.config.max_position_embeddings _snake_case : List[Any] = pipeline.text_encoder.config.hidden_size _snake_case : List[Any] = pipeline.tokenizer( """A sample prompt""" , padding="""max_length""" , max_length=pipeline.tokenizer.model_max_length , truncation=snake_case__ , return_tensors="""pt""" , ) onnx_export( pipeline.text_encoder , model_args=(text_input.input_ids.to(device=snake_case__ , dtype=torch.intaa )) , output_path=output_path / """text_encoder""" / """model.onnx""" , ordered_input_names=["""input_ids"""] , output_names=["""last_hidden_state""", """pooler_output"""] , dynamic_axes={ """input_ids""": {0: """batch""", 1: """sequence"""}, } , opset=snake_case__ , ) del pipeline.text_encoder # UNET _snake_case : str = pipeline.unet.config.in_channels _snake_case : List[str] = pipeline.unet.config.sample_size _snake_case : str = output_path / """unet""" / """model.onnx""" onnx_export( pipeline.unet , model_args=( torch.randn(2 , snake_case__ , snake_case__ , snake_case__ ).to(device=snake_case__ , dtype=snake_case__ ), torch.randn(2 ).to(device=snake_case__ , dtype=snake_case__ ), torch.randn(2 , snake_case__ , snake_case__ ).to(device=snake_case__ , dtype=snake_case__ ), False, ) , output_path=snake_case__ , ordered_input_names=["""sample""", """timestep""", """encoder_hidden_states""", """return_dict"""] , output_names=["""out_sample"""] , dynamic_axes={ """sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""}, """timestep""": {0: """batch"""}, """encoder_hidden_states""": {0: """batch""", 1: """sequence"""}, } , opset=snake_case__ , use_external_data_format=snake_case__ , ) _snake_case : str = str(unet_path.absolute().as_posix() ) _snake_case : Optional[int] = os.path.dirname(snake_case__ ) _snake_case : Tuple = onnx.load(snake_case__ ) # clean up existing tensor files shutil.rmtree(snake_case__ ) os.mkdir(snake_case__ ) # collate external tensor files into one onnx.save_model( snake_case__ , snake_case__ , save_as_external_data=snake_case__ , all_tensors_to_one_file=snake_case__ , location="""weights.pb""" , convert_attribute=snake_case__ , ) del pipeline.unet # VAE ENCODER _snake_case : Optional[Any] = pipeline.vae _snake_case : Optional[int] = vae_encoder.config.in_channels _snake_case : List[Any] = vae_encoder.config.sample_size # need to get the raw tensor output (sample) from the encoder _snake_case : Union[str, Any] = lambda snake_case__ , snake_case__ : vae_encoder.encode(snake_case__ , snake_case__ )[0].sample() onnx_export( snake_case__ , model_args=( torch.randn(1 , snake_case__ , snake_case__ , snake_case__ ).to(device=snake_case__ , dtype=snake_case__ ), False, ) , output_path=output_path / """vae_encoder""" / """model.onnx""" , ordered_input_names=["""sample""", """return_dict"""] , output_names=["""latent_sample"""] , dynamic_axes={ """sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""}, } , opset=snake_case__ , ) # VAE DECODER _snake_case : List[str] = pipeline.vae _snake_case : str = vae_decoder.config.latent_channels _snake_case : Any = vae_decoder.config.out_channels # forward only through the decoder part _snake_case : List[str] = vae_encoder.decode onnx_export( snake_case__ , model_args=( torch.randn(1 , snake_case__ , snake_case__ , snake_case__ ).to(device=snake_case__ , dtype=snake_case__ ), False, ) , output_path=output_path / """vae_decoder""" / """model.onnx""" , ordered_input_names=["""latent_sample""", """return_dict"""] , output_names=["""sample"""] , dynamic_axes={ """latent_sample""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""}, } , opset=snake_case__ , ) del pipeline.vae # SAFETY CHECKER if pipeline.safety_checker is not None: _snake_case : Optional[Any] = pipeline.safety_checker _snake_case : Tuple = safety_checker.config.vision_config.num_channels _snake_case : int = safety_checker.config.vision_config.image_size _snake_case : int = safety_checker.forward_onnx onnx_export( pipeline.safety_checker , model_args=( torch.randn( 1 , snake_case__ , snake_case__ , snake_case__ , ).to(device=snake_case__ , dtype=snake_case__ ), torch.randn(1 , snake_case__ , snake_case__ , snake_case__ ).to(device=snake_case__ , dtype=snake_case__ ), ) , output_path=output_path / """safety_checker""" / """model.onnx""" , ordered_input_names=["""clip_input""", """images"""] , output_names=["""out_images""", """has_nsfw_concepts"""] , dynamic_axes={ """clip_input""": {0: """batch""", 1: """channels""", 2: """height""", 3: """width"""}, """images""": {0: """batch""", 1: """height""", 2: """width""", 3: """channels"""}, } , opset=snake_case__ , ) del pipeline.safety_checker _snake_case : str = OnnxRuntimeModel.from_pretrained(output_path / """safety_checker""" ) _snake_case : Optional[int] = pipeline.feature_extractor else: _snake_case : Any = None _snake_case : Optional[Any] = None _snake_case : Dict = OnnxStableDiffusionPipeline( vae_encoder=OnnxRuntimeModel.from_pretrained(output_path / """vae_encoder""" ) , vae_decoder=OnnxRuntimeModel.from_pretrained(output_path / """vae_decoder""" ) , text_encoder=OnnxRuntimeModel.from_pretrained(output_path / """text_encoder""" ) , tokenizer=pipeline.tokenizer , unet=OnnxRuntimeModel.from_pretrained(output_path / """unet""" ) , scheduler=pipeline.scheduler , safety_checker=snake_case__ , feature_extractor=snake_case__ , requires_safety_checker=safety_checker is not None , ) onnx_pipeline.save_pretrained(snake_case__ ) print("""ONNX pipeline saved to""" , snake_case__ ) del pipeline del onnx_pipeline _snake_case : int = OnnxStableDiffusionPipeline.from_pretrained(snake_case__ , provider="""CPUExecutionProvider""" ) print("""ONNX pipeline is loadable""" ) if __name__ == "__main__": A_ = argparse.ArgumentParser() parser.add_argument( '''--model_path''', type=str, required=True, help='''Path to the `diffusers` checkpoint to convert (either a local directory or on the Hub).''', ) parser.add_argument('''--output_path''', type=str, required=True, help='''Path to the output model.''') parser.add_argument( '''--opset''', default=14, type=int, help='''The version of the ONNX operator set to use.''', ) parser.add_argument('''--fp16''', action='''store_true''', default=False, help='''Export the models in `float16` mode''') A_ = parser.parse_args() convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
360
"""simple docstring""" def UpperCAmelCase__ (snake_case__ : int = 1_00_00_00 ): """simple docstring""" _snake_case : Dict = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , snake_case__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
132
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor lowerCamelCase : Optional[Any] = logging.get_logger(__name__) class A__ ( A__ ): def __init__( self : str , *_a : Optional[int] , **_a : Dict ) -> None: '''simple docstring''' warnings.warn( 'The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use FlavaImageProcessor instead.' , _a , ) super().__init__(*_a , **_a )
47
'''simple docstring''' import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" _SCREAMING_SNAKE_CASE = 42 _SCREAMING_SNAKE_CASE = None def __lowerCamelCase ( A__ , A__=0.999 , A__="cosine" , ) -> Tuple: """simple docstring""" if alpha_transform_type == "cosine": def alpha_bar_fn(A__ ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(A__ ): return math.exp(t * -12.0 ) else: raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) UpperCamelCase = [] for i in range(A__ ): UpperCamelCase = i / num_diffusion_timesteps UpperCamelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(A__ ) / alpha_bar_fn(A__ ) , A__ ) ) return torch.tensor(A__ , dtype=torch.floataa ) class SCREAMING_SNAKE_CASE ( _a , _a ): """simple docstring""" @register_to_config def __init__( self : List[str] , UpperCamelCase__ : int = 1_0_0_0 , UpperCamelCase__ : str = "fixed_small_log" , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[float] = 1.0 , UpperCamelCase__ : str = "epsilon" , UpperCamelCase__ : str = "squaredcos_cap_v2" , ): """simple docstring""" if beta_schedule != "squaredcos_cap_v2": raise ValueError('UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'' ) UpperCamelCase = betas_for_alpha_bar(UpperCamelCase__ ) UpperCamelCase = 1.0 - self.betas UpperCamelCase = torch.cumprod(self.alphas , dim=0 ) UpperCamelCase = torch.tensor(1.0 ) # standard deviation of the initial noise distribution UpperCamelCase = 1.0 # setable values UpperCamelCase = None UpperCamelCase = torch.from_numpy(np.arange(0 , UpperCamelCase__ )[::-1].copy() ) UpperCamelCase = variance_type def A ( self : Dict , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : Optional[int] = None ): """simple docstring""" return sample def A ( self : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, torch.device] = None ): """simple docstring""" UpperCamelCase = num_inference_steps UpperCamelCase = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) UpperCamelCase = (np.arange(0 , UpperCamelCase__ ) * step_ratio).round()[::-1].copy().astype(np.intaa ) UpperCamelCase = torch.from_numpy(UpperCamelCase__ ).to(UpperCamelCase__ ) def A ( self : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Tuple=None ): """simple docstring""" if prev_timestep is None: UpperCamelCase = t - 1 UpperCamelCase = self.alphas_cumprod[t] UpperCamelCase = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one UpperCamelCase = 1 - alpha_prod_t UpperCamelCase = 1 - alpha_prod_t_prev if prev_timestep == t - 1: UpperCamelCase = self.betas[t] else: UpperCamelCase = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample UpperCamelCase = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: UpperCamelCase = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": UpperCamelCase = torch.log(torch.clamp(UpperCamelCase__ , min=1E-2_0 ) ) UpperCamelCase = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler UpperCamelCase = variance.log() UpperCamelCase = beta.log() UpperCamelCase = (predicted_variance + 1) / 2 UpperCamelCase = frac * max_log + (1 - frac) * min_log return variance def A ( self : int , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : int , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : str=None , UpperCamelCase__ : bool = True , ): """simple docstring""" UpperCamelCase = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": UpperCamelCase , UpperCamelCase = torch.split(UpperCamelCase__ , sample.shape[1] , dim=1 ) else: UpperCamelCase = None # 1. compute alphas, betas if prev_timestep is None: UpperCamelCase = t - 1 UpperCamelCase = self.alphas_cumprod[t] UpperCamelCase = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one UpperCamelCase = 1 - alpha_prod_t UpperCamelCase = 1 - alpha_prod_t_prev if prev_timestep == t - 1: UpperCamelCase = self.betas[t] UpperCamelCase = self.alphas[t] else: UpperCamelCase = 1 - alpha_prod_t / alpha_prod_t_prev UpperCamelCase = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": UpperCamelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": UpperCamelCase = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`""" ' for the UnCLIPScheduler.' ) # 3. Clip "predicted x_0" if self.config.clip_sample: UpperCamelCase = torch.clamp( UpperCamelCase__ , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCamelCase = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t UpperCamelCase = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCamelCase = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise UpperCamelCase = 0 if t > 0: UpperCamelCase = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=UpperCamelCase__ , device=model_output.device ) UpperCamelCase = self._get_variance( UpperCamelCase__ , predicted_variance=UpperCamelCase__ , prev_timestep=UpperCamelCase__ , ) if self.variance_type == "fixed_small_log": UpperCamelCase = variance elif self.variance_type == "learned_range": UpperCamelCase = (0.5 * variance).exp() else: raise ValueError( f"""variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`""" ' for the UnCLIPScheduler.' ) UpperCamelCase = variance * variance_noise UpperCamelCase = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=UpperCamelCase__ , pred_original_sample=UpperCamelCase__ ) def A ( self : int , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : torch.IntTensor , ): """simple docstring""" UpperCamelCase = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) UpperCamelCase = timesteps.to(original_samples.device ) UpperCamelCase = alphas_cumprod[timesteps] ** 0.5 UpperCamelCase = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): UpperCamelCase = sqrt_alpha_prod.unsqueeze(-1 ) UpperCamelCase = (1 - alphas_cumprod[timesteps]) ** 0.5 UpperCamelCase = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): UpperCamelCase = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) UpperCamelCase = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
28
0
import numpy as np def _lowerCAmelCase ( __lowerCAmelCase ) -> np.array: """simple docstring""" return 1 / (1 + np.exp(-vector )) if __name__ == "__main__": import doctest doctest.testmod()
44
import math import tensorflow as tf from packaging import version def _lowerCAmelCase ( __lowerCAmelCase ) -> Tuple: """simple docstring""" snake_case__ : List[str] = tf.convert_to_tensor(__lowerCAmelCase ) snake_case__ : Dict = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ) , x.dtype ) )) return x * cdf def _lowerCAmelCase ( __lowerCAmelCase ) -> List[str]: """simple docstring""" snake_case__ : Dict = tf.convert_to_tensor(__lowerCAmelCase ) snake_case__ : Tuple = tf.cast(math.pi , x.dtype ) snake_case__ : str = tf.cast(0.044_715 , x.dtype ) snake_case__ : int = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(__lowerCAmelCase , 3 )) )) return x * cdf def _lowerCAmelCase ( __lowerCAmelCase ) -> Optional[Any]: """simple docstring""" snake_case__ : Dict = tf.convert_to_tensor(__lowerCAmelCase ) return x * tf.tanh(tf.math.softplus(__lowerCAmelCase ) ) def _lowerCAmelCase ( __lowerCAmelCase ) -> Union[str, Any]: """simple docstring""" snake_case__ : List[str] = tf.convert_to_tensor(__lowerCAmelCase ) snake_case__ : str = tf.cast(0.044_715 , x.dtype ) snake_case__ : Optional[Any] = tf.cast(0.7_978_845_608 , x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def _lowerCAmelCase ( __lowerCAmelCase ) -> Union[str, Any]: """simple docstring""" snake_case__ : Optional[int] = tf.convert_to_tensor(__lowerCAmelCase ) snake_case__ : Optional[Any] = tf.cast(1.702 , x.dtype ) return x * tf.math.sigmoid(coeff * x ) def _lowerCAmelCase ( __lowerCAmelCase ) -> str: """simple docstring""" return tf.clip_by_value(_gelu(__lowerCAmelCase ) , -10 , 10 ) def _lowerCAmelCase ( __lowerCAmelCase , __lowerCAmelCase=-1 ) -> Optional[Any]: """simple docstring""" snake_case__ , snake_case__ : str = tf.split(__lowerCAmelCase , 2 , axis=__lowerCAmelCase ) return a * tf.math.sigmoid(__lowerCAmelCase ) if version.parse(tf.version.VERSION) >= version.parse('''2.4'''): def _lowerCAmelCase ( __lowerCAmelCase ) -> Optional[int]: """simple docstring""" return tf.keras.activations.gelu(__lowerCAmelCase , approximate=__lowerCAmelCase ) A__ = tf.keras.activations.gelu A__ = approximate_gelu_wrap else: A__ = _gelu A__ = _gelu_new A__ = { '''gelu''': gelu, '''gelu_10''': gelu_aa, '''gelu_fast''': gelu_fast, '''gelu_new''': gelu_new, '''glu''': glu, '''mish''': mish, '''quick_gelu''': quick_gelu, '''relu''': tf.keras.activations.relu, '''sigmoid''': tf.keras.activations.sigmoid, '''silu''': tf.keras.activations.swish, '''swish''': tf.keras.activations.swish, '''tanh''': tf.keras.activations.tanh, } def _lowerCAmelCase ( __lowerCAmelCase ) -> Optional[int]: """simple docstring""" if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}""" )
44
1
import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel a_ = '0.12' # assumed parallelism: 8 @require_flax @is_staging_test class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @classmethod def __UpperCamelCase ( cls : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = TOKEN HfFolder.save_token(a ) @classmethod def __UpperCamelCase ( cls : List[str] ) -> Optional[Any]: """simple docstring""" try: delete_repo(token=cls._token , repo_id="test-model-flax" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-model-flax-org" ) except HTTPError: pass def __UpperCamelCase ( self : Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) SCREAMING_SNAKE_CASE : List[str] = FlaxBertModel(a ) model.push_to_hub("test-model-flax" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : List[Any] = FlaxBertModel.from_pretrained(F"{USER}/test-model-flax" ) SCREAMING_SNAKE_CASE : Tuple = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE : Dict = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE : Dict = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(a , 1e-3 , msg=F"{key} not identical" ) # Reset repo delete_repo(token=self._token , repo_id="test-model-flax" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(a , repo_id="test-model-flax" , push_to_hub=a , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : int = FlaxBertModel.from_pretrained(F"{USER}/test-model-flax" ) SCREAMING_SNAKE_CASE : str = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE : Any = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE : str = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(a , 1e-3 , msg=F"{key} not identical" ) def __UpperCamelCase ( self : Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxBertModel(a ) model.push_to_hub("valid_org/test-model-flax-org" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org" ) SCREAMING_SNAKE_CASE : str = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE : List[Any] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE : Any = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(a , 1e-3 , msg=F"{key} not identical" ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-model-flax-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( a , repo_id="valid_org/test-model-flax-org" , push_to_hub=a , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : Tuple = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org" ) SCREAMING_SNAKE_CASE : Optional[int] = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE : str = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE : Optional[int] = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(a , 1e-3 , msg=F"{key} not identical" ) def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Optional[Any] = True SCREAMING_SNAKE_CASE : Union[str, Any] = flatten_dict(modela.params) SCREAMING_SNAKE_CASE : Optional[int] = flatten_dict(modela.params) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key])) > 1E-4: SCREAMING_SNAKE_CASE : Any = False return models_are_equal @require_flax class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : str = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) SCREAMING_SNAKE_CASE : List[Any] = FlaxBertModel(a ) SCREAMING_SNAKE_CASE : Optional[int] = "bert" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(a , a ) ) with self.assertRaises(a ): SCREAMING_SNAKE_CASE : Tuple = FlaxBertModel.from_pretrained(a ) SCREAMING_SNAKE_CASE : int = FlaxBertModel.from_pretrained(a , subfolder=a ) self.assertTrue(check_models_equal(a , a ) ) def __UpperCamelCase ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Any = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) SCREAMING_SNAKE_CASE : Dict = FlaxBertModel(a ) SCREAMING_SNAKE_CASE : Tuple = "bert" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(a , a ) , max_shard_size="10KB" ) with self.assertRaises(a ): SCREAMING_SNAKE_CASE : List[Any] = FlaxBertModel.from_pretrained(a ) SCREAMING_SNAKE_CASE : List[Any] = FlaxBertModel.from_pretrained(a , subfolder=a ) self.assertTrue(check_models_equal(a , a ) ) def __UpperCamelCase ( self : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : str = "bert" SCREAMING_SNAKE_CASE : Optional[Any] = "hf-internal-testing/tiny-random-bert-subfolder" with self.assertRaises(a ): SCREAMING_SNAKE_CASE : str = FlaxBertModel.from_pretrained(a ) SCREAMING_SNAKE_CASE : int = FlaxBertModel.from_pretrained(a , subfolder=a ) self.assertIsNotNone(a ) def __UpperCamelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = "bert" SCREAMING_SNAKE_CASE : Optional[int] = "hf-internal-testing/tiny-random-bert-sharded-subfolder" with self.assertRaises(a ): SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxBertModel.from_pretrained(a ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxBertModel.from_pretrained(a , subfolder=a ) self.assertIsNotNone(a )
76
"""simple docstring""" from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class lowercase__ ( snake_case__ ): _UpperCAmelCase :jnp.ndarray _UpperCAmelCase :jnp.ndarray class lowercase__ ( nn.Module ): _UpperCAmelCase :int _UpperCAmelCase :Tuple[int] = (16, 32, 96, 256) _UpperCAmelCase :jnp.dtype = jnp.floataa def UpperCAmelCase__ ( self : List[Any] ): lowerCamelCase_ : Optional[int] =nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) lowerCamelCase_ : Any =[] for i in range(len(self.block_out_channels ) - 1 ): lowerCamelCase_ : Union[str, Any] =self.block_out_channels[i] lowerCamelCase_ : Any =self.block_out_channels[i + 1] lowerCamelCase_ : List[str] =nn.Conv( snake_case__ , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(snake_case__ ) lowerCamelCase_ : List[str] =nn.Conv( snake_case__ , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(snake_case__ ) lowerCamelCase_ : Union[str, Any] =blocks lowerCamelCase_ : Optional[Any] =nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : Tuple , snake_case__ : Union[str, Any] ): lowerCamelCase_ : int =self.conv_in(snake_case__ ) lowerCamelCase_ : List[Any] =nn.silu(snake_case__ ) for block in self.blocks: lowerCamelCase_ : Union[str, Any] =block(snake_case__ ) lowerCamelCase_ : List[str] =nn.silu(snake_case__ ) lowerCamelCase_ : Tuple =self.conv_out(snake_case__ ) return embedding @flax_register_to_config class lowercase__ ( nn.Module, snake_case__, snake_case__ ): _UpperCAmelCase :int = 32 _UpperCAmelCase :int = 4 _UpperCAmelCase :Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _UpperCAmelCase :Union[bool, Tuple[bool]] = False _UpperCAmelCase :Tuple[int] = (320, 640, 1280, 1280) _UpperCAmelCase :int = 2 _UpperCAmelCase :Union[int, Tuple[int]] = 8 _UpperCAmelCase :Optional[Union[int, Tuple[int]]] = None _UpperCAmelCase :int = 1280 _UpperCAmelCase :float = 0.0 _UpperCAmelCase :bool = False _UpperCAmelCase :jnp.dtype = jnp.floataa _UpperCAmelCase :bool = True _UpperCAmelCase :int = 0 _UpperCAmelCase :str = "rgb" _UpperCAmelCase :Tuple[int] = (16, 32, 96, 256) def UpperCAmelCase__ ( self : int , snake_case__ : jax.random.KeyArray ): # init input tensors lowerCamelCase_ : str =(1, self.in_channels, self.sample_size, self.sample_size) lowerCamelCase_ : List[Any] =jnp.zeros(snake_case__ , dtype=jnp.floataa ) lowerCamelCase_ : int =jnp.ones((1,) , dtype=jnp.intaa ) lowerCamelCase_ : Union[str, Any] =jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) lowerCamelCase_ : Optional[int] =(1, 3, self.sample_size * 8, self.sample_size * 8) lowerCamelCase_ : Any =jnp.zeros(snake_case__ , dtype=jnp.floataa ) lowerCamelCase_ , lowerCamelCase_ : Any =jax.random.split(snake_case__ ) lowerCamelCase_ : Tuple ={"params": params_rng, "dropout": dropout_rng} return self.init(snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ )["params"] def UpperCAmelCase__ ( self : List[Any] ): lowerCamelCase_ : Union[str, Any] =self.block_out_channels lowerCamelCase_ : Optional[int] =block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. lowerCamelCase_ : int =self.num_attention_heads or self.attention_head_dim # input lowerCamelCase_ : Any =nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time lowerCamelCase_ : Union[str, Any] =FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) lowerCamelCase_ : List[Any] =FlaxTimestepEmbedding(snake_case__ , dtype=self.dtype ) lowerCamelCase_ : List[str] =FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) lowerCamelCase_ : Optional[int] =self.only_cross_attention if isinstance(snake_case__ , snake_case__ ): lowerCamelCase_ : str =(only_cross_attention,) * len(self.down_block_types ) if isinstance(snake_case__ , snake_case__ ): lowerCamelCase_ : Any =(num_attention_heads,) * len(self.down_block_types ) # down lowerCamelCase_ : Optional[int] =[] lowerCamelCase_ : Optional[Any] =[] lowerCamelCase_ : str =block_out_channels[0] lowerCamelCase_ : str =nn.Conv( snake_case__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case__ ) for i, down_block_type in enumerate(self.down_block_types ): lowerCamelCase_ : Union[str, Any] =output_channel lowerCamelCase_ : Tuple =block_out_channels[i] lowerCamelCase_ : List[Any] =i == len(snake_case__ ) - 1 if down_block_type == "CrossAttnDownBlock2D": lowerCamelCase_ : Tuple =FlaxCrossAttnDownBlockaD( in_channels=snake_case__ , out_channels=snake_case__ , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: lowerCamelCase_ : Union[str, Any] =FlaxDownBlockaD( in_channels=snake_case__ , out_channels=snake_case__ , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(snake_case__ ) for _ in range(self.layers_per_block ): lowerCamelCase_ : List[Any] =nn.Conv( snake_case__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case__ ) if not is_final_block: lowerCamelCase_ : Any =nn.Conv( snake_case__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(snake_case__ ) lowerCamelCase_ : List[str] =down_blocks lowerCamelCase_ : int =controlnet_down_blocks # mid lowerCamelCase_ : int =block_out_channels[-1] lowerCamelCase_ : str =FlaxUNetMidBlockaDCrossAttn( in_channels=snake_case__ , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) lowerCamelCase_ : List[str] =nn.Conv( snake_case__ , kernel_size=(1, 1) , padding="VALID" , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : Tuple , snake_case__ : Dict , snake_case__ : str , snake_case__ : Union[str, Any] , snake_case__ : int , snake_case__ : float = 1.0 , snake_case__ : bool = True , snake_case__ : bool = False , ): lowerCamelCase_ : int =self.controlnet_conditioning_channel_order if channel_order == "bgr": lowerCamelCase_ : Optional[Any] =jnp.flip(snake_case__ , axis=1 ) # 1. time if not isinstance(snake_case__ , jnp.ndarray ): lowerCamelCase_ : Dict =jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(snake_case__ , jnp.ndarray ) and len(timesteps.shape ) == 0: lowerCamelCase_ : Any =timesteps.astype(dtype=jnp.floataa ) lowerCamelCase_ : Optional[Any] =jnp.expand_dims(snake_case__ , 0 ) lowerCamelCase_ : Any =self.time_proj(snake_case__ ) lowerCamelCase_ : Union[str, Any] =self.time_embedding(snake_case__ ) # 2. pre-process lowerCamelCase_ : List[str] =jnp.transpose(snake_case__ , (0, 2, 3, 1) ) lowerCamelCase_ : Union[str, Any] =self.conv_in(snake_case__ ) lowerCamelCase_ : List[str] =jnp.transpose(snake_case__ , (0, 2, 3, 1) ) lowerCamelCase_ : str =self.controlnet_cond_embedding(snake_case__ ) sample += controlnet_cond # 3. down lowerCamelCase_ : List[str] =(sample,) for down_block in self.down_blocks: if isinstance(snake_case__ , snake_case__ ): lowerCamelCase_ , lowerCamelCase_ : Union[str, Any] =down_block(snake_case__ , snake_case__ , snake_case__ , deterministic=not train ) else: lowerCamelCase_ , lowerCamelCase_ : Optional[int] =down_block(snake_case__ , snake_case__ , deterministic=not train ) down_block_res_samples += res_samples # 4. mid lowerCamelCase_ : Optional[int] =self.mid_block(snake_case__ , snake_case__ , snake_case__ , deterministic=not train ) # 5. contronet blocks lowerCamelCase_ : Dict =() for down_block_res_sample, controlnet_block in zip(snake_case__ , self.controlnet_down_blocks ): lowerCamelCase_ : Dict =controlnet_block(snake_case__ ) controlnet_down_block_res_samples += (down_block_res_sample,) lowerCamelCase_ : List[Any] =controlnet_down_block_res_samples lowerCamelCase_ : Tuple =self.controlnet_mid_block(snake_case__ ) # 6. scaling lowerCamelCase_ : Dict =[sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=snake_case__ , mid_block_res_sample=snake_case__ )
144
0
def __lowerCamelCase ( lowerCAmelCase__ ): if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('multiplicative_persistence() only accepts integral values' ) if num < 0: raise ValueError('multiplicative_persistence() does not accept negative values' ) lowerCAmelCase__ = 0 lowerCAmelCase__ = str(lowerCAmelCase__ ) while len(lowerCAmelCase__ ) != 1: lowerCAmelCase__ = [int(lowerCAmelCase__ ) for i in num_string] lowerCAmelCase__ = 1 for i in range(0 , len(lowerCAmelCase__ ) ): total *= numbers[i] lowerCAmelCase__ = str(lowerCAmelCase__ ) steps += 1 return steps def __lowerCamelCase ( lowerCAmelCase__ ): if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('additive_persistence() only accepts integral values' ) if num < 0: raise ValueError('additive_persistence() does not accept negative values' ) lowerCAmelCase__ = 0 lowerCAmelCase__ = str(lowerCAmelCase__ ) while len(lowerCAmelCase__ ) != 1: lowerCAmelCase__ = [int(lowerCAmelCase__ ) for i in num_string] lowerCAmelCase__ = 0 for i in range(0 , len(lowerCAmelCase__ ) ): total += numbers[i] lowerCAmelCase__ = str(lowerCAmelCase__ ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
368
import argparse import math import os import torch from neural_compressor.utils.pytorch import load from PIL import Image from transformers import CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, StableDiffusionPipeline, UNetaDConditionModel def __lowerCamelCase ( ): lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument( '-m' , '--pretrained_model_name_or_path' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , required=lowerCAmelCase__ , help='Path to pretrained model or model identifier from huggingface.co/models.' , ) parser.add_argument( '-c' , '--caption' , type=lowerCAmelCase__ , default='robotic cat with wings' , help='Text used to generate images.' , ) parser.add_argument( '-n' , '--images_num' , type=lowerCAmelCase__ , default=4 , help='How much images to generate.' , ) parser.add_argument( '-s' , '--seed' , type=lowerCAmelCase__ , default=4_2 , help='Seed for random process.' , ) parser.add_argument( '-ci' , '--cuda_id' , type=lowerCAmelCase__ , default=0 , help='cuda_id.' , ) lowerCAmelCase__ = parser.parse_args() return args def __lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): if not len(lowerCAmelCase__ ) == rows * cols: raise ValueError('The specified number of rows and columns are not correct.' ) lowerCAmelCase__ , lowerCAmelCase__ = imgs[0].size lowerCAmelCase__ = Image.new('RGB' , size=(cols * w, rows * h) ) lowerCAmelCase__ , lowerCAmelCase__ = grid.size for i, img in enumerate(lowerCAmelCase__ ): grid.paste(lowerCAmelCase__ , box=(i % cols * w, i // cols * h) ) return grid def __lowerCamelCase ( lowerCAmelCase__ , lowerCAmelCase__="robotic cat with wings" , lowerCAmelCase__=7.5 , lowerCAmelCase__=5_0 , lowerCAmelCase__=1 , lowerCAmelCase__=4_2 , ): lowerCAmelCase__ = torch.Generator(pipeline.device ).manual_seed(lowerCAmelCase__ ) lowerCAmelCase__ = pipeline( lowerCAmelCase__ , guidance_scale=lowerCAmelCase__ , num_inference_steps=lowerCAmelCase__ , generator=lowerCAmelCase__ , num_images_per_prompt=lowerCAmelCase__ , ).images lowerCAmelCase__ = int(math.sqrt(lowerCAmelCase__ ) ) lowerCAmelCase__ = image_grid(lowerCAmelCase__ , rows=_rows , cols=num_images_per_prompt // _rows ) return grid, images lowerCAmelCase__ = parse_args() # Load models and create wrapper for stable diffusion lowerCAmelCase__ = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path, subfolder='tokenizer') lowerCAmelCase__ = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='text_encoder') lowerCAmelCase__ = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder='vae') lowerCAmelCase__ = UNetaDConditionModel.from_pretrained(args.pretrained_model_name_or_path, subfolder='unet') lowerCAmelCase__ = StableDiffusionPipeline.from_pretrained( args.pretrained_model_name_or_path, text_encoder=text_encoder, vae=vae, unet=unet, tokenizer=tokenizer ) lowerCAmelCase__ = lambda images, clip_input: (images, False) if os.path.exists(os.path.join(args.pretrained_model_name_or_path, 'best_model.pt')): lowerCAmelCase__ = load(args.pretrained_model_name_or_path, model=unet) unet.eval() setattr(pipeline, 'unet', unet) else: lowerCAmelCase__ = unet.to(torch.device('cuda', args.cuda_id)) lowerCAmelCase__ = pipeline.to(unet.device) lowerCAmelCase__ , lowerCAmelCase__ = generate_images(pipeline, prompt=args.caption, num_images_per_prompt=args.images_num, seed=args.seed) grid.save(os.path.join(args.pretrained_model_name_or_path, '{}.png'.format('_'.join(args.caption.split())))) lowerCAmelCase__ = os.path.join(args.pretrained_model_name_or_path, '_'.join(args.caption.split())) os.makedirs(dirname, exist_ok=True) for idx, image in enumerate(images): image.save(os.path.join(dirname, '{}.png'.format(idx + 1)))
119
0
"""simple docstring""" def __magic_name__ ( lowercase , lowercase ): while b: SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: Union[str, Any] =b, a % b return a def __magic_name__ ( lowercase , lowercase ): return a if b == 0 else euclidean_gcd_recursive(_a , a % b ) def __magic_name__ ( ): print(f'''euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}''' ) print(f'''euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}''' ) print(f'''euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}''' ) print(f'''euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}''' ) print(f'''euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}''' ) print(f'''euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}''' ) print(f'''euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}''' ) print(f'''euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}''' ) print(f'''euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}''' ) print(f'''euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}''' ) if __name__ == "__main__": main()
173
'''simple docstring''' from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class _a ( __a ): __a : str = ["""vqvae"""] def __init__( self : str , lowercase : AutoencoderKL , lowercase : UNetaDConditionModel , lowercase : Mel , lowercase : Union[DDIMScheduler, DDPMScheduler] , ): '''simple docstring''' super().__init__() self.register_modules(unet=lowercase , scheduler=lowercase , mel=lowercase , vqvae=lowercase ) def A ( self : Optional[Any] ): '''simple docstring''' return 50 if isinstance(self.scheduler , lowercase ) else 1_000 @torch.no_grad() def __call__( self : Optional[Any] , lowercase : int = 1 , lowercase : str = None , lowercase : np.ndarray = None , lowercase : int = 0 , lowercase : int = 0 , lowercase : int = None , lowercase : torch.Generator = None , lowercase : float = 0 , lowercase : float = 0 , lowercase : torch.Generator = None , lowercase : float = 0 , lowercase : torch.Tensor = None , lowercase : torch.Tensor = None , lowercase : Tuple=True , ): '''simple docstring''' UpperCAmelCase = steps or self.get_default_steps() self.scheduler.set_timesteps(lowercase ) UpperCAmelCase = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: UpperCAmelCase = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: UpperCAmelCase = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=lowercase , device=self.device , ) UpperCAmelCase = noise UpperCAmelCase = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(lowercase , lowercase ) UpperCAmelCase = self.mel.audio_slice_to_image(lowercase ) UpperCAmelCase = np.frombuffer(input_image.tobytes() , dtype='''uint8''' ).reshape( (input_image.height, input_image.width) ) UpperCAmelCase = (input_image / 255) * 2 - 1 UpperCAmelCase = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: UpperCAmelCase = self.vqvae.encode(torch.unsqueeze(lowercase , 0 ) ).latent_dist.sample( generator=lowercase )[0] UpperCAmelCase = self.vqvae.config.scaling_factor * input_images if start_step > 0: UpperCAmelCase = self.scheduler.add_noise(lowercase , lowercase , self.scheduler.timesteps[start_step - 1] ) UpperCAmelCase = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) UpperCAmelCase = int(mask_start_secs * pixels_per_second ) UpperCAmelCase = int(mask_end_secs * pixels_per_second ) UpperCAmelCase = self.scheduler.add_noise(lowercase , lowercase , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , lowercase ): UpperCAmelCase = self.unet(lowercase , lowercase , lowercase )['''sample'''] else: UpperCAmelCase = self.unet(lowercase , lowercase )['''sample'''] if isinstance(self.scheduler , lowercase ): UpperCAmelCase = self.scheduler.step( model_output=lowercase , timestep=lowercase , sample=lowercase , eta=lowercase , generator=lowercase , )['''prev_sample'''] else: UpperCAmelCase = self.scheduler.step( model_output=lowercase , timestep=lowercase , sample=lowercase , generator=lowercase , )['''prev_sample'''] if mask is not None: if mask_start > 0: UpperCAmelCase = mask[:, step, :, :mask_start] if mask_end > 0: UpperCAmelCase = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance UpperCAmelCase = 1 / self.vqvae.config.scaling_factor * images UpperCAmelCase = self.vqvae.decode(lowercase )['''sample'''] UpperCAmelCase = (images / 2 + 0.5).clamp(0 , 1 ) UpperCAmelCase = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() UpperCAmelCase = (images * 255).round().astype('''uint8''' ) UpperCAmelCase = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(lowercase , mode='''RGB''' ).convert('''L''' ) for _ in images) ) UpperCAmelCase = [self.mel.image_to_audio(lowercase ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(lowercase )[:, np.newaxis, :] ) , **ImagePipelineOutput(lowercase ) ) @torch.no_grad() def A ( self : Dict , lowercase : List[Image.Image] , lowercase : int = 50 ): '''simple docstring''' assert isinstance(self.scheduler , lowercase ) self.scheduler.set_timesteps(lowercase ) UpperCAmelCase = np.array( [np.frombuffer(image.tobytes() , dtype='''uint8''' ).reshape((1, image.height, image.width) ) for image in images] ) UpperCAmelCase = (sample / 255) * 2 - 1 UpperCAmelCase = torch.Tensor(lowercase ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): UpperCAmelCase = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps UpperCAmelCase = self.scheduler.alphas_cumprod[t] UpperCAmelCase = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) UpperCAmelCase = 1 - alpha_prod_t UpperCAmelCase = self.unet(lowercase , lowercase )['''sample'''] UpperCAmelCase = (1 - alpha_prod_t_prev) ** 0.5 * model_output UpperCAmelCase = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) UpperCAmelCase = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def A ( lowercase : torch.Tensor , lowercase : torch.Tensor , lowercase : float ): '''simple docstring''' UpperCAmelCase = acos(torch.dot(torch.flatten(lowercase ) , torch.flatten(lowercase ) ) / torch.norm(lowercase ) / torch.norm(lowercase ) ) return sin((1 - alpha) * theta ) * xa / sin(lowercase ) + sin(alpha * theta ) * xa / sin(lowercase )
34
0
"""simple docstring""" from __future__ import annotations import math from collections import Counter from string import ascii_lowercase def snake_case ( A__ ): UpperCAmelCase_ : Dict = analyze_text(A__ ) UpperCAmelCase_ : Dict = list(" " + ascii_lowercase ) # what is our total sum of probabilities. UpperCAmelCase_ : Any = sum(single_char_strings.values() ) # one length string UpperCAmelCase_ : List[Any] = 0 # for each alpha we go in our dict and if it is in it we calculate entropy for ch in my_alphas: if ch in single_char_strings: UpperCAmelCase_ : List[str] = single_char_strings[ch] UpperCAmelCase_ : List[Any] = my_str / all_sum my_fir_sum += prob * math.loga(A__ ) # entropy formula. # print entropy print(F"""{round(-1 * my_fir_sum ):.1f}""" ) # two len string UpperCAmelCase_ : Union[str, Any] = sum(two_char_strings.values() ) UpperCAmelCase_ : Union[str, Any] = 0 # for each alpha (two in size) calculate entropy. for cha in my_alphas: for cha in my_alphas: UpperCAmelCase_ : Tuple = cha + cha if sequence in two_char_strings: UpperCAmelCase_ : int = two_char_strings[sequence] UpperCAmelCase_ : Tuple = int(A__ ) / all_sum my_sec_sum += prob * math.loga(A__ ) # print second entropy print(F"""{round(-1 * my_sec_sum ):.1f}""" ) # print the difference between them print(F"""{round((-1 * my_sec_sum) - (-1 * my_fir_sum) ):.1f}""" ) def snake_case ( A__ ): UpperCAmelCase_ : Optional[int] = Counter() # type: ignore UpperCAmelCase_ : Any = Counter() # type: ignore single_char_strings[text[-1]] += 1 # first case when we have space at start. two_char_strings[" " + text[0]] += 1 for i in range(0 ,len(A__ ) - 1 ): single_char_strings[text[i]] += 1 two_char_strings[text[i : i + 2]] += 1 return single_char_strings, two_char_strings def snake_case ( ): import doctest doctest.testmod() # text = ( # "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark " # "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest " # "jointure saw horrible. He private he on be imagine suppose. Fertile " # "beloved evident through no service elderly is. Blind there if every no so " # "at. Own neglected you preferred way sincerity delivered his attempted. To " # "of message cottage windows do besides against uncivil. Delightful " # "unreserved impossible few estimating men favourable see entreaties. She " # "propriety immediate was improving. He or entrance humoured likewise " # "moderate. Much nor game son say feel. Fat make met can must form into " # "gate. Me we offending prevailed discovery. " # ) # calculate_prob(text) if __name__ == "__main__": main()
370
"""simple docstring""" def snake_case ( A__ = 10_00 ): UpperCAmelCase_ : Optional[Any] = 2**power UpperCAmelCase_ : Optional[int] = str(A__ ) UpperCAmelCase_ : Tuple = list(A__ ) UpperCAmelCase_ : Any = 0 for i in list_num: sum_of_num += int(A__ ) return sum_of_num if __name__ == "__main__": lowerCamelCase_ = int(input('''Enter the power of 2: ''').strip()) print('''2 ^ ''', power, ''' = ''', 2**power) lowerCamelCase_ = solution(power) print('''Sum of the digits is: ''', result)
253
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) def a_ ( _lowerCAmelCase ,_lowerCAmelCase=False ,_lowerCAmelCase=False ,_lowerCAmelCase=False ) -> Optional[Any]: __lowerCamelCase : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'transformer.blocks.{i}.norm1.weight', F'vilt.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'transformer.blocks.{i}.norm1.bias', F'vilt.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append( (F'transformer.blocks.{i}.attn.proj.weight', F'vilt.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append( (F'transformer.blocks.{i}.attn.proj.bias', F'vilt.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'transformer.blocks.{i}.norm2.weight', F'vilt.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'transformer.blocks.{i}.norm2.bias', F'vilt.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append( (F'transformer.blocks.{i}.mlp.fc1.weight', F'vilt.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'transformer.blocks.{i}.mlp.fc1.bias', F'vilt.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'transformer.blocks.{i}.mlp.fc2.weight', F'vilt.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'transformer.blocks.{i}.mlp.fc2.bias', F'vilt.encoder.layer.{i}.output.dense.bias') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def a_ ( _lowerCAmelCase ,_lowerCAmelCase ) -> int: for i in range(config.num_hidden_layers ): __lowerCamelCase : str = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __lowerCamelCase : Tuple = state_dict.pop(F'transformer.blocks.{i}.attn.qkv.weight' ) __lowerCamelCase : Optional[int] = state_dict.pop(F'transformer.blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict __lowerCamelCase : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] __lowerCamelCase : Optional[int] = in_proj_bias[: config.hidden_size] __lowerCamelCase : Tuple = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __lowerCamelCase : Tuple = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __lowerCamelCase : List[str] = in_proj_weight[ -config.hidden_size :, : ] __lowerCamelCase : Optional[Any] = in_proj_bias[-config.hidden_size :] def a_ ( _lowerCAmelCase ) -> Optional[int]: __lowerCamelCase : Union[str, Any] = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(_lowerCAmelCase ,_lowerCAmelCase ) def a_ ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ) -> List[str]: __lowerCamelCase : Optional[int] = dct.pop(_lowerCAmelCase ) __lowerCamelCase : Dict = val @torch.no_grad() def a_ ( _lowerCAmelCase ,_lowerCAmelCase ) -> Tuple: __lowerCamelCase : Union[str, Any] = ViltConfig(image_size=384 ,patch_size=32 ,tie_word_embeddings=_lowerCAmelCase ) __lowerCamelCase : Any = False __lowerCamelCase : int = False __lowerCamelCase : Union[str, Any] = False __lowerCamelCase : Union[str, Any] = False if "vqa" in checkpoint_url: __lowerCamelCase : int = True __lowerCamelCase : Any = 3129 __lowerCamelCase : int = 'huggingface/label-files' __lowerCamelCase : Tuple = 'vqa2-id2label.json' __lowerCamelCase : Tuple = json.load(open(hf_hub_download(_lowerCAmelCase ,_lowerCAmelCase ,repo_type='dataset' ) ,'r' ) ) __lowerCamelCase : List[Any] = {int(_lowerCAmelCase ): v for k, v in idalabel.items()} __lowerCamelCase : str = idalabel __lowerCamelCase : int = {v: k for k, v in idalabel.items()} __lowerCamelCase : Optional[int] = ViltForQuestionAnswering(_lowerCAmelCase ) elif "nlvr" in checkpoint_url: __lowerCamelCase : Dict = True __lowerCamelCase : str = 2 __lowerCamelCase : Optional[Any] = {0: 'False', 1: 'True'} __lowerCamelCase : int = {v: k for k, v in config.idalabel.items()} __lowerCamelCase : Optional[int] = 3 __lowerCamelCase : List[str] = ViltForImagesAndTextClassification(_lowerCAmelCase ) elif "irtr" in checkpoint_url: __lowerCamelCase : int = True __lowerCamelCase : Optional[Any] = ViltForImageAndTextRetrieval(_lowerCAmelCase ) elif "mlm_itm" in checkpoint_url: __lowerCamelCase : Dict = True __lowerCamelCase : Optional[Any] = ViltForMaskedLM(_lowerCAmelCase ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys __lowerCamelCase : Tuple = torch.hub.load_state_dict_from_url(_lowerCAmelCase ,map_location='cpu' )['state_dict'] __lowerCamelCase : List[Any] = create_rename_keys(_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ) for src, dest in rename_keys: rename_key(_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ) read_in_q_k_v(_lowerCAmelCase ,_lowerCAmelCase ) if mlm_model or irtr_model: __lowerCamelCase : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(_lowerCAmelCase ,_lowerCAmelCase ) # load state dict into HuggingFace model model.eval() if mlm_model: __lowerCamelCase : Optional[Any] = model.load_state_dict(_lowerCAmelCase ,strict=_lowerCAmelCase ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(_lowerCAmelCase ) # Define processor __lowerCamelCase : List[str] = ViltImageProcessor(size=384 ) __lowerCamelCase : List[str] = BertTokenizer.from_pretrained('bert-base-uncased' ) __lowerCamelCase : List[str] = ViltProcessor(_lowerCAmelCase ,_lowerCAmelCase ) # Forward pass on example inputs (image + text) if nlvr_model: __lowerCamelCase : Tuple = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' ,stream=_lowerCAmelCase ).raw ) __lowerCamelCase : List[Any] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' ,stream=_lowerCAmelCase ).raw ) __lowerCamelCase : Union[str, Any] = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) __lowerCamelCase : Tuple = processor(_lowerCAmelCase ,_lowerCAmelCase ,return_tensors='pt' ) __lowerCamelCase : List[Any] = processor(_lowerCAmelCase ,_lowerCAmelCase ,return_tensors='pt' ) __lowerCamelCase : str = model( input_ids=encoding_a.input_ids ,pixel_values=encoding_a.pixel_values ,pixel_values_a=encoding_a.pixel_values ,) else: __lowerCamelCase : Dict = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' ,stream=_lowerCAmelCase ).raw ) if mlm_model: __lowerCamelCase : Optional[int] = 'a bunch of [MASK] laying on a [MASK].' else: __lowerCamelCase : Optional[Any] = 'How many cats are there?' __lowerCamelCase : Optional[Any] = processor(_lowerCAmelCase ,_lowerCAmelCase ,return_tensors='pt' ) __lowerCamelCase : Optional[Any] = model(**_lowerCAmelCase ) # Verify outputs if mlm_model: __lowerCamelCase : int = torch.Size([1, 11, 30522] ) __lowerCamelCase : int = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] ,_lowerCAmelCase ,atol=1E-4 ) # verify masked token prediction equals "cats" __lowerCamelCase : Optional[Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: __lowerCamelCase : str = torch.Size([1, 3129] ) __lowerCamelCase : Dict = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] ,_lowerCAmelCase ,atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] ,_lowerCAmelCase ,atol=1E-4 ) # verify vqa prediction equals "2" __lowerCamelCase : Optional[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: __lowerCamelCase : Dict = torch.Size([1, 2] ) __lowerCamelCase : Optional[Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] ,_lowerCAmelCase ,atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) print(F'Saving model and processor to {pytorch_dump_folder_path}' ) model.save_pretrained(_lowerCAmelCase ) processor.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt', type=str, help='URL of the checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) _UpperCamelCase = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
208
import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 _a = { '''return_dict''': False, '''output_hidden_states''': True, '''output_attentions''': True, '''torchscript''': True, '''torch_dtype''': '''float16''', '''use_bfloat16''': True, '''tf_legacy_loss''': True, '''pruned_heads''': {'''a''': 1}, '''tie_word_embeddings''': False, '''is_decoder''': True, '''cross_attention_hidden_size''': 1_2_8, '''add_cross_attention''': True, '''tie_encoder_decoder''': True, '''max_length''': 5_0, '''min_length''': 3, '''do_sample''': True, '''early_stopping''': True, '''num_beams''': 3, '''num_beam_groups''': 3, '''diversity_penalty''': 0.5, '''temperature''': 2.0, '''top_k''': 1_0, '''top_p''': 0.7, '''typical_p''': 0.2, '''repetition_penalty''': 0.8, '''length_penalty''': 0.8, '''no_repeat_ngram_size''': 5, '''encoder_no_repeat_ngram_size''': 5, '''bad_words_ids''': [1, 2, 3], '''num_return_sequences''': 3, '''chunk_size_feed_forward''': 5, '''output_scores''': True, '''return_dict_in_generate''': True, '''forced_bos_token_id''': 2, '''forced_eos_token_id''': 3, '''remove_invalid_values''': True, '''architectures''': ['''BertModel'''], '''finetuning_task''': '''translation''', '''id2label''': {0: '''label'''}, '''label2id''': {'''label''': '''0'''}, '''tokenizer_class''': '''BertTokenizerFast''', '''prefix''': '''prefix''', '''bos_token_id''': 6, '''pad_token_id''': 7, '''eos_token_id''': 8, '''sep_token_id''': 9, '''decoder_start_token_id''': 1_0, '''exponential_decay_length_penalty''': (5, 1.01), '''suppress_tokens''': [0, 1], '''begin_suppress_tokens''': 2, '''task_specific_params''': {'''translation''': '''some_params'''}, '''problem_type''': '''regression''', } @is_staging_test class A_ ( unittest.TestCase ): @classmethod def UpperCAmelCase ( cls : Dict ) -> List[str]: __lowerCAmelCase: str = TOKEN HfFolder.save_token(UpperCAmelCase ) @classmethod def UpperCAmelCase ( cls : str ) -> List[Any]: try: delete_repo(token=cls._token , repo_id='test-config' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-config-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-config' ) except HTTPError: pass def UpperCAmelCase ( self : int ) -> Optional[int]: __lowerCAmelCase: Any = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) config.push_to_hub('test-config' , use_auth_token=self._token ) __lowerCAmelCase: str = BertConfig.from_pretrained(F'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) ) # Reset repo delete_repo(token=self._token , repo_id='test-config' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(UpperCAmelCase , repo_id='test-config' , push_to_hub=UpperCAmelCase , use_auth_token=self._token ) __lowerCAmelCase: Union[str, Any] = BertConfig.from_pretrained(F'''{USER}/test-config''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) ) def UpperCAmelCase ( self : int ) -> Dict: __lowerCAmelCase: int = BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) config.push_to_hub('valid_org/test-config-org' , use_auth_token=self._token ) __lowerCAmelCase: Dict = BertConfig.from_pretrained('valid_org/test-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-config-org' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( UpperCAmelCase , repo_id='valid_org/test-config-org' , push_to_hub=UpperCAmelCase , use_auth_token=self._token ) __lowerCAmelCase: int = BertConfig.from_pretrained('valid_org/test-config-org' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) ) def UpperCAmelCase ( self : Union[str, Any] ) -> List[str]: CustomConfig.register_for_auto_class() __lowerCAmelCase: Any = CustomConfig(attribute=4_2 ) config.push_to_hub('test-dynamic-config' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {'AutoConfig': 'custom_configuration.CustomConfig'} ) __lowerCAmelCase: int = AutoConfig.from_pretrained(F'''{USER}/test-dynamic-config''' , trust_remote_code=UpperCAmelCase ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , 'CustomConfig' ) self.assertEqual(new_config.attribute , 4_2 ) class A_ ( unittest.TestCase ): def UpperCAmelCase ( self : Union[str, Any] ) -> int: __lowerCAmelCase: List[Any] = GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated __lowerCAmelCase: Union[str, Any] = c.n_embd + 1 # int __lowerCAmelCase: str = c.resid_pdrop + 1.0 # float __lowerCAmelCase: List[Any] = not c.scale_attn_weights # bool __lowerCAmelCase: List[str] = c.summary_type + 'foo' # str c.update_from_string( F'''n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}''' ) self.assertEqual(UpperCAmelCase , c.n_embd , 'mismatch for key: n_embd' ) self.assertEqual(UpperCAmelCase , c.resid_pdrop , 'mismatch for key: resid_pdrop' ) self.assertEqual(UpperCAmelCase , c.scale_attn_weights , 'mismatch for key: scale_attn_weights' ) self.assertEqual(UpperCAmelCase , c.summary_type , 'mismatch for key: summary_type' ) def UpperCAmelCase ( self : Optional[Any] ) -> Any: __lowerCAmelCase: str = PretrainedConfig() __lowerCAmelCase: Optional[int] = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( UpperCAmelCase , ['is_encoder_decoder', '_name_or_path', '_commit_hash', 'transformers_version'] ) __lowerCAmelCase: int = [key for key, value in config_common_kwargs.items() if value == getattr(UpperCAmelCase , UpperCAmelCase )] if len(UpperCAmelCase ) > 0: raise ValueError( 'The following keys are set with the default values in' ' `test_configuration_common.config_common_kwargs` pick another value for them:' F''' {', '.join(UpperCAmelCase )}.''' ) def UpperCAmelCase ( self : int ) -> Optional[Any]: with self.assertRaises(UpperCAmelCase ): # config is in subfolder, the following should not work without specifying the subfolder __lowerCAmelCase: List[Any] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder' ) __lowerCAmelCase: List[str] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert-subfolder' , subfolder='bert' ) self.assertIsNotNone(UpperCAmelCase ) def UpperCAmelCase ( self : Tuple ) -> List[Any]: # A mock response for an HTTP head request to emulate server down __lowerCAmelCase: Union[str, Any] = mock.Mock() __lowerCAmelCase: str = 5_0_0 __lowerCAmelCase: Optional[Any] = {} __lowerCAmelCase: Optional[int] = HTTPError __lowerCAmelCase: List[Any] = {} # Download this model to make sure it's in the cache. __lowerCAmelCase: Tuple = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request' , return_value=UpperCAmelCase ) as mock_head: __lowerCAmelCase: Union[str, Any] = BertConfig.from_pretrained('hf-internal-testing/tiny-random-bert' ) # This check we did call the fake head request mock_head.assert_called() def UpperCAmelCase ( self : Any ) -> Optional[Any]: # This test is for deprecated behavior and can be removed in v5 __lowerCAmelCase: Tuple = BertConfig.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json' ) def UpperCAmelCase ( self : Dict ) -> str: __lowerCAmelCase: Optional[Any] = AutoConfig.from_pretrained('bert-base-cased' ) __lowerCAmelCase: Optional[Any] = ['config.4.0.0.json'] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(UpperCAmelCase ) __lowerCAmelCase: Tuple = 2 json.dump(configuration.to_dict() , open(os.path.join(UpperCAmelCase , 'config.4.0.0.json' ) , 'w' ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 __lowerCAmelCase: Dict = AutoConfig.from_pretrained(UpperCAmelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 __lowerCAmelCase: Dict = ['config.42.0.0.json'] __lowerCAmelCase: Optional[int] = 7_6_8 configuration.save_pretrained(UpperCAmelCase ) shutil.move(os.path.join(UpperCAmelCase , 'config.4.0.0.json' ) , os.path.join(UpperCAmelCase , 'config.42.0.0.json' ) ) __lowerCAmelCase: int = AutoConfig.from_pretrained(UpperCAmelCase ) self.assertEqual(new_configuration.hidden_size , 7_6_8 ) def UpperCAmelCase ( self : Union[str, Any] ) -> Dict: # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. __lowerCAmelCase: Tuple = 'hf-internal-testing/test-two-configs' import transformers as new_transformers __lowerCAmelCase: List[Any] = 'v4.0.0' __lowerCAmelCase , __lowerCAmelCase: Any = new_transformers.models.auto.AutoConfig.from_pretrained( UpperCAmelCase , return_unused_kwargs=UpperCAmelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(UpperCAmelCase , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers __lowerCAmelCase: List[Any] = 'v3.0.0' __lowerCAmelCase: Union[str, Any] = old_transformers.models.auto.AutoConfig.from_pretrained(UpperCAmelCase ) self.assertEqual(old_configuration.hidden_size , 7_6_8 )
322
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class a__ ( UpperCAmelCase__ , unittest.TestCase ): lowerCamelCase : int =KandinskyVaaPipeline lowerCamelCase : Union[str, Any] =[ "image_embeds", "negative_image_embeds", ] lowerCamelCase : Tuple =["image_embeds", "negative_image_embeds"] lowerCamelCase : Optional[int] =[ "generator", "height", "width", "latents", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] lowerCamelCase : Union[str, Any] =False @property def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" return 32 @property def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" return 32 @property def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" return self.time_input_dim @property def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" return self.time_input_dim * 4 @property def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" return 1_00 @property def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" torch.manual_seed(0 ) __lowerCamelCase = { '''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 = UNetaDConditionModel(**a ) return model @property def SCREAMING_SNAKE_CASE__ ( self : Any ): """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" torch.manual_seed(0 ) __lowerCamelCase = VQModel(**self.dummy_movq_kwargs ) return model def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" __lowerCamelCase = self.dummy_unet __lowerCamelCase = self.dummy_movq __lowerCamelCase = DDIMScheduler( num_train_timesteps=10_00 , beta_schedule='''linear''' , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=a , set_alpha_to_one=a , steps_offset=1 , prediction_type='''epsilon''' , thresholding=a , ) __lowerCamelCase = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def SCREAMING_SNAKE_CASE__ ( self : str , a : int , a : Optional[int]=0 ): """simple docstring""" __lowerCamelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(a ) ).to(a ) __lowerCamelCase = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( a ) if str(a ).startswith('''mps''' ): __lowerCamelCase = torch.manual_seed(a ) else: __lowerCamelCase = torch.Generator(device=a ).manual_seed(a ) __lowerCamelCase = { '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" __lowerCamelCase = '''cpu''' __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = self.pipeline_class(**a ) __lowerCamelCase = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) __lowerCamelCase = pipe(**self.get_dummy_inputs(a ) ) __lowerCamelCase = output.images __lowerCamelCase = pipe( **self.get_dummy_inputs(a ) , return_dict=a , )[0] __lowerCamelCase = image[0, -3:, -3:, -1] __lowerCamelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase = np.array( [0.6_23_79_76, 1.0, 0.36_44_13_32, 1.0, 0.70_63_96_34, 0.29_87_71_86, 0.85_65_21_25, 0.5_21_68_43, 0.54_45_40_46] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), f""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), f""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class a__ ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" __lowerCamelCase = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy''' ) __lowerCamelCase = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(a ) __lowerCamelCase = KandinskyVaaPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder''' , torch_dtype=torch.floataa ) __lowerCamelCase = pipeline.to(a ) pipeline.set_progress_bar_config(disable=a ) __lowerCamelCase = '''red cat, 4k photo''' __lowerCamelCase = torch.Generator(device='''cuda''' ).manual_seed(0 ) __lowerCamelCase , __lowerCamelCase = pipe_prior( a , generator=a , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() __lowerCamelCase = torch.Generator(device='''cuda''' ).manual_seed(0 ) __lowerCamelCase = pipeline( image_embeds=a , negative_image_embeds=a , generator=a , num_inference_steps=1_00 , output_type='''np''' , ) __lowerCamelCase = output.images[0] assert image.shape == (5_12, 5_12, 3) assert_mean_pixel_difference(a , a )
237
'''simple docstring''' import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class a__ : def __init__( self : List[Any] , a : Tuple , a : int , a : int ): """simple docstring""" if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) __lowerCamelCase = img __lowerCamelCase = img.shape[1] __lowerCamelCase = img.shape[0] __lowerCamelCase = dst_width __lowerCamelCase = dst_height __lowerCamelCase = self.src_w / self.dst_w __lowerCamelCase = self.src_h / self.dst_h __lowerCamelCase = __lowerCamelCase = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def SCREAMING_SNAKE_CASE__ ( self : str ): """simple docstring""" for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase = self.img[self.get_y(a )][self.get_x(a )] def SCREAMING_SNAKE_CASE__ ( self : Optional[int] , a : int ): """simple docstring""" return int(self.ratio_x * x ) def SCREAMING_SNAKE_CASE__ ( self : Tuple , a : int ): """simple docstring""" return int(self.ratio_y * y ) if __name__ == "__main__": __UpperCAmelCase , __UpperCAmelCase =8_0_0, 6_0_0 __UpperCAmelCase =imread("image_data/lena.jpg", 1) __UpperCAmelCase =NearestNeighbour(im, dst_w, dst_h) n.process() imshow( f'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
237
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available A__ : Any ={ '''configuration_canine''': ['''CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CanineConfig'''], '''tokenization_canine''': ['''CanineTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A__ : Tuple =[ '''CANINE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CanineForMultipleChoice''', '''CanineForQuestionAnswering''', '''CanineForSequenceClassification''', '''CanineForTokenClassification''', '''CanineLayer''', '''CanineModel''', '''CaninePreTrainedModel''', '''load_tf_weights_in_canine''', ] if TYPE_CHECKING: from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig from .tokenization_canine import CanineTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_canine import ( CANINE_PRETRAINED_MODEL_ARCHIVE_LIST, CanineForMultipleChoice, CanineForQuestionAnswering, CanineForSequenceClassification, CanineForTokenClassification, CanineLayer, CanineModel, CaninePreTrainedModel, load_tf_weights_in_canine, ) else: import sys A__ : Dict =_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
70
'''simple docstring''' import os import pytest from datasets import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, ) A__ : List[Any] =pytest.mark.integration @pytest.mark.parametrize("""path""" , ["""paws""", """csv"""] ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase ): """simple docstring""" inspect_dataset(lowerCAmelCase , lowerCAmelCase ) _lowerCAmelCase = path + """.py""" assert script_name in os.listdir(lowerCAmelCase ) assert "__pycache__" not in os.listdir(lowerCAmelCase ) @pytest.mark.filterwarnings("""ignore:inspect_metric is deprecated:FutureWarning""" ) @pytest.mark.filterwarnings("""ignore:metric_module_factory is deprecated:FutureWarning""" ) @pytest.mark.parametrize("""path""" , ["""accuracy"""] ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase ): """simple docstring""" inspect_metric(lowerCAmelCase , lowerCAmelCase ) _lowerCAmelCase = path + """.py""" assert script_name in os.listdir(lowerCAmelCase ) assert "__pycache__" not in os.listdir(lowerCAmelCase ) @pytest.mark.parametrize( """path, config_name, expected_splits""" , [ ("""squad""", """plain_text""", ["""train""", """validation"""]), ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]), ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]), ] , ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = get_dataset_config_info(lowerCAmelCase , config_name=lowerCAmelCase ) assert info.config_name == config_name assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( """path, config_name, expected_exception""" , [ ("""paws""", None, ValueError), ] , ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" with pytest.raises(lowerCAmelCase ): get_dataset_config_info(lowerCAmelCase , config_name=lowerCAmelCase ) @pytest.mark.parametrize( """path, expected""" , [ ("""squad""", """plain_text"""), ("""acronym_identification""", """default"""), ("""lhoestq/squad""", """plain_text"""), ("""lhoestq/test""", """default"""), ("""lhoestq/demo1""", """lhoestq--demo1"""), ("""dalle-mini/wit""", """dalle-mini--wit"""), ] , ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = get_dataset_config_names(lowerCAmelCase ) assert expected in config_names @pytest.mark.parametrize( """path, expected_configs, expected_splits_in_first_config""" , [ ("""squad""", ["""plain_text"""], ["""train""", """validation"""]), ("""dalle-mini/wit""", ["""dalle-mini--wit"""], ["""train"""]), ("""paws""", ["""labeled_final""", """labeled_swap""", """unlabeled_final"""], ["""train""", """test""", """validation"""]), ] , ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = get_dataset_infos(lowerCAmelCase ) assert list(infos.keys() ) == expected_configs _lowerCAmelCase = expected_configs[0] assert expected_config in infos _lowerCAmelCase = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits_in_first_config @pytest.mark.parametrize( """path, expected_config, expected_splits""" , [ ("""squad""", """plain_text""", ["""train""", """validation"""]), ("""dalle-mini/wit""", """dalle-mini--wit""", ["""train"""]), ("""paws""", """labeled_final""", ["""train""", """test""", """validation"""]), ] , ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = get_dataset_infos(lowerCAmelCase ) assert expected_config in infos _lowerCAmelCase = infos[expected_config] assert info.config_name == expected_config assert list(info.splits.keys() ) == expected_splits @pytest.mark.parametrize( """path, config_name, expected_exception""" , [ ("""paws""", None, ValueError), ] , ) def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" with pytest.raises(lowerCAmelCase ): get_dataset_split_names(lowerCAmelCase , config_name=lowerCAmelCase )
70
1
import re from filelock import FileLock try: import nltk lowercase_ = True except (ImportError, ModuleNotFoundError): lowercase_ = False if NLTK_AVAILABLE: with FileLock('.lock') as lock: nltk.download('punkt', quiet=True) def UpperCamelCase__ ( SCREAMING_SNAKE_CASE__ ): re.sub('<n>' , '' , SCREAMING_SNAKE_CASE__ ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(SCREAMING_SNAKE_CASE__ ) )
194
import warnings from .generation import TFGenerationMixin class A_ ( __UpperCamelCase ): '''simple docstring''' warnings.warn( """Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will """ """be removed in Transformers v5. Import as `from transformers import TFGenerationMixin` instead.""" , __UpperCamelCase , )
194
1
"""simple docstring""" import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer lowercase_ = ["gpt2"] lowercase_ = "gpt2" if is_tf_available(): class __lowerCAmelCase ( tf.Module ): '''simple docstring''' def __init__( self , _a ): super().__init__() __a = tokenizer __a = AutoConfig.from_pretrained(_a ) __a = TFGPTaLMHeadModel.from_config(_a ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name='''text''' ),) ) def __UpperCAmelCase ( self , _a ): __a = self.tokenizer(_a ) __a = tokenized["input_ids"].to_tensor() __a = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) __a = self.model(input_ids=_a , attention_mask=_a )["logits"] return outputs @require_tf @require_keras_nlp class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): super().setUp() __a = [GPTaTokenizer.from_pretrained(_a ) for checkpoint in (TOKENIZER_CHECKPOINTS)] __a = [TFGPTaTokenizer.from_pretrained(_a ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) __a = [ "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ċ, ꝼ", ] __a = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def __UpperCAmelCase ( self ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: __a = tokenizer([test_inputs] , return_tensors='''tf''' ) __a = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors __a = python_outputs[key].numpy() __a = 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 __UpperCAmelCase ( self ): for tf_tokenizer in self.tf_tokenizers: __a = tf.function(_a ) for test_inputs in self.test_sentences: __a = tf.constant(_a ) __a = compiled_tokenizer(_a ) __a = tf_tokenizer(_a ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def __UpperCAmelCase ( self ): for tf_tokenizer in self.tf_tokenizers: __a = ModelToSave(tokenizer=_a ) __a = tf.convert_to_tensor([self.test_sentences[0]] ) __a = model.serving(_a ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: __a = Path(_a ) / "saved.model" tf.saved_model.save(_a , _a , signatures={'''serving_default''': model.serving} ) __a = tf.saved_model.load(_a ) __a = 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 __UpperCAmelCase ( self ): for tf_tokenizer in self.tf_tokenizers: __a = tf.convert_to_tensor([self.test_sentences[0]] ) __a = tf_tokenizer(_a ) # Build model with some sample inputs __a = tf_tokenizer.get_config() __a = TFGPTaTokenizer.from_config(_a ) __a = model_from_config(_a ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def __UpperCAmelCase ( self ): for tf_tokenizer in self.tf_tokenizers: # for the test to run __a = 123_123 for max_length in [3, 5, 1_024]: __a = tf.convert_to_tensor([self.test_sentences[0]] ) __a = tf_tokenizer(_a , max_length=_a ) __a = out["input_ids"].numpy().shape[1] assert out_length == max_length
45
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() a : Dict = logging.get_logger(__name__) def lowercase ( __magic_name__ ): '''simple docstring''' UpperCAmelCase : List[str] = YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: UpperCAmelCase : Tuple = 192 UpperCAmelCase : str = 768 UpperCAmelCase : List[Any] = 12 UpperCAmelCase : List[Any] = 3 UpperCAmelCase : List[Any] = [800, 1333] UpperCAmelCase : List[str] = False elif yolos_name == "yolos_s_dWr": UpperCAmelCase : Union[str, Any] = 330 UpperCAmelCase : Union[str, Any] = 14 UpperCAmelCase : Any = 6 UpperCAmelCase : int = 1320 elif "yolos_s" in yolos_name: UpperCAmelCase : Union[str, Any] = 384 UpperCAmelCase : Dict = 1536 UpperCAmelCase : str = 12 UpperCAmelCase : List[str] = 6 elif "yolos_b" in yolos_name: UpperCAmelCase : int = [800, 1344] UpperCAmelCase : Optional[int] = 91 UpperCAmelCase : int = "huggingface/label-files" UpperCAmelCase : Union[str, Any] = "coco-detection-id2label.json" UpperCAmelCase : Optional[Any] = json.load(open(hf_hub_download(__magic_name__ , __magic_name__ , repo_type="dataset" ) , "r" ) ) UpperCAmelCase : str = {int(__magic_name__ ): v for k, v in idalabel.items()} UpperCAmelCase : str = idalabel UpperCAmelCase : Union[str, Any] = {v: k for k, v in idalabel.items()} return config def lowercase ( __magic_name__ , __magic_name__ , __magic_name__ = False ): '''simple docstring''' for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase : Tuple = state_dict.pop(F"blocks.{i}.attn.qkv.weight" ) UpperCAmelCase : List[Any] = state_dict.pop(F"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase : str = in_proj_weight[: config.hidden_size, :] UpperCAmelCase : Optional[int] = in_proj_bias[: config.hidden_size] UpperCAmelCase : Optional[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase : str = in_proj_weight[-config.hidden_size :, :] UpperCAmelCase : Tuple = in_proj_bias[-config.hidden_size :] def lowercase ( __magic_name__ ): '''simple docstring''' if "backbone" in name: UpperCAmelCase : int = name.replace("backbone" , "vit" ) if "cls_token" in name: UpperCAmelCase : Dict = name.replace("cls_token" , "embeddings.cls_token" ) if "det_token" in name: UpperCAmelCase : int = name.replace("det_token" , "embeddings.detection_tokens" ) if "mid_pos_embed" in name: UpperCAmelCase : Tuple = name.replace("mid_pos_embed" , "encoder.mid_position_embeddings" ) if "pos_embed" in name: UpperCAmelCase : int = name.replace("pos_embed" , "embeddings.position_embeddings" ) if "patch_embed.proj" in name: UpperCAmelCase : str = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "blocks" in name: UpperCAmelCase : Tuple = name.replace("blocks" , "encoder.layer" ) if "attn.proj" in name: UpperCAmelCase : Tuple = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name: UpperCAmelCase : Any = name.replace("attn" , "attention.self" ) if "norm1" in name: UpperCAmelCase : int = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: UpperCAmelCase : List[str] = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: UpperCAmelCase : List[str] = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: UpperCAmelCase : Dict = name.replace("mlp.fc2" , "output.dense" ) if "class_embed" in name: UpperCAmelCase : Any = name.replace("class_embed" , "class_labels_classifier" ) if "bbox_embed" in name: UpperCAmelCase : Optional[int] = name.replace("bbox_embed" , "bbox_predictor" ) if "vit.norm" in name: UpperCAmelCase : Tuple = name.replace("vit.norm" , "vit.layernorm" ) return name def lowercase ( __magic_name__ , __magic_name__ ): '''simple docstring''' for key in orig_state_dict.copy().keys(): UpperCAmelCase : Optional[int] = orig_state_dict.pop(__magic_name__ ) if "qkv" in key: UpperCAmelCase : str = key.split("." ) UpperCAmelCase : List[Any] = int(key_split[2] ) UpperCAmelCase : int = model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: UpperCAmelCase : Optional[int] = val[:dim, :] UpperCAmelCase : Union[str, Any] = val[ dim : dim * 2, : ] UpperCAmelCase : Any = val[-dim:, :] else: UpperCAmelCase : Tuple = val[:dim] UpperCAmelCase : List[str] = val[dim : dim * 2] UpperCAmelCase : Any = val[-dim:] else: UpperCAmelCase : Union[str, Any] = val return orig_state_dict def lowercase ( ): '''simple docstring''' UpperCAmelCase : Union[str, Any] = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase : Tuple = Image.open(requests.get(__magic_name__ , stream=__magic_name__ ).raw ) return im @torch.no_grad() def lowercase ( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = False ): '''simple docstring''' UpperCAmelCase : Tuple = get_yolos_config(__magic_name__ ) # load original state_dict UpperCAmelCase : int = torch.load(__magic_name__ , map_location="cpu" )["model"] # load 🤗 model UpperCAmelCase : int = YolosForObjectDetection(__magic_name__ ) model.eval() UpperCAmelCase : Dict = convert_state_dict(__magic_name__ , __magic_name__ ) model.load_state_dict(__magic_name__ ) # Check outputs on an image, prepared by YolosImageProcessor UpperCAmelCase : Dict = 800 if yolos_name != "yolos_ti" else 512 UpperCAmelCase : int = YolosImageProcessor(format="coco_detection" , size=__magic_name__ ) UpperCAmelCase : List[Any] = image_processor(images=prepare_img() , return_tensors="pt" ) UpperCAmelCase : List[str] = model(**__magic_name__ ) UpperCAmelCase , UpperCAmelCase : Optional[int] = outputs.logits, outputs.pred_boxes UpperCAmelCase , UpperCAmelCase : Optional[Any] = None, None if yolos_name == "yolos_ti": UpperCAmelCase : str = torch.tensor( [[-3_9.5_0_2_2, -1_1.9_8_2_0, -1_7.6_8_8_8], [-2_9.9_5_7_4, -9.9_7_6_9, -1_7.7_6_9_1], [-4_2.3_2_8_1, -2_0.7_2_0_0, -3_0.6_2_9_4]] ) UpperCAmelCase : Tuple = torch.tensor( [[0.4_0_2_1, 0.0_8_3_6, 0.7_9_7_9], [0.0_1_8_4, 0.2_6_0_9, 0.0_3_6_4], [0.1_7_8_1, 0.2_0_0_4, 0.2_0_9_5]] ) elif yolos_name == "yolos_s_200_pre": UpperCAmelCase : Union[str, Any] = torch.tensor( [[-2_4.0_2_4_8, -1_0.3_0_2_4, -1_4.8_2_9_0], [-4_2.0_3_9_2, -1_6.8_2_0_0, -2_7.4_3_3_4], [-2_7.2_7_4_3, -1_1.8_1_5_4, -1_8.7_1_4_8]] ) UpperCAmelCase : List[str] = torch.tensor( [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]] ) elif yolos_name == "yolos_s_300_pre": UpperCAmelCase : List[str] = torch.tensor( [[-3_6.2_2_2_0, -1_4.4_3_8_5, -2_3.5_4_5_7], [-3_5.6_9_7_0, -1_4.7_5_8_3, -2_1.3_9_3_5], [-3_1.5_9_3_9, -1_3.6_0_4_2, -1_6.8_0_4_9]] ) UpperCAmelCase : Dict = torch.tensor( [[0.7_6_1_4, 0.2_3_1_6, 0.4_7_2_8], [0.7_1_6_8, 0.4_4_9_5, 0.3_8_5_5], [0.4_9_9_6, 0.1_4_6_6, 0.9_9_9_6]] ) elif yolos_name == "yolos_s_dWr": UpperCAmelCase : Dict = torch.tensor( [[-4_2.8_6_6_8, -2_4.1_0_4_9, -4_1.1_6_9_0], [-3_4.7_4_5_6, -1_4.1_2_7_4, -2_4.9_1_9_4], [-3_3.7_8_9_8, -1_2.1_9_4_6, -2_5.6_4_9_5]] ) UpperCAmelCase : List[Any] = torch.tensor( [[0.5_5_8_7, 0.2_7_7_3, 0.0_6_0_5], [0.5_0_0_4, 0.3_0_1_4, 0.9_9_9_4], [0.4_9_9_9, 0.1_5_4_8, 0.9_9_9_4]] ) elif yolos_name == "yolos_base": UpperCAmelCase : str = torch.tensor( [[-4_0.6_0_6_4, -2_4.3_0_8_4, -3_2.6_4_4_7], [-5_5.1_9_9_0, -3_0.7_7_1_9, -3_5.5_8_7_7], [-5_1.4_3_1_1, -3_3.3_5_0_7, -3_5.6_4_6_2]] ) UpperCAmelCase : Union[str, Any] = torch.tensor( [[0.5_5_5_5, 0.2_7_9_4, 0.0_6_5_5], [0.9_0_4_9, 0.2_6_6_4, 0.1_8_9_4], [0.9_1_8_3, 0.1_9_8_4, 0.1_6_3_5]] ) else: raise ValueError(F"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , __magic_name__ , atol=1e-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , __magic_name__ , atol=1e-4 ) Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) print(F"Saving model {yolos_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(__magic_name__ ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(__magic_name__ ) if push_to_hub: UpperCAmelCase : int = { "yolos_ti": "yolos-tiny", "yolos_s_200_pre": "yolos-small", "yolos_s_300_pre": "yolos-small-300", "yolos_s_dWr": "yolos-small-dwr", "yolos_base": "yolos-base", } print("Pushing to the hub..." ) UpperCAmelCase : Tuple = model_mapping[yolos_name] image_processor.push_to_hub(__magic_name__ , organization="hustvl" ) model.push_to_hub(__magic_name__ , organization="hustvl" ) if __name__ == "__main__": a : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--yolos_name", default="yolos_s_200_pre", type=str, help=( "Name of the YOLOS model you'd like to convert. Should be one of 'yolos_ti', 'yolos_s_200_pre'," " 'yolos_s_300_pre', 'yolos_s_dWr', 'yolos_base'." ), ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original state dict (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) a : str = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
311
0
'''simple docstring''' def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[int]] ): '''simple docstring''' def update_area_of_max_square(SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 UpperCAmelCase__ = update_area_of_max_square(SCREAMING_SNAKE_CASE__ , col + 1 ) UpperCAmelCase__ = update_area_of_max_square(row + 1 , col + 1 ) UpperCAmelCase__ = update_area_of_max_square(row + 1 , SCREAMING_SNAKE_CASE__ ) if mat[row][col]: UpperCAmelCase__ = 1 + min([right, diagonal, down] ) UpperCAmelCase__ = max(largest_square_area[0] , SCREAMING_SNAKE_CASE__ ) return sub_problem_sol else: return 0 UpperCAmelCase__ = [0] update_area_of_max_square(0 , 0 ) return largest_square_area[0] def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[int]] ): '''simple docstring''' def update_area_of_max_square_using_dp_array( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[int]] ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] UpperCAmelCase__ = update_area_of_max_square_using_dp_array(SCREAMING_SNAKE_CASE__ , col + 1 , SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = update_area_of_max_square_using_dp_array(row + 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if mat[row][col]: UpperCAmelCase__ = 1 + min([right, diagonal, down] ) UpperCAmelCase__ = max(largest_square_area[0] , SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = sub_problem_sol return sub_problem_sol else: return 0 UpperCAmelCase__ = [0] UpperCAmelCase__ = [[-1] * cols for _ in range(SCREAMING_SNAKE_CASE__ )] update_area_of_max_square_using_dp_array(0 , 0 , SCREAMING_SNAKE_CASE__ ) return largest_square_area[0] def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[int]] ): '''simple docstring''' UpperCAmelCase__ = [[0] * (cols + 1) for _ in range(rows + 1 )] UpperCAmelCase__ = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): UpperCAmelCase__ = dp_array[row][col + 1] UpperCAmelCase__ = dp_array[row + 1][col + 1] UpperCAmelCase__ = dp_array[row + 1][col] if mat[row][col] == 1: UpperCAmelCase__ = 1 + min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = max(dp_array[row][col] , SCREAMING_SNAKE_CASE__ ) else: UpperCAmelCase__ = 0 return largest_square_area def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : list[list[int]] ): '''simple docstring''' UpperCAmelCase__ = [0] * (cols + 1) UpperCAmelCase__ = [0] * (cols + 1) UpperCAmelCase__ = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): UpperCAmelCase__ = current_row[col + 1] UpperCAmelCase__ = next_row[col + 1] UpperCAmelCase__ = next_row[col] if mat[row][col] == 1: UpperCAmelCase__ = 1 + min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) UpperCAmelCase__ = max(current_row[col] , SCREAMING_SNAKE_CASE__ ) else: UpperCAmelCase__ = 0 UpperCAmelCase__ = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
61
'''simple docstring''' import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging UpperCAmelCase_ = logging.get_logger(__name__) def _UpperCamelCase ( ): '''simple docstring''' UpperCAmelCase__ = os.getenv("""SM_HP_MP_PARAMETERS""" , """{}""" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. UpperCAmelCase__ = json.loads(SCREAMING_SNAKE_CASE__ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. UpperCAmelCase__ = os.getenv("""SM_FRAMEWORK_PARAMS""" , """{}""" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". UpperCAmelCase__ = json.loads(SCREAMING_SNAKE_CASE__ ) if not mpi_options.get("""sagemaker_mpi_enabled""" , SCREAMING_SNAKE_CASE__ ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("""smdistributed""" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class lowerCAmelCase_ ( lowerCamelCase_ ): '''simple docstring''' lowerCAmelCase_ : str = field( default="""""" , metadata={"""help""": """Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"""} , ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" super().__post_init__() warnings.warn( """`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use """ """`TrainingArguments` instead.""" , _UpperCAmelCase , ) @cached_property def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" logger.info("""PyTorch: setting up devices""" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( """torch.distributed process group is initialized, but local_rank == -1. """ """In order to use Torch DDP, launch your script with `python -m torch.distributed.launch""" ) if self.no_cuda: UpperCAmelCase__ = torch.device("""cpu""" ) UpperCAmelCase__ = 0 elif is_sagemaker_model_parallel_available(): UpperCAmelCase__ = smp.local_rank() UpperCAmelCase__ = torch.device("""cuda""" , _UpperCAmelCase ) UpperCAmelCase__ = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="""smddp""" , timeout=self.ddp_timeout_delta ) UpperCAmelCase__ = int(os.getenv("""SMDATAPARALLEL_LOCAL_RANK""" ) ) UpperCAmelCase__ = torch.device("""cuda""" , self.local_rank ) UpperCAmelCase__ = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 UpperCAmelCase__ = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. UpperCAmelCase__ = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="""nccl""" , timeout=self.ddp_timeout_delta ) UpperCAmelCase__ = torch.device("""cuda""" , self.local_rank ) UpperCAmelCase__ = 1 if device.type == "cuda": torch.cuda.set_device(_UpperCAmelCase ) return device @property def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" return not is_sagemaker_model_parallel_available() @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" return False
61
1
"""simple docstring""" A: Optional[int] = { 0: "0", 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 1_0: "a", 1_1: "b", 1_2: "c", 1_3: "d", 1_4: "e", 1_5: "f", } def _snake_case ( UpperCamelCase : float ): assert type(UpperCamelCase__ ) in (int, float) and decimal == int(UpperCamelCase__ ) UpperCAmelCase : Union[str, Any] = int(UpperCamelCase__ ) UpperCAmelCase : Tuple = '''''' UpperCAmelCase : int = False if decimal < 0: UpperCAmelCase : Optional[int] = True decimal *= -1 while decimal > 0: UpperCAmelCase : str = divmod(UpperCamelCase__ , 16 ) UpperCAmelCase : List[str] = values[remainder] + hexadecimal UpperCAmelCase : Optional[int] = '''0x''' + hexadecimal if negative: UpperCAmelCase : List[Any] = '''-''' + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
109
'''simple docstring''' import re def _a( UpperCamelCase__ : str ): '''simple docstring''' return [char.split() for char in re.split(R'''[^ a-z A-Z 0-9 \s]''', str_ )] def _a( UpperCamelCase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int =split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def _a( UpperCamelCase__ : str, UpperCamelCase__ : bool, UpperCamelCase__ : str ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Any =split_input(UpperCamelCase__ ) if upper: SCREAMING_SNAKE_CASE__ : int =''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: SCREAMING_SNAKE_CASE__ : Any =''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def _a( UpperCamelCase__ : str ): '''simple docstring''' return to_simple_case(UpperCamelCase__ ) def _a( UpperCamelCase__ : str ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : List[str] =to_simple_case(UpperCamelCase__ ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def _a( UpperCamelCase__ : str, UpperCamelCase__ : bool ): '''simple docstring''' return to_complex_case(UpperCamelCase__, UpperCamelCase__, '''_''' ) def _a( UpperCamelCase__ : str, UpperCamelCase__ : bool ): '''simple docstring''' return to_complex_case(UpperCamelCase__, UpperCamelCase__, '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
152
0
a : Dict = """ABCDEFGHIJKLMNOPQRSTUVWXYZ""" def __lowerCamelCase ( ) -> None: UpperCAmelCase : Optional[int] = input("""Enter message: """ ) UpperCAmelCase : Dict = input("""Enter key [alphanumeric]: """ ) UpperCAmelCase : Optional[Any] = input("""Encrypt/Decrypt [e/d]: """ ) if mode.lower().startswith("""e""" ): UpperCAmelCase : List[str] = """encrypt""" UpperCAmelCase : List[str] = encrypt_message(_lowercase , _lowercase ) elif mode.lower().startswith("""d""" ): UpperCAmelCase : Tuple = """decrypt""" UpperCAmelCase : str = decrypt_message(_lowercase , _lowercase ) print(F'''\n{mode.title()}ed message:''' ) print(_lowercase ) def __lowerCamelCase ( _lowercase , _lowercase ) -> str: return translate_message(_lowercase , _lowercase , """encrypt""" ) def __lowerCamelCase ( _lowercase , _lowercase ) -> str: return translate_message(_lowercase , _lowercase , """decrypt""" ) def __lowerCamelCase ( _lowercase , _lowercase , _lowercase ) -> str: UpperCAmelCase : Optional[int] = [] UpperCAmelCase : Optional[Any] = 0 UpperCAmelCase : Tuple = key.upper() for symbol in message: UpperCAmelCase : Dict = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(_lowercase ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(_lowercase ): UpperCAmelCase : Optional[int] = 0 else: translated.append(_lowercase ) return "".join(_lowercase ) if __name__ == "__main__": main()
355
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a : List[Any] = { """configuration_m2m_100""": ["""M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP""", """M2M100Config""", """M2M100OnnxConfig"""], """tokenization_m2m_100""": ["""M2M100Tokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a : Any = [ """M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST""", """M2M100ForConditionalGeneration""", """M2M100Model""", """M2M100PreTrainedModel""", ] if TYPE_CHECKING: from .configuration_mam_aaa import M2M_100_PRETRAINED_CONFIG_ARCHIVE_MAP, MaMaaaConfig, MaMaaaOnnxConfig from .tokenization_mam_aaa import MaMaaaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mam_aaa import ( M2M_100_PRETRAINED_MODEL_ARCHIVE_LIST, MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaPreTrainedModel, ) else: import sys a : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
338
0