code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' from __future__ import annotations def __a ( lowerCAmelCase__ : list[float] ): if len(lowerCAmelCase__ ) < 2: raise ValueError('''Monogons and Digons are not polygons in the Euclidean space''' ) if any(i <= 0 for i in nums ): raise ValueError('''All values must be greater than 0''' ) a__ : Union[str, Any] = nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1] ) if __name__ == "__main__": import doctest doctest.testmod()
688
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass def __a ( lowerCAmelCase__ : List[str] ): for shard in shards: for i in range(lowerCAmelCase__ ): yield {"i": i, "shard": shard} def __a ( ): a__ : str = int(os.environ['''RANK'''] ) a__ : int = int(os.environ['''WORLD_SIZE'''] ) a__ : str = ArgumentParser() parser.add_argument('''--streaming''' , type=lowerCAmelCase__ ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase__ ) parser.add_argument('''--num_workers''' , type=lowerCAmelCase__ , default=0 ) a__ : int = parser.parse_args() a__ : List[str] = args.streaming a__ : Dict = args.num_workers a__ : Dict = {'''shards''': [F'shard_{shard_idx}' for shard_idx in range(lowerCAmelCase__ )]} a__ : Tuple = IterableDataset.from_generator(lowerCAmelCase__ , gen_kwargs=lowerCAmelCase__ ) if not streaming: a__ : str = Dataset.from_list(list(lowerCAmelCase__ ) ) a__ : Optional[int] = split_dataset_by_node(lowerCAmelCase__ , rank=lowerCAmelCase__ , world_size=lowerCAmelCase__ ) a__ : Dict = torch.utils.data.DataLoader(lowerCAmelCase__ , num_workers=lowerCAmelCase__ ) a__ : str = NUM_SHARDS * NUM_ITEMS_PER_SHARD a__ : Dict = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) a__ : str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'local_size {local_size} != expected_local_size {expected_local_size}' ) if __name__ == "__main__": main()
688
1
'''simple docstring''' def __a ( lowerCAmelCase__ : List[Any]=28123 ): a__ : List[Any] = [1] * (limit + 1) for i in range(2 , int(limit**0.5 ) + 1 ): sum_divs[i * i] += i for k in range(i + 1 , limit // i + 1 ): sum_divs[k * i] += k + i a__ : Dict = set() a__ : Dict = 0 for n in range(1 , limit + 1 ): if sum_divs[n] > n: abundants.add(lowerCAmelCase__ ) if not any((n - a in abundants) for a in abundants ): res += n return res if __name__ == "__main__": print(solution())
688
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __SCREAMING_SNAKE_CASE = open # noqa: we just need to have a builtin inside this module to test it properly
688
1
'''simple docstring''' import jax.numpy as jnp from ...utils import logging from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel from .configuration_mta import MTaConfig __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = 'T5Config' def __a ( lowerCAmelCase__ : jnp.array , lowerCAmelCase__ : int , lowerCAmelCase__ : int ): a__ : Any = jnp.zeros_like(lowerCAmelCase__ ) a__ : Optional[Any] = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1] ) a__ : Dict = shifted_input_ids.at[:, 0].set(lowerCAmelCase__ ) a__ : Any = jnp.where(shifted_input_ids == -100 , lowerCAmelCase__ , lowerCAmelCase__ ) return shifted_input_ids class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "mt5" __UpperCamelCase = MTaConfig class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "mt5" __UpperCamelCase = MTaConfig class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "mt5" __UpperCamelCase = MTaConfig
688
'''simple docstring''' import enum import shutil import sys __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = shutil.get_terminal_size() __SCREAMING_SNAKE_CASE = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase__ ( enum.Enum ): """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 1 def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict="" ): sys.stdout.write(str(lowerCAmelCase__ ) + end ) sys.stdout.flush() def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : int="" ): forceWrite(F'\u001b[{color}m{content}\u001b[0m' , lowerCAmelCase__ ) def __a ( ): forceWrite('''\r''' ) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : str ): forceWrite(F'\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}' ) def __a ( ): forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def __a ( ): reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
688
1
'''simple docstring''' import re import time from typing import Optional import IPython.display as disp from ..trainer_callback import TrainerCallback from ..trainer_utils import IntervalStrategy, has_length def __a ( lowerCAmelCase__ : Optional[int] ): a__ : int = int(lowerCAmelCase__ ) a__ , a__ , a__ : List[Any] = t // 3600, (t // 60) % 60, t % 60 return F'{h}:{m:02d}:{s:02d}' if h != 0 else F'{m:02d}:{s:02d}' def __a ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any]=300 ): # docstyle-ignore return F'\n <div>\n {prefix}\n <progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>\n {label}\n </div>\n ' def __a ( lowerCAmelCase__ : Tuple ): a__ : str = '''<table border="1" class="dataframe">\n''' html_code += """ <thead>\n <tr style="text-align: left;">\n""" for i in items[0]: html_code += F' <th>{i}</th>\n' html_code += " </tr>\n </thead>\n <tbody>\n" for line in items[1:]: html_code += " <tr>\n" for elt in line: a__ : int = F'{elt:.6f}' if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) else str(lowerCAmelCase__ ) html_code += F' <td>{elt}</td>\n' html_code += " </tr>\n" html_code += " </tbody>\n</table><p>" return html_code class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = 5 __UpperCamelCase = 0.2 def __init__( self : int , A__ : int , A__ : Optional[str] = None , A__ : bool = True , A__ : Optional["NotebookTrainingTracker"] = None , A__ : int = 3_0_0 , ) -> List[str]: '''simple docstring''' a__ : Tuple = total a__ : List[str] = '''''' if prefix is None else prefix a__ : int = leave a__ : Tuple = parent a__ : Optional[Any] = width a__ : Union[str, Any] = None a__ : int = None a__ : str = None def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , A__ : bool = False , A__ : str = None ) -> List[str]: '''simple docstring''' a__ : List[str] = value if comment is not None: a__ : Tuple = comment if self.last_value is None: a__ : Tuple = time.time() a__ : Union[str, Any] = value a__ : List[Any] = None a__ : List[Any] = self.warmup a__ : Dict = 1 self.update_bar(A__ ) elif value <= self.last_value and not force_update: return elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for , self.total ): if self.first_calls > 0: self.first_calls -= 1 a__ : Optional[Any] = time.time() a__ : List[Any] = current_time - self.start_time # We could have value = self.start_value if the update is called twixe with the same start value. if value > self.start_value: a__ : Any = self.elapsed_time / (value - self.start_value) else: a__ : List[Any] = None if value >= self.total: a__ : Optional[Any] = self.total a__ : Optional[int] = None if not self.leave: self.close() elif self.average_time_per_item is not None: a__ : List[str] = self.average_time_per_item * (self.total - value) self.update_bar(A__ ) a__ : Any = value a__ : Tuple = current_time if self.average_time_per_item is None: a__ : Union[str, Any] = 1 else: a__ : Union[str, Any] = max(int(self.update_every / self.average_time_per_item ) , 1 ) def __lowerCAmelCase ( self : Optional[int] , A__ : List[str] , A__ : Dict=None ) -> Tuple: '''simple docstring''' a__ : Any = ''' ''' * (len(str(self.total ) ) - len(str(A__ ) )) + str(A__ ) if self.elapsed_time is None: a__ : Optional[int] = F'[{spaced_value}/{self.total} : < :' elif self.predicted_remaining is None: a__ : Any = F'[{spaced_value}/{self.total} {format_time(self.elapsed_time )}' else: a__ : int = ( F'[{spaced_value}/{self.total} {format_time(self.elapsed_time )} <' F' {format_time(self.predicted_remaining )}' ) self.label += F', {1/self.average_time_per_item:.2f} it/s' self.label += "]" if self.comment is None or len(self.comment ) == 0 else F', {self.comment}]' self.display() def __lowerCAmelCase ( self : Tuple ) -> int: '''simple docstring''' a__ : str = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width ) if self.parent is not None: # If this is a child bar, the parent will take care of the display. self.parent.display() return if self.output is None: a__ : List[str] = disp.display(disp.HTML(self.html_code ) , display_id=A__ ) else: self.output.update(disp.HTML(self.html_code ) ) def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' if self.parent is None and self.output is not None: self.output.update(disp.HTML('''''' ) ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : int , A__ : int , A__ : List[Any]=None ) -> str: '''simple docstring''' super().__init__(A__ ) a__ : Dict = None if column_names is None else [column_names] a__ : Dict = None def __lowerCAmelCase ( self : Optional[int] ) -> Any: '''simple docstring''' a__ : Dict = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width ) if self.inner_table is not None: self.html_code += text_to_html_table(self.inner_table ) if self.child_bar is not None: self.html_code += self.child_bar.html_code if self.output is None: a__ : List[str] = disp.display(disp.HTML(self.html_code ) , display_id=A__ ) else: self.output.update(disp.HTML(self.html_code ) ) def __lowerCAmelCase ( self : Any , A__ : List[str] ) -> Optional[Any]: '''simple docstring''' if self.inner_table is None: a__ : int = [list(values.keys() ), list(values.values() )] else: a__ : str = self.inner_table[0] if len(self.inner_table ) == 1: # We give a chance to update the column names at the first iteration for key in values.keys(): if key not in columns: columns.append(A__ ) a__ : str = columns self.inner_table.append([values[c] for c in columns] ) def __lowerCAmelCase ( self : Dict , A__ : Optional[Any] , A__ : List[str]=None , A__ : int=3_0_0 ) -> Any: '''simple docstring''' a__ : Union[str, Any] = NotebookProgressBar(A__ , prefix=A__ , parent=self , width=A__ ) return self.child_bar def __lowerCAmelCase ( self : Any ) -> List[Any]: '''simple docstring''' a__ : Dict = None self.display() class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : List[Any] ) -> Optional[int]: '''simple docstring''' a__ : Dict = None a__ : Dict = None a__ : Optional[int] = False def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : Tuple , A__ : Optional[int] , **A__ : Optional[int] ) -> Any: '''simple docstring''' a__ : Optional[Any] = '''Epoch''' if args.evaluation_strategy == IntervalStrategy.EPOCH else '''Step''' a__ : Any = 0 a__ : List[Any] = 0 a__ : Dict = [self.first_column] + ['''Training Loss'''] if args.evaluation_strategy != IntervalStrategy.NO: column_names.append('''Validation Loss''' ) a__ : Any = NotebookTrainingTracker(state.max_steps , A__ ) def __lowerCAmelCase ( self : List[str] , A__ : List[str] , A__ : str , A__ : List[str] , **A__ : Dict ) -> Dict: '''simple docstring''' a__ : Dict = int(state.epoch ) if int(state.epoch ) == state.epoch else F'{state.epoch:.2f}' self.training_tracker.update( state.global_step + 1 , comment=F'Epoch {epoch}/{state.num_train_epochs}' , force_update=self._force_next_update , ) a__ : Union[str, Any] = False def __lowerCAmelCase ( self : Dict , A__ : Tuple , A__ : Dict , A__ : Tuple , A__ : List[Any]=None , **A__ : Optional[int] ) -> str: '''simple docstring''' if not has_length(A__ ): return if self.prediction_bar is None: if self.training_tracker is not None: a__ : str = self.training_tracker.add_child(len(A__ ) ) else: a__ : List[Any] = NotebookProgressBar(len(A__ ) ) self.prediction_bar.update(1 ) else: self.prediction_bar.update(self.prediction_bar.value + 1 ) def __lowerCAmelCase ( self : Dict , A__ : Tuple , A__ : int , A__ : Dict , **A__ : Dict ) -> Tuple: '''simple docstring''' if self.prediction_bar is not None: self.prediction_bar.close() a__ : int = None def __lowerCAmelCase ( self : Optional[Any] , A__ : Tuple , A__ : Tuple , A__ : Union[str, Any] , A__ : List[Any]=None , **A__ : Any ) -> str: '''simple docstring''' if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs: a__ : Any = {'''Training Loss''': logs['''loss''']} # First column is necessarily Step sine we're not in epoch eval strategy a__ : Optional[int] = state.global_step self.training_tracker.write_line(A__ ) def __lowerCAmelCase ( self : List[Any] , A__ : Any , A__ : Any , A__ : Tuple , A__ : int=None , **A__ : List[Any] ) -> Union[str, Any]: '''simple docstring''' if self.training_tracker is not None: a__ : Any = {'''Training Loss''': '''No log''', '''Validation Loss''': '''No log'''} for log in reversed(state.log_history ): if "loss" in log: a__ : Any = log['''loss'''] break if self.first_column == "Epoch": a__ : Union[str, Any] = int(state.epoch ) else: a__ : Any = state.global_step a__ : Optional[int] = '''eval''' for k in metrics: if k.endswith('''_loss''' ): a__ : Optional[int] = re.sub(r'''\_loss$''' , '''''' , A__ ) a__ : Optional[int] = metrics.pop('''total_flos''' , A__ ) a__ : Any = metrics.pop('''epoch''' , A__ ) a__ : Union[str, Any] = metrics.pop(F'{metric_key_prefix}_runtime' , A__ ) a__ : List[Any] = metrics.pop(F'{metric_key_prefix}_samples_per_second' , A__ ) a__ : List[Any] = metrics.pop(F'{metric_key_prefix}_steps_per_second' , A__ ) a__ : Union[str, Any] = metrics.pop(F'{metric_key_prefix}_jit_compilation_time' , A__ ) for k, v in metrics.items(): if k == F'{metric_key_prefix}_loss': a__ : Union[str, Any] = v else: a__ : int = k.split('''_''' ) a__ : Tuple = ''' '''.join([part.capitalize() for part in splits[1:]] ) a__ : int = v self.training_tracker.write_line(A__ ) self.training_tracker.remove_child() a__ : List[Any] = None # Evaluation takes a long time so we should force the next update. a__ : Optional[Any] = True def __lowerCAmelCase ( self : Dict , A__ : Optional[Any] , A__ : List[str] , A__ : Any , **A__ : Union[str, Any] ) -> List[str]: '''simple docstring''' self.training_tracker.update( state.global_step , comment=F'Epoch {int(state.epoch )}/{state.num_train_epochs}' , force_update=A__ ) a__ : Any = None
688
'''simple docstring''' import inspect import unittest class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' try: import diffusers # noqa: F401 except ImportError: assert False def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' import diffusers from diffusers.dependency_versions_table import deps a__ : Optional[int] = inspect.getmembers(A__ , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": a__ : int = '''k-diffusion''' elif backend == "invisible_watermark": a__ : int = '''invisible-watermark''' assert backend in deps, F'{backend} is not in the deps table!'
688
1
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'microsoft/layoutlmv3-base': 'https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json', } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "layoutlmv3" def __init__( self : Union[str, Any] , A__ : Optional[Any]=5_0_2_6_5 , A__ : int=7_6_8 , A__ : str=1_2 , A__ : Tuple=1_2 , A__ : Optional[Any]=3_0_7_2 , A__ : Union[str, Any]="gelu" , A__ : List[Any]=0.1 , A__ : str=0.1 , A__ : List[str]=5_1_2 , A__ : Optional[Any]=2 , A__ : Optional[Any]=0.02 , A__ : int=1E-5 , A__ : Union[str, Any]=1 , A__ : Tuple=0 , A__ : Union[str, Any]=2 , A__ : Tuple=1_0_2_4 , A__ : Tuple=1_2_8 , A__ : List[str]=1_2_8 , A__ : Tuple=True , A__ : List[str]=3_2 , A__ : Tuple=1_2_8 , A__ : Dict=6_4 , A__ : Dict=2_5_6 , A__ : int=True , A__ : List[str]=True , A__ : Optional[Any]=True , A__ : str=2_2_4 , A__ : str=3 , A__ : Tuple=1_6 , A__ : int=None , **A__ : Union[str, Any] , ) -> Tuple: '''simple docstring''' super().__init__( vocab_size=A__ , hidden_size=A__ , num_hidden_layers=A__ , num_attention_heads=A__ , intermediate_size=A__ , hidden_act=A__ , hidden_dropout_prob=A__ , attention_probs_dropout_prob=A__ , max_position_embeddings=A__ , type_vocab_size=A__ , initializer_range=A__ , layer_norm_eps=A__ , pad_token_id=A__ , bos_token_id=A__ , eos_token_id=A__ , **A__ , ) a__ : List[str] = max_ad_position_embeddings a__ : Optional[Any] = coordinate_size a__ : Optional[int] = shape_size a__ : Dict = has_relative_attention_bias a__ : Any = rel_pos_bins a__ : Optional[Any] = max_rel_pos a__ : int = has_spatial_attention_bias a__ : Optional[int] = rel_ad_pos_bins a__ : List[str] = max_rel_ad_pos a__ : Dict = text_embed a__ : str = visual_embed a__ : str = input_size a__ : str = num_channels a__ : Optional[Any] = patch_size a__ : List[Any] = classifier_dropout class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = version.parse("1.12" ) @property def __lowerCAmelCase ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) else: return OrderedDict( [ ('''input_ids''', {0: '''batch''', 1: '''sequence'''}), ('''bbox''', {0: '''batch''', 1: '''sequence'''}), ('''attention_mask''', {0: '''batch''', 1: '''sequence'''}), ('''pixel_values''', {0: '''batch''', 1: '''num_channels'''}), ] ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> float: '''simple docstring''' return 1E-5 @property def __lowerCAmelCase ( self : Union[str, Any] ) -> int: '''simple docstring''' return 1_2 def __lowerCAmelCase ( self : Union[str, Any] , A__ : "ProcessorMixin" , A__ : int = -1 , A__ : int = -1 , A__ : bool = False , A__ : Optional["TensorType"] = None , A__ : int = 3 , A__ : int = 4_0 , A__ : int = 4_0 , ) -> Mapping[str, Any]: '''simple docstring''' setattr(processor.image_processor , '''apply_ocr''' , A__ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX a__ : Optional[Any] = compute_effective_axis_dimension( A__ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX a__ : Tuple = processor.tokenizer.num_special_tokens_to_add(A__ ) a__ : Any = compute_effective_axis_dimension( A__ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=A__ ) # Generate dummy inputs according to compute batch and sequence a__ : str = [[''' '''.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes a__ : Tuple = [[[4_8, 8_4, 7_3, 1_2_8]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) a__ : Union[str, Any] = self._generate_dummy_images(A__ , A__ , A__ , A__ ) a__ : str = dict( processor( A__ , text=A__ , boxes=A__ , return_tensors=A__ , ) ) return inputs
688
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __a ( lowerCAmelCase__ : Dict ): a__ , a__ : int = image.size a__ , a__ : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 a__ : Tuple = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) a__ : List[Any] = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 255.0 a__ : Any = image[None].transpose(0 , 3 , 1 , 2 ) a__ : Dict = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , A__ : VQModel , A__ : UNetaDModel , A__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> str: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : List[str] , A__ : Union[torch.Tensor, PIL.Image.Image] = None , A__ : Optional[int] = 1 , A__ : Optional[int] = 1_0_0 , A__ : Optional[float] = 0.0 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' if isinstance(A__ , PIL.Image.Image ): a__ : List[Any] = 1 elif isinstance(A__ , torch.Tensor ): a__ : List[str] = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(A__ )}' ) if isinstance(A__ , PIL.Image.Image ): a__ : Union[str, Any] = preprocess(A__ ) a__ , a__ : Dict = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image a__ : Optional[int] = (batch_size, self.unet.config.in_channels // 2, height, width) a__ : Optional[int] = next(self.unet.parameters() ).dtype a__ : List[str] = randn_tensor(A__ , generator=A__ , device=self.device , dtype=A__ ) a__ : Any = image.to(device=self.device , dtype=A__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(A__ , device=self.device ) a__ : int = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler a__ : str = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a__ : Union[str, Any] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a__ : str = {} if accepts_eta: a__ : Dict = eta for t in self.progress_bar(A__ ): # concat latents and low resolution image in the channel dimension. a__ : str = torch.cat([latents, image] , dim=1 ) a__ : Optional[Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual a__ : Union[str, Any] = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VQVAE a__ : List[Any] = self.vqvae.decode(A__ ).sample a__ : List[Any] = torch.clamp(A__ , -1.0 , 1.0 ) a__ : Optional[Any] = image / 2 + 0.5 a__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a__ : Union[str, Any] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' __SCREAMING_SNAKE_CASE = 2_5_6 # Modulus to hash a string __SCREAMING_SNAKE_CASE = 1_0_0_0_0_0_3 def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ): a__ : Any = len(lowerCAmelCase__ ) a__ : Dict = len(lowerCAmelCase__ ) if p_len > t_len: return False a__ : Any = 0 a__ : Optional[Any] = 0 a__ : int = 1 # Calculating the hash of pattern and substring of text for i in range(lowerCAmelCase__ ): a__ : Union[str, Any] = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus a__ : str = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue a__ : Optional[Any] = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash a__ : Dict = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def __a ( ): a__ : Dict = '''abc1abc12''' a__ : Tuple = '''alskfjaldsabc1abc1abc12k23adsfabcabc''' a__ : List[Any] = '''alskfjaldsk23adsfabcabc''' assert rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) and not rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) # Test 2) a__ : List[str] = '''ABABX''' a__ : Optional[Any] = '''ABABZABABYABABX''' assert rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) # Test 3) a__ : Any = '''AAAB''' a__ : Tuple = '''ABAAAAAB''' assert rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) # Test 4) a__ : List[str] = '''abcdabcy''' a__ : str = '''abcxabcdabxabcdabcdabcy''' assert rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) # Test 5) a__ : Optional[Any] = '''Lü''' a__ : str = '''Lüsai''' assert rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) a__ : Any = '''Lue''' assert not rabin_karp(lowerCAmelCase__ , lowerCAmelCase__ ) print('''Success.''' ) if __name__ == "__main__": test_rabin_karp()
688
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # pylint: disable=invalid-name __SCREAMING_SNAKE_CASE = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : str=8 ): a__ : Tuple = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a__ : Union[str, Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Dict , A__ : UNetaDConditionModel , A__ : DDPMScheduler , A__ : VQModel , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules( unet=A__ , scheduler=A__ , movq=A__ , ) a__ : Union[str, Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] , A__ : List[str] , A__ : Optional[Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if latents is None: a__ : List[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__ : int = latents.to(A__ ) a__ : Tuple = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : Union[str, Any] , A__ : int=0 ) -> str: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a__ : Union[str, Any] = torch.device(F'cuda:{gpu_id}' ) a__ : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A__ , A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple=0 ) -> Dict: '''simple docstring''' if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) a__ : int = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=A__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a__ : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: a__ , a__ : List[str] = cpu_offload_with_hook(A__ , A__ , prev_module_hook=A__ ) # We'll offload the last model manually. a__ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.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 @torch.no_grad() @replace_example_docstring(A__ ) def __call__( self : Any , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : torch.FloatTensor , A__ : int = 5_1_2 , A__ : int = 5_1_2 , A__ : int = 1_0_0 , A__ : float = 4.0 , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> str: '''simple docstring''' a__ : Optional[Any] = self._execution_device a__ : List[str] = guidance_scale > 1.0 if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : Optional[int] = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) a__ : Union[str, Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a__ : Tuple = image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = negative_image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = hint.repeat_interleave(A__ , dim=0 ) a__ : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) a__ : Tuple = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) self.scheduler.set_timesteps(A__ , device=A__ ) a__ : int = self.scheduler.timesteps a__ : str = self.movq.config.latent_channels a__ , a__ : Optional[int] = downscale_height_and_width(A__ , A__ , self.movq_scale_factor ) # create initial latent a__ : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A__ , A__ , A__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance a__ : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ : List[str] = {'''image_embeds''': image_embeds, '''hint''': hint} a__ : Union[str, Any] = self.unet( sample=A__ , timestep=A__ , encoder_hidden_states=A__ , added_cond_kwargs=A__ , return_dict=A__ , )[0] if do_classifier_free_guidance: a__ , a__ : Dict = noise_pred.split(latents.shape[1] , dim=1 ) a__ , a__ : Dict = noise_pred.chunk(2 ) a__ , a__ : Optional[Any] = variance_pred.chunk(2 ) a__ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a__ , a__ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step( A__ , A__ , A__ , generator=A__ , )[0] # post-processing a__ : Tuple = self.movq.decode(A__ , force_not_quantize=A__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: a__ : Union[str, Any] = image * 0.5 + 0.5 a__ : str = image.clamp(0 , 1 ) a__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ : int = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' import json import sys def __a ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[Any] ): with open(lowerCAmelCase__ , encoding='''utf-8''' ) as f: a__ : Any = json.load(lowerCAmelCase__ ) a__ : Union[str, Any] = ['''<details>''', '''<summary>Show updated benchmarks!</summary>''', ''' '''] for benchmark_name in sorted(lowerCAmelCase__ ): a__ : str = results[benchmark_name] a__ : Optional[int] = benchmark_name.split('''/''' )[-1] output_md.append(F'### Benchmark: {benchmark_file_name}' ) a__ : Optional[Any] = '''| metric |''' a__ : Any = '''|--------|''' a__ : Any = '''| new / old (diff) |''' for metric_name in sorted(lowerCAmelCase__ ): a__ : int = benchmark_res[metric_name] a__ : Optional[int] = metric_vals['''new'''] a__ : Tuple = metric_vals.get('''old''' , lowerCAmelCase__ ) a__ : Optional[int] = metric_vals.get('''diff''' , lowerCAmelCase__ ) a__ : Tuple = F' {new_val:f}' if isinstance(lowerCAmelCase__ , (int, float) ) else '''None''' if old_val is not None: val_str += F' / {old_val:f}' if isinstance(lowerCAmelCase__ , (int, float) ) else "None" if dif_val is not None: val_str += F' ({dif_val:f})' if isinstance(lowerCAmelCase__ , (int, float) ) else "None" title += " " + metric_name + " |" lines += "---|" value += val_str + " |" output_md += [title, lines, value, " "] output_md.append('''</details>''' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.writelines('''\n'''.join(lowerCAmelCase__ ) ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = sys.argv[1] __SCREAMING_SNAKE_CASE = sys.argv[2] format_json_to_md(input_json_file, output_md_file)
688
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } __SCREAMING_SNAKE_CASE = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def __a ( lowerCAmelCase__ : Union[str, Any] ): with open(lowerCAmelCase__ , '''r''' ) as f: a__ : Optional[int] = f.read().splitlines() return [l.strip() for l in lines] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[str] , A__ : int , A__ : Union[str, Any]="<unk>" , A__ : Tuple="<cls>" , A__ : List[Any]="<pad>" , A__ : Optional[int]="<mask>" , A__ : List[Any]="<eos>" , **A__ : Optional[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) a__ : Union[str, Any] = load_vocab_file(A__ ) a__ : int = dict(enumerate(self.all_tokens ) ) a__ : str = {tok: ind for ind, tok in enumerate(self.all_tokens )} a__ : List[Any] = unk_token a__ : Any = cls_token a__ : Any = pad_token a__ : Any = mask_token a__ : Any = eos_token a__ : int = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCAmelCase ( self : Any , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , **A__ : str ) -> List[Any]: '''simple docstring''' return text.split() def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int]=False ) -> Tuple: '''simple docstring''' return len(self._id_to_token ) def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCAmelCase ( self : Any , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : List[Any] , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Tuple = [self.cls_token_id] a__ : Union[str, Any] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCAmelCase ( self : Tuple , A__ : List , A__ : Optional[List] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] a__ : Any = [1] + ([0] * len(A__ )) + [1] if token_ids_a is not None: mask += [0] * len(A__ ) + [1] return mask def __lowerCAmelCase ( self : Any , A__ : Dict , A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = os.path.join(A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(A__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return self.get_vocab_size(with_added_tokens=A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Union[List[str], List[AddedToken]] , A__ : bool = False ) -> int: '''simple docstring''' return super()._add_tokens(A__ , special_tokens=A__ )
688
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import _LazyModule __SCREAMING_SNAKE_CASE = {'processing_wav2vec2_with_lm': ['Wav2Vec2ProcessorWithLM']} if TYPE_CHECKING: from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM else: import sys __SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
688
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ : """simple docstring""" def __init__( self : str ) -> Dict: '''simple docstring''' a__ : List[str] = False def __lowerCAmelCase ( self : Tuple , A__ : Optional[int] , A__ : Optional[Any] , A__ : List[str] , A__ : Tuple ) -> Optional[int]: '''simple docstring''' if not self.initialized: a__ : Optional[Any] = RagRetriever( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : Union[str, Any] = True def __lowerCAmelCase ( self : Tuple ) -> Tuple: '''simple docstring''' self.retriever.index.init_index() def __lowerCAmelCase ( self : List[Any] , A__ : List[Any] , A__ : Optional[int] ) -> List[Any]: '''simple docstring''' a__ , a__ : Optional[Any] = self.retriever._main_retrieve(A__ , A__ ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : Optional[int] , A__ : List[Any] , A__ : List[Any] , A__ : str , A__ : Any=None ) -> Optional[Any]: '''simple docstring''' if index is not None and index.is_initialized() and len(A__ ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : List[str] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(A__ , A__ , A__ , A__ ) for worker in self.retrieval_workers ] ) def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: '''simple docstring''' logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[int] , A__ : int ) -> Dict: '''simple docstring''' if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. a__ : List[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] a__ , a__ : Tuple = ray.get(random_worker.retrieve.remote(A__ , A__ ) ) else: a__ , a__ : int = self._main_retrieve(A__ , A__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[Any] , A__ : Any=None , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return super(A__ , cls ).get_tokenizers(A__ , A__ , **A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[int] , A__ : Union[str, Any] , A__ : Union[str, Any]=None , **A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Dict = kwargs.pop('''config''' , A__ ) or RagConfig.from_pretrained(A__ , **A__ ) a__ : Dict = RagTokenizer.from_pretrained(A__ , config=A__ ) a__ : str = rag_tokenizer.question_encoder a__ : List[str] = rag_tokenizer.generator if indexed_dataset is not None: a__ : List[Any] = '''custom''' a__ : List[Any] = CustomHFIndex(config.retrieval_vector_size , A__ ) else: a__ : Optional[Any] = cls._build_index(A__ ) return cls( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , retrieval_workers=A__ , index=A__ , )
688
1
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : int ): # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: a__ : Any = ksize + 1 a__ : List[Any] = np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(lowerCAmelCase__ ): for x in range(lowerCAmelCase__ ): # distance from center a__ : str = x - ksize // 2 a__ : str = y - ksize // 2 # degree to radiant a__ : Any = theta / 180 * np.pi a__ : Tuple = np.cos(_theta ) a__ : List[str] = np.sin(_theta ) # get kernel x a__ : int = cos_theta * px + sin_theta * py # get kernel y a__ : Optional[int] = -sin_theta * px + cos_theta * py # fill kernel a__ : int = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image __SCREAMING_SNAKE_CASE = imread('../image_data/lena.jpg') # turn image in gray scale value __SCREAMING_SNAKE_CASE = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges __SCREAMING_SNAKE_CASE = np.zeros(gray.shape[:2]) for theta in [0, 3_0, 6_0, 9_0, 1_2_0, 1_5_0]: __SCREAMING_SNAKE_CASE = gabor_filter_kernel(1_0, 8, theta, 1_0, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) __SCREAMING_SNAKE_CASE = out / out.max() * 2_5_5 __SCREAMING_SNAKE_CASE = out.astype(np.uinta) imshow('Original', gray) imshow('Gabor filter with 20x20 mask and 6 directions', out) waitKey(0)
688
'''simple docstring''' def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): a__ : List[str] = len(lowerCAmelCase__ ) a__ : int = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): a__ : Dict = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
688
1
'''simple docstring''' def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : int = 0 ): a__ : List[Any] = length or len(lowerCAmelCase__ ) a__ : Optional[Any] = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: a__ , a__ : Optional[Any] = list_data[i + 1], list_data[i] a__ : int = True return list_data if not swapped else bubble_sort(lowerCAmelCase__ , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
688
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "swin2sr" __UpperCamelCase = { "hidden_size": "embed_dim", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] , A__ : int=6_4 , A__ : List[Any]=1 , A__ : List[Any]=3 , A__ : Any=1_8_0 , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Dict=8 , A__ : Any=2.0 , A__ : Optional[int]=True , A__ : Union[str, Any]=0.0 , A__ : Union[str, Any]=0.0 , A__ : List[str]=0.1 , A__ : Any="gelu" , A__ : Tuple=False , A__ : Optional[int]=0.02 , A__ : List[Any]=1E-5 , A__ : Any=2 , A__ : Union[str, Any]=1.0 , A__ : Dict="1conv" , A__ : Optional[Any]="pixelshuffle" , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : List[str] = image_size a__ : Optional[Any] = patch_size a__ : Dict = num_channels a__ : Optional[int] = embed_dim a__ : int = depths a__ : Optional[int] = len(A__ ) a__ : Dict = num_heads a__ : List[Any] = window_size a__ : Optional[int] = mlp_ratio a__ : Optional[int] = qkv_bias a__ : Union[str, Any] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Union[str, Any] = drop_path_rate a__ : int = hidden_act a__ : int = use_absolute_embeddings a__ : Dict = layer_norm_eps a__ : List[str] = initializer_range a__ : List[Any] = upscale a__ : List[Any] = img_range a__ : Optional[int] = resi_connection a__ : int = upsampler
688
1
'''simple docstring''' import unittest import numpy as np from transformers import AlbertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.albert.modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __init__( self : Union[str, Any] , A__ : str , A__ : List[Any]=1_3 , A__ : Any=7 , A__ : List[str]=True , A__ : Optional[int]=True , A__ : str=True , A__ : int=True , A__ : Optional[Any]=9_9 , A__ : List[Any]=3_2 , A__ : List[Any]=5 , A__ : Optional[Any]=4 , A__ : int=3_7 , A__ : Optional[int]="gelu" , A__ : Optional[int]=0.1 , A__ : str=0.1 , A__ : str=5_1_2 , A__ : Tuple=1_6 , A__ : Optional[int]=2 , A__ : int=0.02 , A__ : int=4 , ) -> List[str]: '''simple docstring''' a__ : List[Any] = parent a__ : Tuple = batch_size a__ : Optional[int] = seq_length a__ : Optional[Any] = is_training a__ : List[str] = use_attention_mask a__ : Optional[Any] = use_token_type_ids a__ : Tuple = use_labels a__ : Optional[int] = vocab_size a__ : Any = hidden_size a__ : Any = num_hidden_layers a__ : Union[str, Any] = num_attention_heads a__ : int = intermediate_size a__ : Tuple = hidden_act a__ : Optional[int] = hidden_dropout_prob a__ : int = attention_probs_dropout_prob a__ : List[str] = max_position_embeddings a__ : int = type_vocab_size a__ : List[Any] = type_sequence_label_size a__ : Optional[Any] = initializer_range a__ : Union[str, Any] = num_choices def __lowerCAmelCase ( self : Tuple ) -> Optional[Any]: '''simple docstring''' a__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Dict = None if self.use_attention_mask: a__ : int = random_attention_mask([self.batch_size, self.seq_length] ) a__ : Any = None if self.use_token_type_ids: a__ : int = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a__ : Union[str, Any] = AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=A__ , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __lowerCAmelCase ( self : int ) -> Optional[Any]: '''simple docstring''' a__ : Dict = self.prepare_config_and_inputs() a__ , a__ , a__ , a__ : Any = config_and_inputs a__ : Dict = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict @require_flax class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = ( ( FlaxAlbertModel, FlaxAlbertForPreTraining, FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertForQuestionAnswering, ) if is_flax_available() else () ) def __lowerCAmelCase ( self : List[Any] ) -> Any: '''simple docstring''' a__ : Dict = FlaxAlbertModelTester(self ) @slow def __lowerCAmelCase ( self : Tuple ) -> Dict: '''simple docstring''' for model_class_name in self.all_model_classes: a__ : Optional[Any] = model_class_name.from_pretrained('''albert-base-v2''' ) a__ : int = model(np.ones((1, 1) ) ) self.assertIsNotNone(A__ ) @require_flax class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = FlaxAlbertModel.from_pretrained('''albert-base-v2''' ) a__ : List[str] = np.array([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]] ) a__ : int = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) a__ : Optional[Any] = model(A__ , attention_mask=A__ )[0] a__ : Optional[Any] = (1, 1_1, 7_6_8) self.assertEqual(output.shape , A__ ) a__ : int = np.array( [[[-0.6_513, 1.5_035, -0.2_766], [-0.6_515, 1.5_046, -0.2_780], [-0.6_512, 1.5_049, -0.2_784]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , A__ , atol=1E-4 ) )
688
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : int = 0 def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[Any] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[Any] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[int] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict() config_dict.pop('''image_processor_type''' ) a__ : Union[str, Any] = CLIPImageProcessor(**A__ ) # save in new folder model_config.save_pretrained(A__ ) config.save_pretrained(A__ ) a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ ) # make sure private variable is not incorrectly saved a__ : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''clip-base is not a local folder and is not a valid model identifier''' ): a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' with self.assertRaises(A__ ): a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoImageProcessor.register(A__ , A__ ) with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[str] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = CustomImageProcessor.from_pretrained(A__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = True try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # If remote code is not set, the default is to use local a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. a__ : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub a__ : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(A__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
688
1
'''simple docstring''' import logging from transformers.configuration_utils import PretrainedConfig __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "masked_bert" def __init__( self : Tuple , A__ : Optional[int]=3_0_5_2_2 , A__ : int=7_6_8 , A__ : Optional[int]=1_2 , A__ : str=1_2 , A__ : Union[str, Any]=3_0_7_2 , A__ : Any="gelu" , A__ : List[str]=0.1 , A__ : Optional[Any]=0.1 , A__ : Optional[int]=5_1_2 , A__ : int=2 , A__ : Any=0.02 , A__ : Any=1E-12 , A__ : Optional[int]=0 , A__ : List[Any]="topK" , A__ : Dict="constant" , A__ : Optional[Any]=0.0 , **A__ : List[Any] , ) -> List[Any]: '''simple docstring''' super().__init__(pad_token_id=A__ , **A__ ) a__ : Tuple = vocab_size a__ : Optional[Any] = hidden_size a__ : Any = num_hidden_layers a__ : Dict = num_attention_heads a__ : Optional[Any] = hidden_act a__ : List[Any] = intermediate_size a__ : Optional[Any] = hidden_dropout_prob a__ : Optional[Any] = attention_probs_dropout_prob a__ : Any = max_position_embeddings a__ : int = type_vocab_size a__ : Any = initializer_range a__ : Any = layer_norm_eps a__ : Any = pruning_method a__ : Dict = mask_init a__ : Any = mask_scale
688
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version __SCREAMING_SNAKE_CASE = get_logger(__name__) class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = "dummy_data" __UpperCamelCase = "datasets" __UpperCamelCase = False def __init__( self : Any , A__ : str , A__ : str , A__ : Union[Version, str] , A__ : Optional[str] = None , A__ : bool = False , A__ : bool = True , A__ : Optional[List[Callable]] = None , ) -> int: '''simple docstring''' a__ : Tuple = 0 a__ : Any = dataset_name a__ : int = cache_dir a__ : str = use_local_dummy_data a__ : List[str] = config # download_callbacks take a single url as input a__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root a__ : str = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general a__ : Optional[Any] = str(A__ ) # to be downloaded a__ : Tuple = None a__ : Tuple = None @property def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' if self._dummy_file is None: a__ : Dict = self.download_dummy_data() return self._dummy_file @property def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('''dummy''' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('''dummy''' , self.version_name ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : int = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) a__ : str = cached_path( A__ , cache_dir=self.cache_dir , extract_compressed_file=A__ , force_extract=A__ ) return os.path.join(A__ , self.dummy_file_name ) @property def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self._bucket_url is None: a__ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) ) return self._bucket_url @property def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , *A__ : int ) -> Union[str, Any]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested a__ : Tuple = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned a__ : Union[str, Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(A__ , A__ ): return self.create_dummy_data_dict(A__ , A__ ) elif isinstance(A__ , (list, tuple) ): return self.create_dummy_data_list(A__ , A__ ) else: return self.create_dummy_data_single(A__ , A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Any , *A__ : int ) -> Any: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Any , A__ : Optional[int] , A__ : Optional[Any] ) -> int: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , *A__ : List[Any] , **A__ : str ) -> Optional[Any]: '''simple docstring''' return path def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' return {} def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[str] ) -> Any: '''simple docstring''' a__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A__ , A__ ): for single_url in single_urls: download_callback(A__ ) else: a__ : Dict = single_urls download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A__ , A__ ): a__ : Optional[int] = [os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) for x in single_urls] else: a__ : Optional[Any] = single_urls a__ : Tuple = os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) a__ : List[str] = value # make sure that values are unique if all(isinstance(A__ , A__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique a__ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : str = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one a__ : Union[str, Any] = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , A__ ) ) for url in data_url ) a__ : Optional[Any] = all( url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): a__ : Dict = [data_url[0]] * len(A__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Optional[int] = os.path.join(A__ , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) ) dummy_data_list.append(A__ ) return dummy_data_list def __lowerCAmelCase ( self : Dict , A__ : Dict , A__ : str ) -> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Union[str, Any] = os.path.join(A__ , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) ) if os.path.exists(A__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' pass def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: '''simple docstring''' pass def __lowerCAmelCase ( self : Any , A__ : Tuple ) -> Any: '''simple docstring''' def _iter_archive_members(A__ : str ): # this preserves the order of the members inside the ZIP archive a__ : Dict = Path(self.dummy_file ).parent a__ : Tuple = path.relative_to(A__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: a__ : Optional[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A__ ) a__ : str = Path(A__ ) a__ : Optional[Any] = _iter_archive_members(A__ ) if self.use_local_dummy_data else path.rglob('''*''' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ): yield file_path.relative_to(A__ ).as_posix(), file_path.open('''rb''' ) def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> Tuple: '''simple docstring''' if not isinstance(A__ , A__ ): a__ : int = [paths] for path in paths: if os.path.isfile(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): return yield path else: for dirpath, dirnames, filenames in os.walk(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): continue dirnames.sort() for filename in sorted(A__ ): if filename.startswith(('''.''', '''__''') ): continue yield os.path.join(A__ , A__ )
688
1
'''simple docstring''' import os import pytest from attr import dataclass __SCREAMING_SNAKE_CASE = 'us-east-1' # defaults region @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = 42 __UpperCamelCase = "arn:aws:iam::558105141721:role/sagemaker_execution_role" __UpperCamelCase = { "task_name": "mnli", "per_device_train_batch_size": 16, "per_device_eval_batch_size": 16, "do_train": True, "do_eval": True, "do_predict": True, "output_dir": "/opt/ml/model", "overwrite_output_dir": True, "max_steps": 500, "save_steps": 5500, } __UpperCamelCase = {**hyperparameters, "max_steps": 1000} @property def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowerCAmelCase ( self : Dict ) -> str: '''simple docstring''' return F'{self.framework}-transfromers-test' @property def __lowerCAmelCase ( self : List[str] ) -> str: '''simple docstring''' return F'./tests/sagemaker/scripts/{self.framework}' @property def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='''class''' ) def __a ( lowerCAmelCase__ : str ): a__ : Union[str, Any] = SageMakerTestEnvironment(framework=request.cls.framework )
688
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = LxmertTokenizer __UpperCamelCase = LxmertTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' super().setUp() a__ : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : int , A__ : int ) -> int: '''simple docstring''' a__ : List[Any] = '''UNwant\u00E9d,running''' a__ : Optional[int] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ : Optional[int] = self.tokenizer_class(self.vocab_file ) a__ : List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [7, 4, 5, 1_0, 8, 9] ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__ : Union[str, Any] = self.get_tokenizer() a__ : Union[str, Any] = self.get_rust_tokenizer() a__ : str = '''I was born in 92000, and this is falsé.''' a__ : Tuple = tokenizer.tokenize(A__ ) a__ : Tuple = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) a__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : str = tokenizer.encode(A__ ) a__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ )
688
1
'''simple docstring''' import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("TEST_SAGEMAKER" , "False" ) ) is not True , reason="Skipping test because should only be run when releasing minor transformers version" , ) @pytest.mark.usefixtures("sm_env" ) @parameterized_class( [ { "framework": "pytorch", "script": "run_glue.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 650, "eval_accuracy": 0.6, "eval_loss": 0.9}, }, { "framework": "tensorflow", "script": "run_tf.py", "model_name_or_path": "distilbert-base-cased", "instance_type": "ml.g4dn.xlarge", "results": {"train_runtime": 600, "eval_accuracy": 0.3, "eval_loss": 0.9}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Any ) -> str: '''simple docstring''' if self.framework == "pytorch": subprocess.run( F'cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'.split() , encoding='''utf-8''' , check=A__ , ) assert hasattr(self , '''env''' ) def __lowerCAmelCase ( self : List[Any] , A__ : Optional[Any]=1 ) -> str: '''simple docstring''' return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F'{self.env.base_job_name}-single' , instance_count=A__ , instance_type=self.instance_type , debugger_hook_config=A__ , hyperparameters={**self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version='''py36''' , ) def __lowerCAmelCase ( self : Optional[int] , A__ : List[Any] ) -> str: '''simple docstring''' TrainingJobAnalytics(A__ ).export_csv(F'{self.env.test_path}/{job_name}_metrics.csv' ) def __lowerCAmelCase ( self : Any ) -> Tuple: '''simple docstring''' a__ : Union[str, Any] = self.create_estimator() # run training estimator.fit() # result dataframe a__ : Optional[int] = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis a__ : Optional[Any] = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) a__ : Optional[int] = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping a__ : int = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 9_9_9_9_9_9 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(F'{estimator.latest_training_job.name}.json' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , A__ )
688
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file a__ : Dict = TapasConfig.from_json_file(lowerCAmelCase__ ) # set absolute/relative position embeddings parameter a__ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": a__ : Optional[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WTQ": # run_task_main.py hparams a__ : List[str] = 4 a__ : Optional[int] = True # hparam_utils.py hparams a__ : List[Any] = 0.664694 a__ : List[Any] = 0.207951 a__ : Union[str, Any] = 0.121194 a__ : Optional[Any] = True a__ : Optional[int] = True a__ : List[str] = False a__ : Union[str, Any] = 0.0352513 a__ : Any = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams a__ : Tuple = 4 a__ : Dict = False # hparam_utils.py hparams a__ : str = 36.4519 a__ : str = 0.903421 a__ : Optional[Any] = 222.088 a__ : Dict = True a__ : Dict = True a__ : Dict = True a__ : str = 0.763141 a__ : List[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "TABFACT": a__ : List[str] = TapasForSequenceClassification(config=lowerCAmelCase__ ) elif task == "MLM": a__ : Tuple = TapasForMaskedLM(config=lowerCAmelCase__ ) elif task == "INTERMEDIATE_PRETRAINING": a__ : List[str] = TapasModel(config=lowerCAmelCase__ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase__ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) a__ : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase__ ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
688
1
'''simple docstring''' import inspect from typing import Callable, List, Optional, Union import torch from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, WhisperForConditionalGeneration, WhisperProcessor, ) from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Union[str, Any] , A__ : WhisperForConditionalGeneration , A__ : WhisperProcessor , A__ : AutoencoderKL , A__ : CLIPTextModel , A__ : CLIPTokenizer , A__ : UNetaDConditionModel , A__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , A__ : StableDiffusionSafetyChecker , A__ : CLIPImageProcessor , ) -> Dict: '''simple docstring''' super().__init__() if safety_checker is None: logger.warning( F'You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure' ''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered''' ''' results in services or applications open to the public. Both the diffusers team and Hugging Face''' ''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling''' ''' it only for use-cases that involve analyzing network behavior or auditing its results. For more''' ''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''' ) self.register_modules( speech_model=A__ , speech_processor=A__ , vae=A__ , text_encoder=A__ , tokenizer=A__ , unet=A__ , scheduler=A__ , feature_extractor=A__ , ) def __lowerCAmelCase ( self : str , A__ : Optional[Union[str, int]] = "auto" ) -> Dict: '''simple docstring''' if slice_size == "auto": a__ : int = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(A__ ) def __lowerCAmelCase ( self : str ) -> Dict: '''simple docstring''' self.enable_attention_slicing(A__ ) @torch.no_grad() def __call__( self : List[Any] , A__ : int , A__ : List[str]=1_6_0_0_0 , A__ : int = 5_1_2 , A__ : int = 5_1_2 , A__ : int = 5_0 , A__ : float = 7.5 , A__ : Optional[Union[str, List[str]]] = None , A__ : Optional[int] = 1 , A__ : float = 0.0 , A__ : Optional[torch.Generator] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , A__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , A__ : int = 1 , **A__ : Any , ) -> Any: '''simple docstring''' a__ : List[Any] = self.speech_processor.feature_extractor( A__ , return_tensors='''pt''' , sampling_rate=A__ ).input_features.to(self.device ) a__ : List[Any] = self.speech_model.generate(A__ , max_length=4_8_0_0_0_0 ) a__ : List[str] = self.speech_processor.tokenizer.batch_decode(A__ , skip_special_tokens=A__ , normalize=A__ )[ 0 ] if isinstance(A__ , A__ ): a__ : int = 1 elif isinstance(A__ , A__ ): a__ : Optional[Any] = len(A__ ) else: raise ValueError(F'`prompt` has to be of type `str` or `list` but is {type(A__ )}' ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F'`height` and `width` have to be divisible by 8 but are {height} and {width}.' ) if (callback_steps is None) or ( callback_steps is not None and (not isinstance(A__ , A__ ) or callback_steps <= 0) ): raise ValueError( F'`callback_steps` has to be a positive integer but is {callback_steps} of type' F' {type(A__ )}.' ) # get prompt text embeddings a__ : Optional[int] = self.tokenizer( A__ , padding='''max_length''' , max_length=self.tokenizer.model_max_length , return_tensors='''pt''' , ) a__ : List[Any] = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: a__ : Optional[Any] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( '''The following part of your input was truncated because CLIP can only handle sequences up to''' F' {self.tokenizer.model_max_length} tokens: {removed_text}' ) a__ : Union[str, Any] = text_input_ids[:, : self.tokenizer.model_max_length] a__ : Dict = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method a__ , a__ , a__ : str = text_embeddings.shape a__ : str = text_embeddings.repeat(1 , A__ , 1 ) a__ : Any = text_embeddings.view(bs_embed * num_images_per_prompt , A__ , -1 ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. a__ : List[str] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: a__ : List[str] if negative_prompt is None: a__ : Dict = [''''''] * batch_size elif type(A__ ) is not type(A__ ): raise TypeError( F'`negative_prompt` should be the same type to `prompt`, but got {type(A__ )} !=' F' {type(A__ )}.' ) elif isinstance(A__ , A__ ): a__ : int = [negative_prompt] elif batch_size != len(A__ ): raise ValueError( F'`negative_prompt`: {negative_prompt} has batch size {len(A__ )}, but `prompt`:' F' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches' ''' the batch size of `prompt`.''' ) else: a__ : List[str] = negative_prompt a__ : Optional[Any] = text_input_ids.shape[-1] a__ : int = self.tokenizer( A__ , padding='''max_length''' , max_length=A__ , truncation=A__ , return_tensors='''pt''' , ) a__ : Any = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method a__ : Optional[int] = uncond_embeddings.shape[1] a__ : str = uncond_embeddings.repeat(1 , A__ , 1 ) a__ : Tuple = uncond_embeddings.view(batch_size * num_images_per_prompt , A__ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes a__ : Optional[Any] = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. a__ : Dict = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) a__ : Union[str, Any] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps a__ : str = torch.randn(A__ , generator=A__ , device='''cpu''' , dtype=A__ ).to( self.device ) else: a__ : List[str] = torch.randn(A__ , generator=A__ , device=self.device , dtype=A__ ) else: if latents.shape != latents_shape: raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {latents_shape}' ) a__ : Optional[int] = latents.to(self.device ) # set timesteps self.scheduler.set_timesteps(A__ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand a__ : Optional[Any] = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler a__ : Tuple = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a__ : Tuple = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a__ : Union[str, Any] = {} if accepts_eta: a__ : List[Any] = eta for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance a__ : str = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ : Dict = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual a__ : Optional[int] = self.unet(A__ , A__ , encoder_hidden_states=A__ ).sample # perform guidance if do_classifier_free_guidance: a__ , a__ : List[str] = noise_pred.chunk(2 ) a__ : Optional[int] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 a__ : str = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(A__ , A__ , A__ ) a__ : List[str] = 1 / 0.18_215 * latents a__ : Optional[int] = self.vae.decode(A__ ).sample a__ : str = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 a__ : int = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ : Dict = self.numpy_to_pil(A__ ) if not return_dict: return image return StableDiffusionPipelineOutput(images=A__ , nsfw_content_detected=A__ )
688
'''simple docstring''' 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_fnet import FNetTokenizer else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } __SCREAMING_SNAKE_CASE = { 'google/fnet-base': 5_1_2, 'google/fnet-large': 5_1_2, } __SCREAMING_SNAKE_CASE = '▁' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "token_type_ids"] __UpperCamelCase = FNetTokenizer def __init__( self : Any , A__ : Any=None , A__ : int=None , A__ : List[str]=False , A__ : int=True , A__ : str=True , A__ : List[Any]="<unk>" , A__ : Dict="[SEP]" , A__ : List[str]="<pad>" , A__ : Union[str, Any]="[CLS]" , A__ : Dict="[MASK]" , **A__ : Tuple , ) -> List[str]: '''simple docstring''' a__ : Optional[int] = ( AddedToken(A__ , lstrip=A__ , rstrip=A__ , normalized=A__ ) if isinstance(A__ , A__ ) else mask_token ) super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , **A__ , ) a__ : Optional[Any] = do_lower_case a__ : Dict = remove_space a__ : List[Any] = keep_accents a__ : Optional[Any] = vocab_file a__ : Any = False if not self.vocab_file else True def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : List[Any] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Dict = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : Tuple , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(A__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return a__ : Union[str, Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ): copyfile(self.vocab_file , A__ ) return (out_vocab_file,)
688
1
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = DiTPipeline __UpperCamelCase = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS __UpperCamelCase = PipelineTesterMixin.required_optional_params - { "latents", "num_images_per_prompt", "callback", "callback_steps", } __UpperCamelCase = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS __UpperCamelCase = False def __lowerCAmelCase ( self : str ) -> Any: '''simple docstring''' torch.manual_seed(0 ) a__ : Optional[int] = TransformeraDModel( sample_size=1_6 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=A__ , activation_fn='''gelu-approximate''' , num_embeds_ada_norm=1_0_0_0 , norm_type='''ada_norm_zero''' , norm_elementwise_affine=A__ , ) a__ : Dict = AutoencoderKL() a__ : Optional[int] = DDIMScheduler() a__ : int = {'''transformer''': transformer.eval(), '''vae''': vae.eval(), '''scheduler''': scheduler} return components def __lowerCAmelCase ( self : List[Any] , A__ : Union[str, Any] , A__ : int=0 ) -> Union[str, Any]: '''simple docstring''' if str(A__ ).startswith('''mps''' ): a__ : Dict = torch.manual_seed(A__ ) else: a__ : List[Any] = torch.Generator(device=A__ ).manual_seed(A__ ) a__ : List[Any] = { '''class_labels''': [1], '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self : List[str] ) -> Dict: '''simple docstring''' a__ : Any = '''cpu''' a__ : Dict = self.get_dummy_components() a__ : List[str] = self.pipeline_class(**A__ ) pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) a__ : Dict = self.get_dummy_inputs(A__ ) a__ : Any = pipe(**A__ ).images a__ : List[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 1_6, 1_6, 3) ) a__ : Union[str, Any] = np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457] ) a__ : Union[str, Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(A__ , 1E-3 ) def __lowerCAmelCase ( self : Optional[int] ) -> Tuple: '''simple docstring''' self._test_inference_batch_single_identical(relax_max_difference=A__ , expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] = torch.manual_seed(0 ) a__ : int = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-256''' ) pipe.to('''cuda''' ) a__ : str = ['''vase''', '''umbrella''', '''white shark''', '''white wolf'''] a__ : Union[str, Any] = pipe.get_label_ids(A__ ) a__ : Dict = pipe(A__ , generator=A__ , num_inference_steps=4_0 , output_type='''np''' ).images for word, image in zip(A__ , A__ ): a__ : int = load_numpy( F'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy' ) assert np.abs((expected_image - image).max() ) < 1E-2 def __lowerCAmelCase ( self : int ) -> Optional[Any]: '''simple docstring''' a__ : Optional[int] = DiTPipeline.from_pretrained('''facebook/DiT-XL-2-512''' ) a__ : List[str] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to('''cuda''' ) a__ : Union[str, Any] = ['''vase''', '''umbrella'''] a__ : Optional[Any] = pipe.get_label_ids(A__ ) a__ : List[str] = torch.manual_seed(0 ) a__ : Tuple = pipe(A__ , generator=A__ , num_inference_steps=2_5 , output_type='''np''' ).images for word, image in zip(A__ , A__ ): a__ : Dict = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' F'/dit/{word}_512.npy' ) assert np.abs((expected_image - image).max() ) < 1E-1
688
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { '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' ), }, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': 5_1_2, 'distilbert-base-uncased-distilled-squad': 5_1_2, 'distilbert-base-cased': 5_1_2, 'distilbert-base-cased-distilled-squad': 5_1_2, 'distilbert-base-german-cased': 5_1_2, 'distilbert-base-multilingual-cased': 5_1_2, } __SCREAMING_SNAKE_CASE = { '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 lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = DistilBertTokenizer def __init__( self : str , A__ : Optional[Any]=None , A__ : Any=None , A__ : Tuple=True , A__ : List[Any]="[UNK]" , A__ : List[str]="[SEP]" , A__ : Tuple="[PAD]" , A__ : Optional[int]="[CLS]" , A__ : Union[str, Any]="[MASK]" , A__ : List[str]=True , A__ : Any=None , **A__ : int , ) -> str: '''simple docstring''' super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , tokenize_chinese_chars=A__ , strip_accents=A__ , **A__ , ) a__ : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , A__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , A__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , A__ ) != tokenize_chinese_chars ): a__ : int = getattr(A__ , normalizer_state.pop('''type''' ) ) a__ : List[Any] = do_lower_case a__ : str = strip_accents a__ : List[str] = tokenize_chinese_chars a__ : Dict = normalizer_class(**A__ ) a__ : List[Any] = do_lower_case def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Dict=None ) -> List[str]: '''simple docstring''' a__ : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : int , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : List[str] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : str , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' a__ : int = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
688
1
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = ProphetNetTokenizer __UpperCamelCase = False def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' super().setUp() a__ : List[str] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : Dict , A__ : Any ) -> Optional[int]: '''simple docstring''' a__ : int = '''UNwant\u00E9d,running''' a__ : str = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : Optional[Any] ) -> str: '''simple docstring''' a__ : str = self.tokenizer_class(self.vocab_file ) a__ : Union[str, Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [9, 6, 7, 1_2, 1_0, 1_1] ) def __lowerCAmelCase ( self : List[str] ) -> str: '''simple docstring''' a__ : Tuple = BasicTokenizer() self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] ) def __lowerCAmelCase ( self : Dict ) -> str: '''simple docstring''' a__ : Optional[int] = BasicTokenizer(do_lower_case=A__ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' a__ : Dict = BasicTokenizer(do_lower_case=A__ , strip_accents=A__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] ) def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' a__ : List[Any] = BasicTokenizer(do_lower_case=A__ , strip_accents=A__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : Optional[int] ) -> str: '''simple docstring''' a__ : List[str] = BasicTokenizer(do_lower_case=A__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] ) def __lowerCAmelCase ( self : List[str] ) -> Any: '''simple docstring''' a__ : Union[str, Any] = BasicTokenizer(do_lower_case=A__ ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Tuple ) -> List[Any]: '''simple docstring''' a__ : Tuple = BasicTokenizer(do_lower_case=A__ , strip_accents=A__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : int ) -> Union[str, Any]: '''simple docstring''' a__ : List[Any] = BasicTokenizer(do_lower_case=A__ , strip_accents=A__ ) self.assertListEqual( tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def __lowerCAmelCase ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' a__ : Dict = BasicTokenizer(do_lower_case=A__ , never_split=['''[UNK]'''] ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] ) def __lowerCAmelCase ( self : Optional[int] ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing'''] a__ : Any = {} for i, token in enumerate(A__ ): a__ : Union[str, Any] = i a__ : List[str] = WordpieceTokenizer(vocab=A__ , unk_token='''[UNK]''' ) self.assertListEqual(tokenizer.tokenize('''''' ) , [] ) self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] ) @require_torch def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : int = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a__ : Union[str, Any] = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] a__ : List[Any] = [1_0_3_7, 2_1_4_6, 2_0_4_2_3, 2_0_0_5, 7_6_8_0, 7_8_4_9, 3_9_8_9, 1_0_1_2, 1_0_2] a__ : Optional[int] = tokenizer(A__ , padding=A__ , return_tensors='''pt''' ) self.assertIsInstance(A__ , A__ ) a__ : Optional[Any] = list(batch.input_ids.numpy()[0] ) self.assertListEqual(A__ , A__ ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def __lowerCAmelCase ( self : Any ) -> List[Any]: '''simple docstring''' self.assertTrue(_is_whitespace(''' ''' ) ) self.assertTrue(_is_whitespace('''\t''' ) ) self.assertTrue(_is_whitespace('''\r''' ) ) self.assertTrue(_is_whitespace('''\n''' ) ) self.assertTrue(_is_whitespace('''\u00A0''' ) ) self.assertFalse(_is_whitespace('''A''' ) ) self.assertFalse(_is_whitespace('''-''' ) ) def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' self.assertTrue(_is_control('''\u0005''' ) ) self.assertFalse(_is_control('''A''' ) ) self.assertFalse(_is_control(''' ''' ) ) self.assertFalse(_is_control('''\t''' ) ) self.assertFalse(_is_control('''\r''' ) ) def __lowerCAmelCase ( self : List[str] ) -> Optional[int]: '''simple docstring''' self.assertTrue(_is_punctuation('''-''' ) ) self.assertTrue(_is_punctuation('''$''' ) ) self.assertTrue(_is_punctuation('''`''' ) ) self.assertTrue(_is_punctuation('''.''' ) ) self.assertFalse(_is_punctuation('''A''' ) ) self.assertFalse(_is_punctuation(''' ''' ) ) @slow def __lowerCAmelCase ( self : str ) -> Tuple: '''simple docstring''' a__ : Union[str, Any] = self.tokenizer_class.from_pretrained('''microsoft/prophetnet-large-uncased''' ) a__ : Optional[int] = tokenizer.encode('''sequence builders''' , add_special_tokens=A__ ) a__ : int = tokenizer.encode('''multi-sequence build''' , add_special_tokens=A__ ) a__ : List[str] = tokenizer.build_inputs_with_special_tokens(A__ ) a__ : List[Any] = tokenizer.build_inputs_with_special_tokens(A__ , A__ ) assert encoded_sentence == text + [1_0_2] assert encoded_pair == text + [1_0_2] + text_a + [1_0_2]
688
'''simple docstring''' from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __SCREAMING_SNAKE_CASE = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right __SCREAMING_SNAKE_CASE = tuple[int, int] class lowerCAmelCase__ : """simple docstring""" def __init__( self : str , A__ : int , A__ : int , A__ : int , A__ : int , A__ : int , A__ : Node | None , ) -> None: '''simple docstring''' a__ : Optional[int] = pos_x a__ : str = pos_y a__ : Optional[int] = (pos_y, pos_x) a__ : List[str] = goal_x a__ : Any = goal_y a__ : Any = g_cost a__ : Optional[int] = parent a__ : Union[str, Any] = self.calculate_heuristic() a__ : List[Any] = self.g_cost + self.h_cost def __lowerCAmelCase ( self : Union[str, Any] ) -> float: '''simple docstring''' a__ : List[str] = self.pos_x - self.goal_x a__ : List[str] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(A__ ) + abs(A__ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : List[Any] , A__ : Node ) -> bool: '''simple docstring''' return self.f_cost < other.f_cost class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] , A__ : TPosition , A__ : TPosition ) -> Optional[Any]: '''simple docstring''' a__ : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , A__ ) a__ : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , A__ ) a__ : Dict = [self.start] a__ : list[Node] = [] a__ : str = False def __lowerCAmelCase ( self : List[str] ) -> list[TPosition]: '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() a__ : Dict = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(A__ ) self.closed_nodes.append(A__ ) a__ : List[Any] = self.get_successors(A__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[int] = self.open_nodes.pop(self.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(A__ ) else: self.open_nodes.append(A__ ) return [self.start.pos] def __lowerCAmelCase ( self : Optional[Any] , A__ : Node ) -> list[Node]: '''simple docstring''' a__ : Optional[int] = [] for action in delta: a__ : List[Any] = parent.pos_x + action[1] a__ : Tuple = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(A__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( A__ , A__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , A__ , ) ) return successors def __lowerCAmelCase ( self : List[Any] , A__ : Node | None ) -> list[TPosition]: '''simple docstring''' a__ : Union[str, Any] = node a__ : Optional[Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) a__ : Any = current_node.parent path.reverse() return path class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , A__ : TPosition , A__ : TPosition ) -> None: '''simple docstring''' a__ : str = AStar(A__ , A__ ) a__ : Optional[int] = AStar(A__ , A__ ) a__ : List[str] = False def __lowerCAmelCase ( self : Tuple ) -> list[TPosition]: '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() a__ : int = self.fwd_astar.open_nodes.pop(0 ) a__ : List[Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( A__ , A__ ) self.fwd_astar.closed_nodes.append(A__ ) self.bwd_astar.closed_nodes.append(A__ ) a__ : Tuple = current_bwd_node a__ : Optional[int] = current_fwd_node a__ : Optional[int] = { self.fwd_astar: self.fwd_astar.get_successors(A__ ), self.bwd_astar: self.bwd_astar.get_successors(A__ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[Any] = astar.open_nodes.pop( astar.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(A__ ) else: astar.open_nodes.append(A__ ) return [self.fwd_astar.start.pos] def __lowerCAmelCase ( self : List[str] , A__ : Node , A__ : Node ) -> list[TPosition]: '''simple docstring''' a__ : str = self.fwd_astar.retrace_path(A__ ) a__ : List[str] = self.bwd_astar.retrace_path(A__ ) bwd_path.pop() bwd_path.reverse() a__ : Optional[int] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] __SCREAMING_SNAKE_CASE = (0, 0) __SCREAMING_SNAKE_CASE = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = AStar(init, goal) __SCREAMING_SNAKE_CASE = a_star.search() __SCREAMING_SNAKE_CASE = time.time() - start_time print(f'AStar execution time = {end_time:f} seconds') __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = BidirectionalAStar(init, goal) __SCREAMING_SNAKE_CASE = time.time() - bd_start_time print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
688
1
'''simple docstring''' import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def __a ( lowerCAmelCase__ : Any ): a__ : List[str] = torch.exp(lowerCAmelCase__ ) a__ : Optional[int] = torch.sum(lowerCAmelCase__ , dim=1 ) # sum of exp(x_i) a__ : List[Any] = torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i) return torch.log(lowerCAmelCase__ ) - B / A class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : Any , A__ : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' super().__init__() a__ : Any = config.output_attentions a__ : Dict = config.output_hidden_states a__ : Optional[Any] = nn.ModuleList([BertLayer(A__ ) for _ in range(config.num_hidden_layers )] ) a__ : Dict = nn.ModuleList([BertHighway(A__ ) for _ in range(config.num_hidden_layers )] ) a__ : Any = [-1 for _ in range(config.num_hidden_layers )] def __lowerCAmelCase ( self : List[str] , A__ : Any ) -> Optional[Any]: '''simple docstring''' if (type(A__ ) is float) or (type(A__ ) is int): for i in range(len(self.early_exit_entropy ) ): a__ : Union[str, Any] = x else: a__ : Tuple = x def __lowerCAmelCase ( self : Dict , A__ : Dict ) -> Optional[Any]: '''simple docstring''' a__ : Tuple = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def __lowerCAmelCase ( self : Dict , A__ : Optional[int] , A__ : Union[str, Any]=None , A__ : Any=None , A__ : Union[str, Any]=None , A__ : Optional[Any]=None , ) -> Optional[Any]: '''simple docstring''' a__ : Optional[Any] = () a__ : Tuple = () a__ : Union[str, Any] = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: a__ : Dict = all_hidden_states + (hidden_states,) a__ : List[Any] = layer_module( A__ , A__ , head_mask[i] , A__ , A__ ) a__ : Optional[int] = layer_outputs[0] if self.output_attentions: a__ : List[Any] = all_attentions + (layer_outputs[1],) a__ : Any = (hidden_states,) if self.output_hidden_states: a__ : Tuple = current_outputs + (all_hidden_states,) if self.output_attentions: a__ : Optional[Any] = current_outputs + (all_attentions,) a__ : Union[str, Any] = self.highway[i](A__ ) # logits, pooled_output if not self.training: a__ : List[Any] = highway_exit[0] a__ : int = entropy(A__ ) a__ : str = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy a__ : str = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: a__ : Any = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(A__ , i + 1 ) else: a__ : int = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: a__ : Tuple = all_hidden_states + (hidden_states,) a__ : List[Any] = (hidden_states,) if self.output_hidden_states: a__ : List[str] = outputs + (all_hidden_states,) if self.output_attentions: a__ : Optional[Any] = outputs + (all_attentions,) a__ : List[Any] = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( "The Bert Model transformer with early exiting (DeeBERT). " , lowerCAmelCase_ , ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : Any ) -> List[str]: '''simple docstring''' super().__init__(A__ ) a__ : int = config a__ : int = BertEmbeddings(A__ ) a__ : Optional[Any] = DeeBertEncoder(A__ ) a__ : Union[str, Any] = BertPooler(A__ ) self.init_weights() def __lowerCAmelCase ( self : List[Any] ) -> int: '''simple docstring''' self.encoder.init_highway_pooler(self.pooler ) def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' return self.embeddings.word_embeddings def __lowerCAmelCase ( self : List[Any] , A__ : Tuple ) -> Any: '''simple docstring''' a__ : int = value def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(A__ ) @add_start_docstrings_to_model_forward(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int]=None , A__ : Optional[Any]=None , A__ : Any=None , A__ : str=None , A__ : Optional[int]=None , A__ : Union[str, Any]=None , A__ : List[str]=None , A__ : str=None , ) -> Any: '''simple docstring''' if input_ids is not None and inputs_embeds is not None: raise ValueError('''You cannot specify both input_ids and inputs_embeds at the same time''' ) elif input_ids is not None: a__ : Optional[Any] = input_ids.size() elif inputs_embeds is not None: a__ : Optional[Any] = inputs_embeds.size()[:-1] else: raise ValueError('''You have to specify either input_ids or inputs_embeds''' ) a__ : Tuple = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: a__ : Tuple = torch.ones(A__ , device=A__ ) if encoder_attention_mask is None: a__ : Tuple = torch.ones(A__ , device=A__ ) if token_type_ids is None: a__ : Dict = torch.zeros(A__ , dtype=torch.long , device=A__ ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. a__ : torch.Tensor = self.get_extended_attention_mask(A__ , A__ , A__ ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: a__ : Any = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: a__ : str = encoder_attention_mask[:, None, None, :] a__ : Optional[Any] = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility a__ : Union[str, Any] = (1.0 - encoder_extended_attention_mask) * -10_000.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] a__ : Optional[int] = self.get_head_mask(A__ , self.config.num_hidden_layers ) a__ : List[Any] = self.embeddings( input_ids=A__ , position_ids=A__ , token_type_ids=A__ , inputs_embeds=A__ ) a__ : List[str] = self.encoder( A__ , attention_mask=A__ , head_mask=A__ , encoder_hidden_states=A__ , encoder_attention_mask=A__ , ) a__ : Optional[int] = encoder_outputs[0] a__ : int = self.pooler(A__ ) a__ : Optional[Any] = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : List[Any] , A__ : Dict ) -> Tuple: '''simple docstring''' a__ : Dict = message a__ : Dict = exit_layer # start from 1! class lowerCAmelCase__ ( nn.Module ): """simple docstring""" def __init__( self : Optional[int] , A__ : List[Any] ) -> Optional[int]: '''simple docstring''' super().__init__() a__ : Dict = BertPooler(A__ ) a__ : List[Any] = nn.Dropout(config.hidden_dropout_prob ) a__ : Optional[Any] = nn.Linear(config.hidden_size , config.num_labels ) def __lowerCAmelCase ( self : List[Any] , A__ : Optional[Any] ) -> str: '''simple docstring''' a__ : List[str] = encoder_outputs[0] a__ : int = self.pooler(A__ ) # "return" pooler_output # BertModel a__ : Any = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification a__ : List[Any] = bmodel_output[1] a__ : str = self.dropout(A__ ) a__ : int = self.classifier(A__ ) return logits, pooled_output @add_start_docstrings( "Bert Model (with early exiting - DeeBERT) with a classifier on top,\n also takes care of multi-layer training. " , lowerCAmelCase_ , ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Union[str, Any] , A__ : Optional[Any] ) -> Dict: '''simple docstring''' super().__init__(A__ ) a__ : Tuple = config.num_labels a__ : List[str] = config.num_hidden_layers a__ : int = DeeBertModel(A__ ) a__ : int = nn.Dropout(config.hidden_dropout_prob ) a__ : List[str] = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(A__ ) def __lowerCAmelCase ( self : Any , A__ : Optional[Any]=None , A__ : Optional[int]=None , A__ : Optional[int]=None , A__ : Tuple=None , A__ : Optional[int]=None , A__ : Tuple=None , A__ : Any=None , A__ : List[str]=-1 , A__ : List[str]=False , ) -> List[Any]: '''simple docstring''' a__ : str = self.num_layers try: a__ : int = self.bert( A__ , attention_mask=A__ , token_type_ids=A__ , position_ids=A__ , head_mask=A__ , inputs_embeds=A__ , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits a__ : Optional[int] = outputs[1] a__ : List[str] = self.dropout(A__ ) a__ : int = self.classifier(A__ ) a__ : Any = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: a__ : Optional[int] = e.message a__ : Tuple = e.exit_layer a__ : List[Any] = outputs[0] if not self.training: a__ : Dict = entropy(A__ ) a__ : List[str] = [] a__ : Dict = [] if labels is not None: if self.num_labels == 1: # We are doing regression a__ : Dict = MSELoss() a__ : List[Any] = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: a__ : Union[str, Any] = CrossEntropyLoss() a__ : Optional[int] = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits a__ : Tuple = [] for highway_exit in outputs[-1]: a__ : int = highway_exit[0] if not self.training: highway_logits_all.append(A__ ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression a__ : List[str] = MSELoss() a__ : Optional[Any] = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: a__ : Tuple = CrossEntropyLoss() a__ : List[str] = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(A__ ) if train_highway: a__ : str = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: a__ : Optional[int] = (loss,) + outputs if not self.training: a__ : Any = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: a__ : Tuple = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
688
'''simple docstring''' import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] ): # Construct model if gpta_config_file == "": a__ : Union[str, Any] = GPTaConfig() else: a__ : Dict = GPTaConfig.from_json_file(lowerCAmelCase__ ) a__ : Optional[int] = GPTaModel(lowerCAmelCase__ ) # Load weights from numpy load_tf_weights_in_gpta(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model a__ : int = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME a__ : Union[str, Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , lowerCAmelCase__ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--gpt2_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
688
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } __SCREAMING_SNAKE_CASE = { 'YituTech/conv-bert-base': 5_1_2, 'YituTech/conv-bert-medium-small': 5_1_2, 'YituTech/conv-bert-small': 5_1_2, } __SCREAMING_SNAKE_CASE = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ConvBertTokenizer def __init__( self : List[str] , A__ : Optional[int]=None , A__ : str=None , A__ : Union[str, Any]=True , A__ : Any="[UNK]" , A__ : Optional[int]="[SEP]" , A__ : Union[str, Any]="[PAD]" , A__ : Any="[CLS]" , A__ : List[Any]="[MASK]" , A__ : List[str]=True , A__ : Any=None , **A__ : Union[str, Any] , ) -> List[str]: '''simple docstring''' super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , tokenize_chinese_chars=A__ , strip_accents=A__ , **A__ , ) a__ : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , A__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , A__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , A__ ) != tokenize_chinese_chars ): a__ : Any = getattr(A__ , normalizer_state.pop('''type''' ) ) a__ : int = do_lower_case a__ : Optional[Any] = strip_accents a__ : Optional[Any] = tokenize_chinese_chars a__ : Dict = normalizer_class(**A__ ) a__ : Optional[Any] = do_lower_case def __lowerCAmelCase ( self : Optional[Any] , A__ : Any , A__ : Union[str, Any]=None ) -> List[str]: '''simple docstring''' a__ : Optional[int] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : Any , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : Optional[Any] , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' a__ : Optional[int] = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
688
'''simple docstring''' import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } __SCREAMING_SNAKE_CASE = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } __SCREAMING_SNAKE_CASE = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: __SCREAMING_SNAKE_CASE = reader.read() __SCREAMING_SNAKE_CASE = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): __SCREAMING_SNAKE_CASE = UNetaDModel(**config) else: __SCREAMING_SNAKE_CASE = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel __SCREAMING_SNAKE_CASE = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) __SCREAMING_SNAKE_CASE = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: __SCREAMING_SNAKE_CASE = config[key] del config[key] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['down_block_types']] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: __SCREAMING_SNAKE_CASE = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) __SCREAMING_SNAKE_CASE = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue __SCREAMING_SNAKE_CASE = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: __SCREAMING_SNAKE_CASE = param_value __SCREAMING_SNAKE_CASE = True if not has_changed: __SCREAMING_SNAKE_CASE = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
688
1
'''simple docstring''' import os from collections import deque import torch from torch.utils.data import Dataset class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[int] , A__ : Tuple="" , A__ : Union[str, Any]="train" ) -> Union[str, Any]: '''simple docstring''' assert os.path.isdir(A__ ) a__ : List[str] = [] a__ : str = os.listdir(A__ ) for story_filename in story_filenames_list: if "summary" in story_filename: continue a__ : str = os.path.join(A__ , A__ ) if not os.path.isfile(A__ ): continue self.documents.append(A__ ) def __len__( self : Any ) -> str: '''simple docstring''' return len(self.documents ) def __getitem__( self : Optional[int] , A__ : Any ) -> Any: '''simple docstring''' a__ : str = self.documents[idx] a__ : str = document_path.split('''/''' )[-1] with open(A__ , encoding='''utf-8''' ) as source: a__ : int = source.read() a__ , a__ : Optional[int] = process_story(A__ ) return document_name, story_lines, summary_lines def __a ( lowerCAmelCase__ : Optional[Any] ): a__ : str = list(filter(lambda lowerCAmelCase__ : len(lowerCAmelCase__ ) != 0 , [line.strip() for line in raw_story.split('''\n''' )] ) ) # for some unknown reason some lines miss a period, add it a__ : str = [_add_missing_period(lowerCAmelCase__ ) for line in nonempty_lines] # gather article lines a__ : Union[str, Any] = [] a__ : Tuple = deque(lowerCAmelCase__ ) while True: try: a__ : List[str] = lines.popleft() if element.startswith('''@highlight''' ): break story_lines.append(lowerCAmelCase__ ) except IndexError: # if "@highlight" is absent from the file we pop # all elements until there is None, raising an exception. return story_lines, [] # gather summary lines a__ : Union[str, Any] = list(filter(lambda lowerCAmelCase__ : not t.startswith('''@highlight''' ) , lowerCAmelCase__ ) ) return story_lines, summary_lines def __a ( lowerCAmelCase__ : str ): a__ : Dict = ['''.''', '''!''', '''?''', '''...''', '''\'''', '''`''', '''"''', '''\u2019''', '''\u2019''', ''')'''] if line.startswith('''@highlight''' ): return line if line[-1] in END_TOKENS: return line return line + "." def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Union[str, Any] ): if len(lowerCAmelCase__ ) > block_size: return sequence[:block_size] else: sequence.extend([pad_token_id] * (block_size - len(lowerCAmelCase__ )) ) return sequence def __a ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[str] ): a__ : Any = torch.ones_like(lowerCAmelCase__ ) a__ : Optional[int] = sequence == pad_token_id a__ : Union[str, Any] = 0 return mask def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : str ): a__ : int = [tokenizer.encode(lowerCAmelCase__ ) for line in story_lines] a__ : List[Any] = [token for sentence in story_lines_token_ids for token in sentence] a__ : Dict = [tokenizer.encode(lowerCAmelCase__ ) for line in summary_lines] a__ : Union[str, Any] = [token for sentence in summary_lines_token_ids for token in sentence] return story_token_ids, summary_token_ids def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] ): a__ : Optional[Any] = [] for sequence in batch: a__ : int = -1 a__ : Union[str, Any] = [] for s in sequence: if s == separator_token_id: sentence_num += 1 embeddings.append(sentence_num % 2 ) batch_embeddings.append(lowerCAmelCase__ ) return torch.tensor(lowerCAmelCase__ )
688
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = (KDPMaDiscreteScheduler,) __UpperCamelCase = 10 def __lowerCAmelCase ( self : Optional[Any] , **A__ : Optional[int] ) -> int: '''simple docstring''' a__ : Optional[int] = { '''num_train_timesteps''': 1_1_0_0, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**A__ ) return config def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=A__ ) def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=A__ , beta_end=A__ ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A__ ) def __lowerCAmelCase ( self : str ) -> Optional[int]: '''simple docstring''' a__ : Any = self.scheduler_classes[0] a__ : str = self.get_scheduler_config(prediction_type='''v_prediction''' ) a__ : Dict = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : Tuple = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Dict = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : Optional[Any] = scheduler.scale_model_input(A__ , A__ ) a__ : Union[str, Any] = model(A__ , A__ ) a__ : List[str] = scheduler.step(A__ , A__ , A__ ) a__ : Optional[Any] = output.prev_sample a__ : Tuple = torch.sum(torch.abs(A__ ) ) a__ : Optional[int] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_4286_5017_0972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' if torch_device == "mps": return a__ : List[Any] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : Tuple = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : List[Any] = self.dummy_model() a__ : Any = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Any = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : str = scheduler.scale_model_input(A__ , A__ ) a__ : List[str] = model(A__ , A__ ) a__ : str = scheduler.step(A__ , A__ , A__ ) a__ : List[Any] = output.prev_sample a__ : Dict = torch.sum(torch.abs(A__ ) ) a__ : Optional[Any] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' if torch_device == "mps": return a__ : Optional[int] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : List[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps , device=A__ ) a__ : Union[str, Any] = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter.to(A__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: a__ : Optional[int] = scheduler.scale_model_input(A__ , A__ ) a__ : List[Any] = model(A__ , A__ ) a__ : Any = scheduler.step(A__ , A__ , A__ ) a__ : List[str] = output.prev_sample a__ : Any = torch.sum(torch.abs(A__ ) ) a__ : Union[str, Any] = torch.mean(torch.abs(A__ ) ) if str(A__ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
688
1
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = ["image_processor", "tokenizer"] __UpperCamelCase = "LayoutLMv2ImageProcessor" __UpperCamelCase = ("LayoutXLMTokenizer", "LayoutXLMTokenizerFast") def __init__( self : Union[str, Any] , A__ : List[str]=None , A__ : Optional[Any]=None , **A__ : Any ) -> Any: '''simple docstring''' if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , A__ , ) a__ : Dict = kwargs.pop('''feature_extractor''' ) a__ : List[Any] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(A__ , A__ ) def __call__( self : List[str] , A__ : Optional[Any] , A__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , A__ : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , A__ : Union[List[List[int]], List[List[List[int]]]] = None , A__ : Optional[Union[List[int], List[List[int]]]] = None , A__ : bool = True , A__ : Union[bool, str, PaddingStrategy] = False , A__ : Union[bool, str, TruncationStrategy] = None , A__ : Optional[int] = None , A__ : int = 0 , A__ : Optional[int] = None , A__ : Optional[bool] = None , A__ : Optional[bool] = None , A__ : bool = False , A__ : bool = False , A__ : bool = False , A__ : bool = False , A__ : bool = True , A__ : Optional[Union[str, TensorType]] = None , **A__ : List[Any] , ) -> BatchEncoding: '''simple docstring''' if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( '''You cannot provide bounding boxes ''' '''if you initialized the image processor with apply_ocr set to True.''' ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( '''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' ) if return_overflowing_tokens is True and return_offsets_mapping is False: raise ValueError('''You cannot return overflowing tokens without returning the offsets mapping.''' ) # first, apply the image processor a__ : int = self.image_processor(images=A__ , return_tensors=A__ ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(A__ , A__ ): a__ : List[Any] = [text] # add batch dimension (as the image processor always adds a batch dimension) a__ : Any = features['''words'''] a__ : str = self.tokenizer( text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=A__ , add_special_tokens=A__ , padding=A__ , truncation=A__ , max_length=A__ , stride=A__ , pad_to_multiple_of=A__ , return_token_type_ids=A__ , return_attention_mask=A__ , return_overflowing_tokens=A__ , return_special_tokens_mask=A__ , return_offsets_mapping=A__ , return_length=A__ , verbose=A__ , return_tensors=A__ , **A__ , ) # add pixel values a__ : Dict = features.pop('''pixel_values''' ) if return_overflowing_tokens is True: a__ : Union[str, Any] = self.get_overflowing_images(A__ , encoded_inputs['''overflow_to_sample_mapping'''] ) a__ : Optional[int] = images return encoded_inputs def __lowerCAmelCase ( self : List[str] , A__ : Optional[Any] , A__ : Tuple ) -> Tuple: '''simple docstring''' a__ : Dict = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(A__ ) != len(A__ ): raise ValueError( '''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got''' F' {len(A__ )} and {len(A__ )}' ) return images_with_overflow def __lowerCAmelCase ( self : Optional[Any] , *A__ : Tuple , **A__ : str ) -> Union[str, Any]: '''simple docstring''' return self.tokenizer.batch_decode(*A__ , **A__ ) def __lowerCAmelCase ( self : List[Any] , *A__ : Union[str, Any] , **A__ : Dict ) -> Union[str, Any]: '''simple docstring''' return self.tokenizer.decode(*A__ , **A__ ) @property def __lowerCAmelCase ( self : Union[str, Any] ) -> str: '''simple docstring''' return ["input_ids", "bbox", "attention_mask", "image"] @property def __lowerCAmelCase ( self : int ) -> List[str]: '''simple docstring''' warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , A__ , ) return self.image_processor_class @property def __lowerCAmelCase ( self : Optional[Any] ) -> List[str]: '''simple docstring''' warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , A__ , ) return self.image_processor
688
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None a__ , a__ : List[Any] = get_aligned_output_features_output_indices(A__ , A__ , A__ ) self.assertEqual(A__ , ['''c'''] ) self.assertEqual(A__ , [2] ) # Out indices set to match out features a__ , a__ : Optional[int] = get_aligned_output_features_output_indices(['''a''', '''c'''] , A__ , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features set to match out indices a__ , a__ : int = get_aligned_output_features_output_indices(A__ , [0, 2] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features selected from negative indices a__ , a__ : List[str] = get_aligned_output_features_output_indices(A__ , [-3, -1] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [-3, -1] ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , A__ ) # Out features must be a list with self.assertRaises(A__ ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(A__ ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : Optional[Any] = BackboneMixin() a__ : int = ['''a''', '''b''', '''c'''] a__ : List[Any] = ['''a''', '''c'''] a__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly a__ : Dict = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) a__ : int = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
688
1
'''simple docstring''' import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Union[str, Any] , A__ : Any=0.01 , A__ : Any=1_0_0_0 ) -> Optional[int]: '''simple docstring''' a__ : Dict = p_stop a__ : str = max_length def __iter__( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] = 0 a__ : int = False while not stop and count < self.max_length: yield count count += 1 a__ : List[str] = random.random() < self.p_stop class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Dict , A__ : Tuple , A__ : Union[str, Any] , A__ : Optional[int]=False , A__ : Tuple=True ) -> Dict: '''simple docstring''' a__ : List[str] = [ BatchSamplerShard(A__ , 2 , A__ , split_batches=A__ , even_batches=A__ ) for i in range(2 ) ] a__ : str = [list(A__ ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(A__ ) for shard in batch_sampler_shards] , [len(A__ ) for e in expected] ) self.assertListEqual(A__ , A__ ) def __lowerCAmelCase ( self : Tuple ) -> str: '''simple docstring''' a__ : int = BatchSampler(range(2_4 ) , batch_size=3 , drop_last=A__ ) a__ : Dict = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1, 2_2, 2_3]], ] self.check_batch_sampler_shards(A__ , A__ ) a__ : Any = BatchSampler(range(2_4 ) , batch_size=3 , drop_last=A__ ) # Expected shouldn't change self.check_batch_sampler_shards(A__ , A__ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. a__ : Dict = BatchSampler(range(2_1 ) , batch_size=3 , drop_last=A__ ) a__ : Optional[Any] = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [0, 1, 2]], ] self.check_batch_sampler_shards(A__ , A__ ) a__ : int = BatchSampler(range(2_1 ) , batch_size=3 , drop_last=A__ ) a__ : int = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(A__ , A__ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. a__ : str = BatchSampler(range(2_2 ) , batch_size=3 , drop_last=A__ ) a__ : Dict = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1, 0, 1]], ] self.check_batch_sampler_shards(A__ , A__ ) a__ : Dict = BatchSampler(range(2_2 ) , batch_size=3 , drop_last=A__ ) a__ : int = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(A__ , A__ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. a__ : int = BatchSampler(range(2_0 ) , batch_size=3 , drop_last=A__ ) a__ : Optional[int] = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [1, 2, 3]], ] self.check_batch_sampler_shards(A__ , A__ ) a__ : Dict = BatchSampler(range(2_0 ) , batch_size=3 , drop_last=A__ ) a__ : Optional[int] = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(A__ , A__ ) # Check the shards when the dataset is very small. a__ : int = BatchSampler(range(2 ) , batch_size=3 , drop_last=A__ ) a__ : Optional[Any] = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(A__ , A__ ) a__ : List[Any] = BatchSampler(range(2 ) , batch_size=3 , drop_last=A__ ) a__ : str = [[], []] self.check_batch_sampler_shards(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' a__ : Tuple = BatchSampler(range(2_4 ) , batch_size=4 , drop_last=A__ ) a__ : Optional[int] = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [2_2, 2_3]], ] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ ) a__ : Union[str, Any] = BatchSampler(range(2_4 ) , batch_size=4 , drop_last=A__ ) # Expected shouldn't change self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ ) # Check the shards when the dataset is not a round multiple of batch size. a__ : List[Any] = BatchSampler(range(2_2 ) , batch_size=4 , drop_last=A__ ) a__ : Optional[Any] = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [0, 1]], ] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ ) a__ : Optional[Any] = BatchSampler(range(2_2 ) , batch_size=4 , drop_last=A__ ) a__ : Optional[int] = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. a__ : Optional[Any] = BatchSampler(range(2_1 ) , batch_size=4 , drop_last=A__ ) a__ : Union[str, Any] = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 0]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [1, 2]], ] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ ) a__ : Dict = BatchSampler(range(2_1 ) , batch_size=4 , drop_last=A__ ) a__ : Tuple = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ ) # Check the shards when the dataset is very small. a__ : Optional[Any] = BatchSampler(range(2 ) , batch_size=4 , drop_last=A__ ) a__ : Dict = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ ) a__ : Optional[Any] = BatchSampler(range(2 ) , batch_size=4 , drop_last=A__ ) a__ : int = [[], []] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ ) def __lowerCAmelCase ( self : Optional[int] ) -> Tuple: '''simple docstring''' a__ : List[Any] = BatchSampler(range(2_4 ) , batch_size=3 , drop_last=A__ ) a__ : Any = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1, 2_2, 2_3]], ] self.check_batch_sampler_shards(A__ , A__ , even_batches=A__ ) a__ : List[Any] = BatchSampler(range(2_4 ) , batch_size=3 , drop_last=A__ ) # Expected shouldn't change self.check_batch_sampler_shards(A__ , A__ , even_batches=A__ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. a__ : int = BatchSampler(range(2_1 ) , batch_size=3 , drop_last=A__ ) a__ : Any = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(A__ , A__ , even_batches=A__ ) a__ : Optional[int] = BatchSampler(range(2_1 ) , batch_size=3 , drop_last=A__ ) a__ : Union[str, Any] = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(A__ , A__ , even_batches=A__ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. a__ : Optional[int] = BatchSampler(range(2_2 ) , batch_size=3 , drop_last=A__ ) a__ : int = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9, 2_0]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7], [2_1]], ] self.check_batch_sampler_shards(A__ , A__ , even_batches=A__ ) a__ : Tuple = BatchSampler(range(2_2 ) , batch_size=3 , drop_last=A__ ) a__ : Optional[Any] = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(A__ , A__ , even_batches=A__ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. a__ : Any = BatchSampler(range(2_0 ) , batch_size=3 , drop_last=A__ ) a__ : str = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4], [1_8, 1_9]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(A__ , A__ , even_batches=A__ ) a__ : Optional[Any] = BatchSampler(range(2_0 ) , batch_size=3 , drop_last=A__ ) a__ : Dict = [ [[0, 1, 2], [6, 7, 8], [1_2, 1_3, 1_4]], [[3, 4, 5], [9, 1_0, 1_1], [1_5, 1_6, 1_7]], ] self.check_batch_sampler_shards(A__ , A__ , even_batches=A__ ) # Check the shards when the dataset is very small. a__ : Dict = BatchSampler(range(2 ) , batch_size=3 , drop_last=A__ ) a__ : Tuple = [[[0, 1]], []] self.check_batch_sampler_shards(A__ , A__ , even_batches=A__ ) a__ : Optional[int] = BatchSampler(range(2 ) , batch_size=3 , drop_last=A__ ) a__ : str = [[], []] self.check_batch_sampler_shards(A__ , A__ , even_batches=A__ ) def __lowerCAmelCase ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' a__ : Optional[int] = BatchSampler(range(2_4 ) , batch_size=4 , drop_last=A__ ) a__ : Optional[Any] = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9], [2_2, 2_3]], ] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ , even_batches=A__ ) a__ : Dict = BatchSampler(range(2_4 ) , batch_size=4 , drop_last=A__ ) # Expected shouldn't change self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ , even_batches=A__ ) # Check the shards when the dataset is not a round multiple of batch size. a__ : Union[str, Any] = BatchSampler(range(2_2 ) , batch_size=4 , drop_last=A__ ) a__ : str = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0, 2_1]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ , even_batches=A__ ) a__ : List[Any] = BatchSampler(range(2_2 ) , batch_size=4 , drop_last=A__ ) a__ : Any = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ , even_batches=A__ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. a__ : Tuple = BatchSampler(range(2_1 ) , batch_size=4 , drop_last=A__ ) a__ : Tuple = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7], [2_0]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ , even_batches=A__ ) a__ : Tuple = BatchSampler(range(2_1 ) , batch_size=4 , drop_last=A__ ) a__ : Dict = [ [[0, 1], [4, 5], [8, 9], [1_2, 1_3], [1_6, 1_7]], [[2, 3], [6, 7], [1_0, 1_1], [1_4, 1_5], [1_8, 1_9]], ] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ , even_batches=A__ ) # Check the shards when the dataset is very small. a__ : List[str] = BatchSampler(range(2 ) , batch_size=4 , drop_last=A__ ) a__ : List[Any] = [[[0, 1]], []] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ , even_batches=A__ ) a__ : Any = BatchSampler(range(2 ) , batch_size=4 , drop_last=A__ ) a__ : str = [[], []] self.check_batch_sampler_shards(A__ , A__ , split_batches=A__ , even_batches=A__ ) def __lowerCAmelCase ( self : Tuple ) -> Union[str, Any]: '''simple docstring''' a__ : Tuple = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 1_0, 1_1], [1_2, 1_3]] a__ : int = [BatchSamplerShard(A__ , 2 , A__ , even_batches=A__ ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) , 3 ) self.assertEqual(len(batch_sampler_shards[1] ) , 2 ) self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [1_2, 1_3]] ) self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 1_0, 1_1]] ) def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[Any] , A__ : Optional[Any] , A__ : Tuple=False , A__ : Any=2 , A__ : Dict=False ) -> List[str]: '''simple docstring''' random.seed(A__ ) a__ : List[str] = list(A__ ) a__ : Union[str, Any] = [ IterableDatasetShard( A__ , batch_size=A__ , drop_last=A__ , num_processes=A__ , process_index=A__ , split_batches=A__ , ) for i in range(A__ ) ] a__ : Optional[Any] = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(A__ ) iterable_dataset_lists.append(list(A__ ) ) a__ : Optional[int] = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size a__ : Dict = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(A__ ) , len(A__ ) ) self.assertTrue(len(A__ ) % shard_batch_size == 0 ) a__ : Optional[int] = [] for idx in range(0 , len(A__ ) , A__ ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(A__ ) < len(A__ ): reference += reference self.assertListEqual(A__ , reference[: len(A__ )] ) def __lowerCAmelCase ( self : Dict ) -> Tuple: '''simple docstring''' a__ : Dict = 4_2 a__ : Optional[int] = RandomIterableDataset() self.check_iterable_dataset_shards(A__ , A__ , batch_size=4 , drop_last=A__ , split_batches=A__ ) self.check_iterable_dataset_shards(A__ , A__ , batch_size=4 , drop_last=A__ , split_batches=A__ ) self.check_iterable_dataset_shards(A__ , A__ , batch_size=4 , drop_last=A__ , split_batches=A__ ) self.check_iterable_dataset_shards(A__ , A__ , batch_size=4 , drop_last=A__ , split_batches=A__ ) # Edge case with a very small dataset a__ : str = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(A__ , A__ , batch_size=4 , drop_last=A__ , split_batches=A__ ) self.check_iterable_dataset_shards(A__ , A__ , batch_size=4 , drop_last=A__ , split_batches=A__ ) self.check_iterable_dataset_shards(A__ , A__ , batch_size=4 , drop_last=A__ , split_batches=A__ ) self.check_iterable_dataset_shards(A__ , A__ , batch_size=4 , drop_last=A__ , split_batches=A__ ) def __lowerCAmelCase ( self : Any ) -> str: '''simple docstring''' a__ : List[str] = BatchSampler(range(1_6 ) , batch_size=4 , drop_last=A__ ) a__ : List[str] = SkipBatchSampler(A__ , 2 ) self.assertListEqual(list(A__ ) , [[8, 9, 1_0, 1_1], [1_2, 1_3, 1_4, 1_5]] ) def __lowerCAmelCase ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' a__ : List[str] = SkipDataLoader(list(range(1_6 ) ) , batch_size=4 , skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 1_0, 1_1], [1_2, 1_3, 1_4, 1_5]] ) def __lowerCAmelCase ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' a__ : Optional[int] = DataLoader(list(range(1_6 ) ) , batch_size=4 ) a__ : List[str] = skip_first_batches(A__ , num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 1_0, 1_1], [1_2, 1_3, 1_4, 1_5]] ) def __lowerCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[Any] = DataLoaderShard(list(range(1_6 ) ) , batch_size=4 ) for idx, _ in enumerate(A__ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(A__ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) def __lowerCAmelCase ( self : Union[str, Any] ) -> List[str]: '''simple docstring''' Accelerator() a__ : Union[str, Any] = DataLoaderDispatcher(range(1_6 ) , batch_size=4 ) for idx, _ in enumerate(A__ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(A__ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
688
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __a ( lowerCAmelCase__ : List[Any] ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ): a__ : Dict = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue a__ : Any = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) a__ : int = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) a__ : Optional[Any] = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) a__ : Dict = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) a__ : List[str] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) a__ : List[Any] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) a__ : str = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) a__ : List[Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) a__ : List[Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) a__ : str = key.replace('''image_encoder.module''' , '''flava.image_model''' ) a__ : Dict = key.replace('''text_encoder.module''' , '''flava.text_model''' ) a__ : List[Any] = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) a__ : List[str] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) a__ : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' ) a__ : Any = key.replace('''image_projection''' , '''flava.image_projection''' ) a__ : Any = value.float() for key, value in codebook_state_dict.items(): a__ : List[str] = value return upgrade @torch.no_grad() def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict=None ): if config_path is not None: a__ : Tuple = FlavaConfig.from_pretrained(lowerCAmelCase__ ) else: a__ : Optional[int] = FlavaConfig() a__ : List[Any] = FlavaForPreTraining(lowerCAmelCase__ ).eval() a__ : Optional[int] = convert_dalle_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , save_checkpoint=lowerCAmelCase__ ) if os.path.exists(lowerCAmelCase__ ): a__ : List[str] = torch.load(lowerCAmelCase__ , map_location='''cpu''' ) else: a__ : Dict = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' ) a__ : List[Any] = upgrade_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) a__ : Any = hf_model.state_dict() a__ : Optional[Any] = count_parameters(lowerCAmelCase__ ) a__ : int = count_parameters(lowerCAmelCase__ ) + count_parameters(lowerCAmelCase__ ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
688
1
'''simple docstring''' import enum import shutil import sys __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = shutil.get_terminal_size() __SCREAMING_SNAKE_CASE = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase__ ( enum.Enum ): """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 1 def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict="" ): sys.stdout.write(str(lowerCAmelCase__ ) + end ) sys.stdout.flush() def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : int="" ): forceWrite(F'\u001b[{color}m{content}\u001b[0m' , lowerCAmelCase__ ) def __a ( ): forceWrite('''\r''' ) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : str ): forceWrite(F'\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}' ) def __a ( ): forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def __a ( ): reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
688
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass def __a ( lowerCAmelCase__ : List[str] ): for shard in shards: for i in range(lowerCAmelCase__ ): yield {"i": i, "shard": shard} def __a ( ): a__ : str = int(os.environ['''RANK'''] ) a__ : int = int(os.environ['''WORLD_SIZE'''] ) a__ : str = ArgumentParser() parser.add_argument('''--streaming''' , type=lowerCAmelCase__ ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase__ ) parser.add_argument('''--num_workers''' , type=lowerCAmelCase__ , default=0 ) a__ : int = parser.parse_args() a__ : List[str] = args.streaming a__ : Dict = args.num_workers a__ : Dict = {'''shards''': [F'shard_{shard_idx}' for shard_idx in range(lowerCAmelCase__ )]} a__ : Tuple = IterableDataset.from_generator(lowerCAmelCase__ , gen_kwargs=lowerCAmelCase__ ) if not streaming: a__ : str = Dataset.from_list(list(lowerCAmelCase__ ) ) a__ : Optional[int] = split_dataset_by_node(lowerCAmelCase__ , rank=lowerCAmelCase__ , world_size=lowerCAmelCase__ ) a__ : Dict = torch.utils.data.DataLoader(lowerCAmelCase__ , num_workers=lowerCAmelCase__ ) a__ : str = NUM_SHARDS * NUM_ITEMS_PER_SHARD a__ : Dict = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) a__ : str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'local_size {local_size} != expected_local_size {expected_local_size}' ) if __name__ == "__main__": main()
688
1
'''simple docstring''' from math import asin, atan, cos, radians, sin, sqrt, tan __SCREAMING_SNAKE_CASE = 6_378_137.0 __SCREAMING_SNAKE_CASE = 6_356_752.314_245 __SCREAMING_SNAKE_CASE = 6_3_7_8_1_3_7 def __a ( lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : float ): a__ : List[str] = (AXIS_A - AXIS_B) / AXIS_A a__ : Optional[Any] = atan((1 - flattening) * tan(radians(lowerCAmelCase__ ) ) ) a__ : int = atan((1 - flattening) * tan(radians(lowerCAmelCase__ ) ) ) a__ : Optional[int] = radians(lowerCAmelCase__ ) a__ : Optional[int] = radians(lowerCAmelCase__ ) # Equation a__ : Optional[int] = sin((phi_a - phi_a) / 2 ) a__ : List[Any] = sin((lambda_a - lambda_a) / 2 ) # Square both values sin_sq_phi *= sin_sq_phi sin_sq_lambda *= sin_sq_lambda a__ : Any = sqrt(sin_sq_phi + (cos(lowerCAmelCase__ ) * cos(lowerCAmelCase__ ) * sin_sq_lambda) ) return 2 * RADIUS * asin(lowerCAmelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
688
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __SCREAMING_SNAKE_CASE = open # noqa: we just need to have a builtin inside this module to test it properly
688
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'shi-labs/dinat-mini-in1k-224': 'https://huggingface.co/shi-labs/dinat-mini-in1k-224/resolve/main/config.json', # See all Dinat models at https://huggingface.co/models?filter=dinat } class lowerCAmelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "dinat" __UpperCamelCase = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Optional[int] , A__ : Optional[int]=4 , A__ : List[str]=3 , A__ : str=6_4 , A__ : List[Any]=[3, 4, 6, 5] , A__ : List[Any]=[2, 4, 8, 1_6] , A__ : Any=7 , A__ : Any=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]] , A__ : Dict=3.0 , A__ : Optional[Any]=True , A__ : Optional[int]=0.0 , A__ : Tuple=0.0 , A__ : Optional[Any]=0.1 , A__ : List[Any]="gelu" , A__ : Optional[Any]=0.02 , A__ : Tuple=1E-5 , A__ : str=0.0 , A__ : int=None , A__ : Optional[Any]=None , **A__ : Optional[Any] , ) -> List[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : Any = patch_size a__ : Any = num_channels a__ : Dict = embed_dim a__ : Optional[int] = depths a__ : List[Any] = len(A__ ) a__ : int = num_heads a__ : Tuple = kernel_size a__ : Dict = dilations a__ : Any = mlp_ratio a__ : List[Any] = qkv_bias a__ : Tuple = hidden_dropout_prob a__ : Optional[int] = attention_probs_dropout_prob a__ : List[str] = drop_path_rate a__ : Optional[int] = hidden_act a__ : Dict = layer_norm_eps a__ : List[str] = initializer_range # we set the hidden_size attribute in order to make Dinat work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model a__ : str = int(embed_dim * 2 ** (len(A__ ) - 1) ) a__ : Tuple = layer_scale_init_value a__ : Union[str, Any] = ['''stem'''] + [F'stage{idx}' for idx in range(1 , len(A__ ) + 1 )] a__ , a__ : List[str] = get_aligned_output_features_output_indices( out_features=A__ , out_indices=A__ , stage_names=self.stage_names )
688
'''simple docstring''' import enum import shutil import sys __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = shutil.get_terminal_size() __SCREAMING_SNAKE_CASE = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase__ ( enum.Enum ): """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 1 def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict="" ): sys.stdout.write(str(lowerCAmelCase__ ) + end ) sys.stdout.flush() def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : int="" ): forceWrite(F'\u001b[{color}m{content}\u001b[0m' , lowerCAmelCase__ ) def __a ( ): forceWrite('''\r''' ) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : str ): forceWrite(F'\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}' ) def __a ( ): forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def __a ( ): reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
688
1
'''simple docstring''' import unittest import numpy as np import torch from torch import nn from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import enable_full_determinism, skip_mps from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = KandinskyVaaPriorPipeline __UpperCamelCase = ["prompt"] __UpperCamelCase = ["prompt", "negative_prompt"] __UpperCamelCase = [ "num_images_per_prompt", "generator", "num_inference_steps", "latents", "negative_prompt", "guidance_scale", "output_type", "return_dict", ] __UpperCamelCase = False @property def __lowerCAmelCase ( self : Optional[int] ) -> Optional[int]: '''simple docstring''' return 3_2 @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return 3_2 @property def __lowerCAmelCase ( self : Dict ) -> Optional[Any]: '''simple docstring''' return self.time_input_dim @property def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' return self.time_input_dim * 4 @property def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return 1_0_0 @property def __lowerCAmelCase ( self : Union[str, Any] ) -> int: '''simple docstring''' a__ : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) return tokenizer @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) a__ : str = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) return CLIPTextModelWithProjection(A__ ) @property def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' torch.manual_seed(0 ) a__ : List[Any] = { '''num_attention_heads''': 2, '''attention_head_dim''': 1_2, '''embedding_dim''': self.text_embedder_hidden_size, '''num_layers''': 1, } a__ : Union[str, Any] = PriorTransformer(**A__ ) # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0 a__ : List[Any] = nn.Parameter(torch.ones(model.clip_std.shape ) ) return model @property def __lowerCAmelCase ( self : List[str] ) -> Optional[Any]: '''simple docstring''' torch.manual_seed(0 ) a__ : Union[str, Any] = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=2_2_4 , projection_dim=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1_4 , ) a__ : Dict = CLIPVisionModelWithProjection(A__ ) return model @property def __lowerCAmelCase ( self : List[str] ) -> Optional[int]: '''simple docstring''' a__ : Optional[Any] = CLIPImageProcessor( crop_size=2_2_4 , do_center_crop=A__ , do_normalize=A__ , do_resize=A__ , image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073] , image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711] , resample=3 , size=2_2_4 , ) return image_processor def __lowerCAmelCase ( self : List[Any] ) -> Union[str, Any]: '''simple docstring''' a__ : str = self.dummy_prior a__ : Union[str, Any] = self.dummy_image_encoder a__ : Optional[int] = self.dummy_text_encoder a__ : List[Any] = self.dummy_tokenizer a__ : Tuple = self.dummy_image_processor a__ : Union[str, Any] = UnCLIPScheduler( variance_type='''fixed_small_log''' , prediction_type='''sample''' , num_train_timesteps=1_0_0_0 , clip_sample=A__ , clip_sample_range=10.0 , ) a__ : List[str] = { '''prior''': prior, '''image_encoder''': image_encoder, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''scheduler''': scheduler, '''image_processor''': image_processor, } return components def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[int] , A__ : Optional[int]=0 ) -> Optional[int]: '''simple docstring''' if str(A__ ).startswith('''mps''' ): a__ : List[str] = torch.manual_seed(A__ ) else: a__ : Union[str, Any] = torch.Generator(device=A__ ).manual_seed(A__ ) a__ : Dict = { '''prompt''': '''horse''', '''generator''': generator, '''guidance_scale''': 4.0, '''num_inference_steps''': 2, '''output_type''': '''np''', } return inputs def __lowerCAmelCase ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' a__ : Tuple = '''cpu''' a__ : Optional[Any] = self.get_dummy_components() a__ : Any = self.pipeline_class(**A__ ) a__ : int = pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) a__ : List[str] = pipe(**self.get_dummy_inputs(A__ ) ) a__ : List[str] = output.image_embeds a__ : Union[str, Any] = pipe( **self.get_dummy_inputs(A__ ) , return_dict=A__ , )[0] a__ : int = image[0, -1_0:] a__ : Union[str, Any] = image_from_tuple[0, -1_0:] assert image.shape == (1, 3_2) a__ : List[Any] = np.array( [-0.0_532, 1.7_120, 0.3_656, -1.0_852, -0.8_946, -1.1_756, 0.4_348, 0.2_482, 0.5_146, -0.1_156] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @skip_mps def __lowerCAmelCase ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' a__ : List[str] = torch_device == '''cpu''' a__ : Union[str, Any] = True a__ : Any = False self._test_inference_batch_single_identical( test_max_difference=A__ , relax_max_difference=A__ , test_mean_pixel_difference=A__ , ) @skip_mps def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' a__ : List[str] = torch_device == '''cpu''' a__ : List[str] = False self._test_attention_slicing_forward_pass( test_max_difference=A__ , test_mean_pixel_difference=A__ , )
688
'''simple docstring''' import inspect import unittest class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' try: import diffusers # noqa: F401 except ImportError: assert False def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' import diffusers from diffusers.dependency_versions_table import deps a__ : Optional[int] = inspect.getmembers(A__ , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": a__ : int = '''k-diffusion''' elif backend == "invisible_watermark": a__ : int = '''invisible-watermark''' assert backend in deps, F'{backend} is not in the deps table!'
688
1
'''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 __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) def __a ( ): # Get the sagemaker specific mp parameters from smp_options variable. a__ : str = os.getenv('''SM_HP_MP_PARAMETERS''' , '''{}''' ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. a__ : Optional[Any] = json.loads(lowerCAmelCase__ ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. a__ : Any = os.getenv('''SM_FRAMEWORK_PARAMS''' , '''{}''' ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". a__ : Optional[Any] = json.loads(lowerCAmelCase__ ) if not mpi_options.get('''sagemaker_mpi_enabled''' , lowerCAmelCase__ ): 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""" __UpperCamelCase = field( default="" , metadata={"help": "Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"} , ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' super().__post_init__() warnings.warn( '''`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use ''' '''`TrainingArguments` instead.''' , A__ , ) @cached_property def __lowerCAmelCase ( self : str ) -> "torch.device": '''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: a__ : List[Any] = torch.device('''cpu''' ) a__ : Optional[Any] = 0 elif is_sagemaker_model_parallel_available(): a__ : Optional[Any] = smp.local_rank() a__ : Any = torch.device('''cuda''' , A__ ) a__ : Tuple = 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 ) a__ : Dict = int(os.getenv('''SMDATAPARALLEL_LOCAL_RANK''' ) ) a__ : Dict = torch.device('''cuda''' , self.local_rank ) a__ : Tuple = 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 a__ : List[Any] = 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. a__ : List[Any] = 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 ) a__ : List[str] = torch.device('''cuda''' , self.local_rank ) a__ : str = 1 if device.type == "cuda": torch.cuda.set_device(A__ ) return device @property def __lowerCAmelCase ( self : Dict ) -> str: '''simple docstring''' if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return not is_sagemaker_model_parallel_available() @property def __lowerCAmelCase ( self : List[str] ) -> Union[str, Any]: '''simple docstring''' return False
688
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __a ( lowerCAmelCase__ : Dict ): a__ , a__ : int = image.size a__ , a__ : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 a__ : Tuple = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) a__ : List[Any] = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 255.0 a__ : Any = image[None].transpose(0 , 3 , 1 , 2 ) a__ : Dict = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , A__ : VQModel , A__ : UNetaDModel , A__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> str: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : List[str] , A__ : Union[torch.Tensor, PIL.Image.Image] = None , A__ : Optional[int] = 1 , A__ : Optional[int] = 1_0_0 , A__ : Optional[float] = 0.0 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' if isinstance(A__ , PIL.Image.Image ): a__ : List[Any] = 1 elif isinstance(A__ , torch.Tensor ): a__ : List[str] = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(A__ )}' ) if isinstance(A__ , PIL.Image.Image ): a__ : Union[str, Any] = preprocess(A__ ) a__ , a__ : Dict = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image a__ : Optional[int] = (batch_size, self.unet.config.in_channels // 2, height, width) a__ : Optional[int] = next(self.unet.parameters() ).dtype a__ : List[str] = randn_tensor(A__ , generator=A__ , device=self.device , dtype=A__ ) a__ : Any = image.to(device=self.device , dtype=A__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(A__ , device=self.device ) a__ : int = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler a__ : str = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a__ : Union[str, Any] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a__ : str = {} if accepts_eta: a__ : Dict = eta for t in self.progress_bar(A__ ): # concat latents and low resolution image in the channel dimension. a__ : str = torch.cat([latents, image] , dim=1 ) a__ : Optional[Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual a__ : Union[str, Any] = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VQVAE a__ : List[Any] = self.vqvae.decode(A__ ).sample a__ : List[Any] = torch.clamp(A__ , -1.0 , 1.0 ) a__ : Optional[Any] = image / 2 + 0.5 a__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a__ : Union[str, Any] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None a__ , a__ : List[Any] = get_aligned_output_features_output_indices(A__ , A__ , A__ ) self.assertEqual(A__ , ['''c'''] ) self.assertEqual(A__ , [2] ) # Out indices set to match out features a__ , a__ : Optional[int] = get_aligned_output_features_output_indices(['''a''', '''c'''] , A__ , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features set to match out indices a__ , a__ : int = get_aligned_output_features_output_indices(A__ , [0, 2] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features selected from negative indices a__ , a__ : List[str] = get_aligned_output_features_output_indices(A__ , [-3, -1] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [-3, -1] ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , A__ ) # Out features must be a list with self.assertRaises(A__ ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(A__ ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : Optional[Any] = BackboneMixin() a__ : int = ['''a''', '''b''', '''c'''] a__ : List[Any] = ['''a''', '''c'''] a__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly a__ : Dict = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) a__ : int = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
688
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # pylint: disable=invalid-name __SCREAMING_SNAKE_CASE = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : str=8 ): a__ : Tuple = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a__ : Union[str, Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Dict , A__ : UNetaDConditionModel , A__ : DDPMScheduler , A__ : VQModel , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules( unet=A__ , scheduler=A__ , movq=A__ , ) a__ : Union[str, Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] , A__ : List[str] , A__ : Optional[Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if latents is None: a__ : List[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__ : int = latents.to(A__ ) a__ : Tuple = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : Union[str, Any] , A__ : int=0 ) -> str: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a__ : Union[str, Any] = torch.device(F'cuda:{gpu_id}' ) a__ : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A__ , A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple=0 ) -> Dict: '''simple docstring''' if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) a__ : int = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=A__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a__ : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: a__ , a__ : List[str] = cpu_offload_with_hook(A__ , A__ , prev_module_hook=A__ ) # We'll offload the last model manually. a__ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.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 @torch.no_grad() @replace_example_docstring(A__ ) def __call__( self : Any , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : torch.FloatTensor , A__ : int = 5_1_2 , A__ : int = 5_1_2 , A__ : int = 1_0_0 , A__ : float = 4.0 , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> str: '''simple docstring''' a__ : Optional[Any] = self._execution_device a__ : List[str] = guidance_scale > 1.0 if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : Optional[int] = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) a__ : Union[str, Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a__ : Tuple = image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = negative_image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = hint.repeat_interleave(A__ , dim=0 ) a__ : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) a__ : Tuple = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) self.scheduler.set_timesteps(A__ , device=A__ ) a__ : int = self.scheduler.timesteps a__ : str = self.movq.config.latent_channels a__ , a__ : Optional[int] = downscale_height_and_width(A__ , A__ , self.movq_scale_factor ) # create initial latent a__ : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A__ , A__ , A__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance a__ : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ : List[str] = {'''image_embeds''': image_embeds, '''hint''': hint} a__ : Union[str, Any] = self.unet( sample=A__ , timestep=A__ , encoder_hidden_states=A__ , added_cond_kwargs=A__ , return_dict=A__ , )[0] if do_classifier_free_guidance: a__ , a__ : Dict = noise_pred.split(latents.shape[1] , dim=1 ) a__ , a__ : Dict = noise_pred.chunk(2 ) a__ , a__ : Optional[Any] = variance_pred.chunk(2 ) a__ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a__ , a__ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step( A__ , A__ , A__ , generator=A__ , )[0] # post-processing a__ : Tuple = self.movq.decode(A__ , force_not_quantize=A__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: a__ : Union[str, Any] = image * 0.5 + 0.5 a__ : str = image.clamp(0 , 1 ) a__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ : int = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def __a ( lowerCAmelCase__ : Optional[Any]=None ): a__ : Optional[Any] = argparse.ArgumentParser(add_help=lowerCAmelCase__ , allow_abbrev=lowerCAmelCase__ ) # The main config parser a__ : Optional[Any] = config_command_parser(lowerCAmelCase__ ) # The subparser to add commands to a__ : Dict = config_parser.add_subparsers(title='''subcommands''' , dest='''subcommand''' ) # Then add other parsers with the parent parser default_command_parser(lowerCAmelCase__ , parents=[parent_parser] ) update_command_parser(lowerCAmelCase__ , parents=[parent_parser] ) return config_parser def __a ( ): a__ : Union[str, Any] = get_config_parser() a__ : Any = config_parser.parse_args() if not hasattr(lowerCAmelCase__ , '''func''' ): config_parser.print_help() exit(1 ) # Run args.func(lowerCAmelCase__ ) if __name__ == "__main__": main()
688
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } __SCREAMING_SNAKE_CASE = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def __a ( lowerCAmelCase__ : Union[str, Any] ): with open(lowerCAmelCase__ , '''r''' ) as f: a__ : Optional[int] = f.read().splitlines() return [l.strip() for l in lines] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[str] , A__ : int , A__ : Union[str, Any]="<unk>" , A__ : Tuple="<cls>" , A__ : List[Any]="<pad>" , A__ : Optional[int]="<mask>" , A__ : List[Any]="<eos>" , **A__ : Optional[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) a__ : Union[str, Any] = load_vocab_file(A__ ) a__ : int = dict(enumerate(self.all_tokens ) ) a__ : str = {tok: ind for ind, tok in enumerate(self.all_tokens )} a__ : List[Any] = unk_token a__ : Any = cls_token a__ : Any = pad_token a__ : Any = mask_token a__ : Any = eos_token a__ : int = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCAmelCase ( self : Any , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , **A__ : str ) -> List[Any]: '''simple docstring''' return text.split() def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int]=False ) -> Tuple: '''simple docstring''' return len(self._id_to_token ) def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCAmelCase ( self : Any , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : List[Any] , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Tuple = [self.cls_token_id] a__ : Union[str, Any] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCAmelCase ( self : Tuple , A__ : List , A__ : Optional[List] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] a__ : Any = [1] + ([0] * len(A__ )) + [1] if token_ids_a is not None: mask += [0] * len(A__ ) + [1] return mask def __lowerCAmelCase ( self : Any , A__ : Dict , A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = os.path.join(A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(A__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return self.get_vocab_size(with_added_tokens=A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Union[List[str], List[AddedToken]] , A__ : bool = False ) -> int: '''simple docstring''' return super()._add_tokens(A__ , special_tokens=A__ )
688
1
'''simple docstring''' from pickle import UnpicklingError import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict from ..utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): try: with open(lowerCAmelCase__ , '''rb''' ) as flax_state_f: a__ : Optional[Any] = from_bytes(lowerCAmelCase__ , flax_state_f.read() ) except UnpicklingError as e: try: with open(lowerCAmelCase__ ) as f: if f.read().startswith('''version''' ): raise OSError( '''You seem to have cloned a repository without having git-lfs installed. Please''' ''' install git-lfs and run `git lfs install` followed by `git lfs pull` in the''' ''' folder you cloned.''' ) else: raise ValueError from e except (UnicodeDecodeError, ValueError): raise EnvironmentError(F'Unable to convert {model_file} to Flax deserializable object. ' ) return load_flax_weights_in_pytorch_model(lowerCAmelCase__ , lowerCAmelCase__ ) def __a ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : str ): try: import torch # noqa: F401 except ImportError: logger.error( '''Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see''' ''' https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation''' ''' instructions.''' ) raise # check if we have bf16 weights a__ : List[Any] = flatten_dict(jax.tree_util.tree_map(lambda lowerCAmelCase__ : x.dtype == jnp.bfloataa , lowerCAmelCase__ ) ).values() if any(lowerCAmelCase__ ): # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( '''Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` ''' '''before loading those in PyTorch model.''' ) a__ : List[str] = jax.tree_util.tree_map( lambda lowerCAmelCase__ : params.astype(np.floataa ) if params.dtype == jnp.bfloataa else params , lowerCAmelCase__ ) a__ : Tuple = '''''' a__ : List[str] = flatten_dict(lowerCAmelCase__ , sep='''.''' ) a__ : List[str] = pt_model.state_dict() # keep track of unexpected & missing keys a__ : int = [] a__ : List[Any] = set(pt_model_dict.keys() ) for flax_key_tuple, flax_tensor in flax_state_dict.items(): a__ : List[str] = flax_key_tuple.split('''.''' ) if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4: a__ : Optional[Any] = flax_key_tuple_array[:-1] + ['''weight'''] a__ : Union[str, Any] = jnp.transpose(lowerCAmelCase__ , (3, 2, 0, 1) ) elif flax_key_tuple_array[-1] == "kernel": a__ : List[Any] = flax_key_tuple_array[:-1] + ['''weight'''] a__ : Optional[int] = flax_tensor.T elif flax_key_tuple_array[-1] == "scale": a__ : Union[str, Any] = flax_key_tuple_array[:-1] + ['''weight'''] if "time_embedding" not in flax_key_tuple_array: for i, flax_key_tuple_string in enumerate(lowerCAmelCase__ ): a__ : List[str] = ( flax_key_tuple_string.replace('''_0''' , '''.0''' ) .replace('''_1''' , '''.1''' ) .replace('''_2''' , '''.2''' ) .replace('''_3''' , '''.3''' ) .replace('''_4''' , '''.4''' ) .replace('''_5''' , '''.5''' ) .replace('''_6''' , '''.6''' ) .replace('''_7''' , '''.7''' ) .replace('''_8''' , '''.8''' ) .replace('''_9''' , '''.9''' ) ) a__ : Dict = '''.'''.join(lowerCAmelCase__ ) if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( F'Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected ' F'to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.' ) else: # add weight to pytorch dict a__ : List[Any] = np.asarray(lowerCAmelCase__ ) if not isinstance(lowerCAmelCase__ , np.ndarray ) else flax_tensor a__ : Optional[int] = torch.from_numpy(lowerCAmelCase__ ) # remove from missing keys missing_keys.remove(lowerCAmelCase__ ) else: # weight is not expected by PyTorch model unexpected_keys.append(lowerCAmelCase__ ) pt_model.load_state_dict(lowerCAmelCase__ ) # re-transform missing_keys to list a__ : Tuple = list(lowerCAmelCase__ ) if len(lowerCAmelCase__ ) > 0: logger.warning( '''Some weights of the Flax model were not used when initializing the PyTorch model''' F' {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing' F' {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture' ''' (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This''' F' IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect' ''' to be exactly identical (e.g. initializing a BertForSequenceClassification model from a''' ''' FlaxBertForSequenceClassification model).''' ) if len(lowerCAmelCase__ ) > 0: logger.warning( F'Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly' F' initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to' ''' use it for predictions and inference.''' ) return pt_model
688
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ : """simple docstring""" def __init__( self : str ) -> Dict: '''simple docstring''' a__ : List[str] = False def __lowerCAmelCase ( self : Tuple , A__ : Optional[int] , A__ : Optional[Any] , A__ : List[str] , A__ : Tuple ) -> Optional[int]: '''simple docstring''' if not self.initialized: a__ : Optional[Any] = RagRetriever( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : Union[str, Any] = True def __lowerCAmelCase ( self : Tuple ) -> Tuple: '''simple docstring''' self.retriever.index.init_index() def __lowerCAmelCase ( self : List[Any] , A__ : List[Any] , A__ : Optional[int] ) -> List[Any]: '''simple docstring''' a__ , a__ : Optional[Any] = self.retriever._main_retrieve(A__ , A__ ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : Optional[int] , A__ : List[Any] , A__ : List[Any] , A__ : str , A__ : Any=None ) -> Optional[Any]: '''simple docstring''' if index is not None and index.is_initialized() and len(A__ ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : List[str] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(A__ , A__ , A__ , A__ ) for worker in self.retrieval_workers ] ) def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: '''simple docstring''' logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[int] , A__ : int ) -> Dict: '''simple docstring''' if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. a__ : List[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] a__ , a__ : Tuple = ray.get(random_worker.retrieve.remote(A__ , A__ ) ) else: a__ , a__ : int = self._main_retrieve(A__ , A__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[Any] , A__ : Any=None , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return super(A__ , cls ).get_tokenizers(A__ , A__ , **A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[int] , A__ : Union[str, Any] , A__ : Union[str, Any]=None , **A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Dict = kwargs.pop('''config''' , A__ ) or RagConfig.from_pretrained(A__ , **A__ ) a__ : Dict = RagTokenizer.from_pretrained(A__ , config=A__ ) a__ : str = rag_tokenizer.question_encoder a__ : List[str] = rag_tokenizer.generator if indexed_dataset is not None: a__ : List[Any] = '''custom''' a__ : List[Any] = CustomHFIndex(config.retrieval_vector_size , A__ ) else: a__ : Optional[Any] = cls._build_index(A__ ) return cls( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , retrieval_workers=A__ , index=A__ , )
688
1
'''simple docstring''' def __a ( lowerCAmelCase__ : int ): if number > 0: raise ValueError('''input must be a negative integer''' ) a__ : str = len(bin(lowerCAmelCase__ )[3:] ) a__ : str = bin(abs(lowerCAmelCase__ ) - (1 << binary_number_length) )[3:] a__ : Tuple = ( ( '''1''' + '''0''' * (binary_number_length - len(lowerCAmelCase__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
688
'''simple docstring''' def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): a__ : List[str] = len(lowerCAmelCase__ ) a__ : int = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): a__ : Dict = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
688
1
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class lowerCAmelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = StableDiffusionPanoramaPipeline __UpperCamelCase = TEXT_TO_IMAGE_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_BATCH_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS __UpperCamelCase = TEXT_TO_IMAGE_IMAGE_PARAMS def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' torch.manual_seed(0 ) a__ : Tuple = UNetaDConditionModel( block_out_channels=(3_2, 6_4) , layers_per_block=1 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=3_2 , ) a__ : List[str] = DDIMScheduler() torch.manual_seed(0 ) a__ : Union[str, Any] = AutoencoderKL( block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) a__ : Union[str, Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=3_2 , intermediate_size=3_7 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_0_0_0 , ) a__ : Union[str, Any] = CLIPTextModel(A__ ) a__ : Dict = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) a__ : List[Any] = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __lowerCAmelCase ( self : str , A__ : List[str] , A__ : Optional[int]=0 ) -> Optional[Any]: '''simple docstring''' a__ : Optional[int] = torch.manual_seed(A__ ) a__ : Any = { '''prompt''': '''a photo of the dolomites''', '''generator''': generator, # Setting height and width to None to prevent OOMs on CPU. '''height''': None, '''width''': None, '''num_inference_steps''': 1, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self : Any ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] = '''cpu''' # ensure determinism for the device-dependent torch.Generator a__ : str = self.get_dummy_components() a__ : Any = StableDiffusionPanoramaPipeline(**A__ ) a__ : Optional[int] = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) a__ : Any = self.get_dummy_inputs(A__ ) a__ : Optional[Any] = sd_pipe(**A__ ).images a__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) a__ : Tuple = np.array([0.6_186, 0.5_374, 0.4_915, 0.4_135, 0.4_114, 0.4_563, 0.5_128, 0.4_977, 0.4_757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCAmelCase ( self : Optional[Any] ) -> Any: '''simple docstring''' super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def __lowerCAmelCase ( self : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25E-3 ) def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' a__ : Tuple = '''cpu''' # ensure determinism for the device-dependent torch.Generator a__ : Dict = self.get_dummy_components() a__ : Tuple = StableDiffusionPanoramaPipeline(**A__ ) a__ : Optional[int] = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) a__ : int = self.get_dummy_inputs(A__ ) a__ : List[str] = '''french fries''' a__ : Tuple = sd_pipe(**A__ , negative_prompt=A__ ) a__ : List[str] = output.images a__ : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) a__ : Any = np.array([0.6_187, 0.5_375, 0.4_915, 0.4_136, 0.4_114, 0.4_563, 0.5_128, 0.4_976, 0.4_757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCAmelCase ( self : Any ) -> Union[str, Any]: '''simple docstring''' a__ : List[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator a__ : Optional[Any] = self.get_dummy_components() a__ : Optional[int] = StableDiffusionPanoramaPipeline(**A__ ) a__ : Tuple = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) a__ : Optional[Any] = self.get_dummy_inputs(A__ ) a__ : str = sd_pipe(**A__ , view_batch_size=2 ) a__ : str = output.images a__ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) a__ : Any = np.array([0.6_187, 0.5_375, 0.4_915, 0.4_136, 0.4_114, 0.4_563, 0.5_128, 0.4_976, 0.4_757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCAmelCase ( self : Union[str, Any] ) -> str: '''simple docstring''' a__ : Optional[int] = '''cpu''' # ensure determinism for the device-dependent torch.Generator a__ : Union[str, Any] = self.get_dummy_components() a__ : List[Any] = EulerAncestralDiscreteScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' ) a__ : Any = StableDiffusionPanoramaPipeline(**A__ ) a__ : int = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) a__ : str = self.get_dummy_inputs(A__ ) a__ : List[str] = sd_pipe(**A__ ).images a__ : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) a__ : Optional[Any] = np.array([0.4_024, 0.6_510, 0.4_901, 0.5_378, 0.5_813, 0.5_622, 0.4_795, 0.4_467, 0.4_952] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def __lowerCAmelCase ( self : Optional[int] ) -> List[Any]: '''simple docstring''' a__ : int = '''cpu''' # ensure determinism for the device-dependent torch.Generator a__ : List[Any] = self.get_dummy_components() a__ : Dict = PNDMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , skip_prk_steps=A__ ) a__ : Dict = StableDiffusionPanoramaPipeline(**A__ ) a__ : Tuple = sd_pipe.to(A__ ) sd_pipe.set_progress_bar_config(disable=A__ ) a__ : Any = self.get_dummy_inputs(A__ ) a__ : Optional[int] = sd_pipe(**A__ ).images a__ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 6_4, 6_4, 3) a__ : Dict = np.array([0.6_391, 0.6_291, 0.4_861, 0.5_134, 0.5_552, 0.4_578, 0.5_032, 0.5_023, 0.4_539] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowerCAmelCase ( self : Tuple , A__ : Optional[int]=0 ) -> Dict: '''simple docstring''' a__ : Any = torch.manual_seed(A__ ) a__ : Optional[Any] = { '''prompt''': '''a photo of the dolomites''', '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : str = '''stabilityai/stable-diffusion-2-base''' a__ : Optional[int] = DDIMScheduler.from_pretrained(A__ , subfolder='''scheduler''' ) a__ : Optional[Any] = StableDiffusionPanoramaPipeline.from_pretrained(A__ , scheduler=A__ , safety_checker=A__ ) pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) pipe.enable_attention_slicing() a__ : Dict = self.get_inputs() a__ : Any = pipe(**A__ ).images a__ : str = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 2_0_4_8, 3) a__ : int = np.array( [ 0.36_968_392, 0.27_025_372, 0.32_446_766, 0.28_379_387, 0.36_363_274, 0.30_733_347, 0.27_100_027, 0.27_054_125, 0.25_536_096, ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-2 def __lowerCAmelCase ( self : List[str] ) -> List[Any]: '''simple docstring''' a__ : Optional[Any] = StableDiffusionPanoramaPipeline.from_pretrained( '''stabilityai/stable-diffusion-2-base''' , safety_checker=A__ ) a__ : Union[str, Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) pipe.enable_attention_slicing() a__ : Optional[Any] = self.get_inputs() a__ : Dict = pipe(**A__ ).images a__ : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_1_2, 2_0_4_8, 3) a__ : List[Any] = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def __lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' a__ : List[str] = 0 def callback_fn(A__ : int , A__ : int , A__ : torch.FloatTensor ) -> None: a__ : Optional[Any] = True nonlocal number_of_steps number_of_steps += 1 if step == 1: a__ : List[str] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 6_4, 2_5_6) a__ : Optional[Any] = latents[0, -3:, -3:, -1] a__ : str = np.array( [ 0.18_681_869, 0.33_907_816, 0.5_361_276, 0.14_432_865, -0.02_856_611, -0.73_941_123, 0.23_397_987, 0.47_322_682, -0.37_823_164, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: a__ : Dict = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 6_4, 2_5_6) a__ : Optional[Any] = latents[0, -3:, -3:, -1] a__ : int = np.array( [ 0.18_539_645, 0.33_987_248, 0.5_378_559, 0.14_437_142, -0.02_455_261, -0.7_338_317, 0.23_990_755, 0.47_356_272, -0.3_786_505, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 a__ : Union[str, Any] = False a__ : Union[str, Any] = '''stabilityai/stable-diffusion-2-base''' a__ : Optional[Any] = DDIMScheduler.from_pretrained(A__ , subfolder='''scheduler''' ) a__ : List[Any] = StableDiffusionPanoramaPipeline.from_pretrained(A__ , scheduler=A__ , safety_checker=A__ ) a__ : str = pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) pipe.enable_attention_slicing() a__ : Union[str, Any] = self.get_inputs() pipe(**A__ , callback=A__ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowerCAmelCase ( self : str ) -> List[str]: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() a__ : Union[str, Any] = '''stabilityai/stable-diffusion-2-base''' a__ : Tuple = DDIMScheduler.from_pretrained(A__ , subfolder='''scheduler''' ) a__ : int = StableDiffusionPanoramaPipeline.from_pretrained(A__ , scheduler=A__ , safety_checker=A__ ) a__ : Any = pipe.to(A__ ) pipe.set_progress_bar_config(disable=A__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() a__ : Optional[int] = self.get_inputs() a__ : Dict = pipe(**A__ ) a__ : int = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 1_0**9
688
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "swin2sr" __UpperCamelCase = { "hidden_size": "embed_dim", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] , A__ : int=6_4 , A__ : List[Any]=1 , A__ : List[Any]=3 , A__ : Any=1_8_0 , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Dict=8 , A__ : Any=2.0 , A__ : Optional[int]=True , A__ : Union[str, Any]=0.0 , A__ : Union[str, Any]=0.0 , A__ : List[str]=0.1 , A__ : Any="gelu" , A__ : Tuple=False , A__ : Optional[int]=0.02 , A__ : List[Any]=1E-5 , A__ : Any=2 , A__ : Union[str, Any]=1.0 , A__ : Dict="1conv" , A__ : Optional[Any]="pixelshuffle" , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : List[str] = image_size a__ : Optional[Any] = patch_size a__ : Dict = num_channels a__ : Optional[int] = embed_dim a__ : int = depths a__ : Optional[int] = len(A__ ) a__ : Dict = num_heads a__ : List[Any] = window_size a__ : Optional[int] = mlp_ratio a__ : Optional[int] = qkv_bias a__ : Union[str, Any] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Union[str, Any] = drop_path_rate a__ : int = hidden_act a__ : int = use_absolute_embeddings a__ : Dict = layer_norm_eps a__ : List[str] = initializer_range a__ : List[Any] = upscale a__ : List[Any] = img_range a__ : Optional[int] = resi_connection a__ : int = upsampler
688
1
'''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 lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' a__ : List[Any] = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' ) a__ : Any = AutoTokenizer.from_pretrained('''google/mt5-small''' ) a__ : List[Any] = tokenizer('''Hello there''' , return_tensors='''np''' ).input_ids a__ : str = tokenizer('''Hi I am''' , return_tensors='''np''' ).input_ids a__ : Union[str, Any] = shift_tokens_right(A__ , model.config.pad_token_id , model.config.decoder_start_token_id ) a__ : str = model(A__ , decoder_input_ids=A__ ).logits a__ : int = optax.softmax_cross_entropy(A__ , onehot(A__ , logits.shape[-1] ) ).mean() a__ : List[Any] = -(labels.shape[-1] * loss.item()) a__ : Union[str, Any] = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
688
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : int = 0 def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[Any] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[Any] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[int] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict() config_dict.pop('''image_processor_type''' ) a__ : Union[str, Any] = CLIPImageProcessor(**A__ ) # save in new folder model_config.save_pretrained(A__ ) config.save_pretrained(A__ ) a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ ) # make sure private variable is not incorrectly saved a__ : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''clip-base is not a local folder and is not a valid model identifier''' ): a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' with self.assertRaises(A__ ): a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoImageProcessor.register(A__ , A__ ) with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[str] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = CustomImageProcessor.from_pretrained(A__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = True try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # If remote code is not set, the default is to use local a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. a__ : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub a__ : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(A__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
688
1
'''simple docstring''' __SCREAMING_SNAKE_CASE = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } def __a ( lowerCAmelCase__ : dict , lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[Any] ): a__ : int = set() # keep track of all the paths to be checked a__ : Optional[int] = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue a__ : List[Any] = queue.pop(0 ) # get the last node from the path a__ : int = path[-1] if node not in explored: a__ : Optional[Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: a__ : Optional[int] = list(lowerCAmelCase__ ) new_path.append(lowerCAmelCase__ ) queue.append(lowerCAmelCase__ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(lowerCAmelCase__ ) # in case there's no path between the 2 nodes return [] def __a ( lowerCAmelCase__ : dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : str ): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 a__ : Union[str, Any] = [start] a__ : Tuple = set(lowerCAmelCase__ ) # Keep tab on distances from `start` node. a__ : Optional[Any] = {start: 0, target: -1} while queue: a__ : Optional[int] = queue.pop(0 ) if node == target: a__ : Optional[Any] = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(lowerCAmelCase__ ) queue.append(lowerCAmelCase__ ) a__ : Union[str, Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, 'G', 'D')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, 'G', 'D')) # returns 4
688
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version __SCREAMING_SNAKE_CASE = get_logger(__name__) class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = "dummy_data" __UpperCamelCase = "datasets" __UpperCamelCase = False def __init__( self : Any , A__ : str , A__ : str , A__ : Union[Version, str] , A__ : Optional[str] = None , A__ : bool = False , A__ : bool = True , A__ : Optional[List[Callable]] = None , ) -> int: '''simple docstring''' a__ : Tuple = 0 a__ : Any = dataset_name a__ : int = cache_dir a__ : str = use_local_dummy_data a__ : List[str] = config # download_callbacks take a single url as input a__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root a__ : str = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general a__ : Optional[Any] = str(A__ ) # to be downloaded a__ : Tuple = None a__ : Tuple = None @property def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' if self._dummy_file is None: a__ : Dict = self.download_dummy_data() return self._dummy_file @property def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('''dummy''' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('''dummy''' , self.version_name ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : int = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) a__ : str = cached_path( A__ , cache_dir=self.cache_dir , extract_compressed_file=A__ , force_extract=A__ ) return os.path.join(A__ , self.dummy_file_name ) @property def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self._bucket_url is None: a__ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) ) return self._bucket_url @property def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , *A__ : int ) -> Union[str, Any]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested a__ : Tuple = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned a__ : Union[str, Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(A__ , A__ ): return self.create_dummy_data_dict(A__ , A__ ) elif isinstance(A__ , (list, tuple) ): return self.create_dummy_data_list(A__ , A__ ) else: return self.create_dummy_data_single(A__ , A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Any , *A__ : int ) -> Any: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Any , A__ : Optional[int] , A__ : Optional[Any] ) -> int: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , *A__ : List[Any] , **A__ : str ) -> Optional[Any]: '''simple docstring''' return path def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' return {} def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[str] ) -> Any: '''simple docstring''' a__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A__ , A__ ): for single_url in single_urls: download_callback(A__ ) else: a__ : Dict = single_urls download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A__ , A__ ): a__ : Optional[int] = [os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) for x in single_urls] else: a__ : Optional[Any] = single_urls a__ : Tuple = os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) a__ : List[str] = value # make sure that values are unique if all(isinstance(A__ , A__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique a__ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : str = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one a__ : Union[str, Any] = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , A__ ) ) for url in data_url ) a__ : Optional[Any] = all( url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): a__ : Dict = [data_url[0]] * len(A__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Optional[int] = os.path.join(A__ , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) ) dummy_data_list.append(A__ ) return dummy_data_list def __lowerCAmelCase ( self : Dict , A__ : Dict , A__ : str ) -> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Union[str, Any] = os.path.join(A__ , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) ) if os.path.exists(A__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' pass def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: '''simple docstring''' pass def __lowerCAmelCase ( self : Any , A__ : Tuple ) -> Any: '''simple docstring''' def _iter_archive_members(A__ : str ): # this preserves the order of the members inside the ZIP archive a__ : Dict = Path(self.dummy_file ).parent a__ : Tuple = path.relative_to(A__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: a__ : Optional[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A__ ) a__ : str = Path(A__ ) a__ : Optional[Any] = _iter_archive_members(A__ ) if self.use_local_dummy_data else path.rglob('''*''' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ): yield file_path.relative_to(A__ ).as_posix(), file_path.open('''rb''' ) def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> Tuple: '''simple docstring''' if not isinstance(A__ , A__ ): a__ : int = [paths] for path in paths: if os.path.isfile(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): return yield path else: for dirpath, dirnames, filenames in os.walk(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): continue dirnames.sort() for filename in sorted(A__ ): if filename.startswith(('''.''', '''__''') ): continue yield os.path.join(A__ , A__ )
688
1
'''simple docstring''' import pytest import datasets # Import fixture modules as plugins __SCREAMING_SNAKE_CASE = ['tests.fixtures.files', 'tests.fixtures.hub', 'tests.fixtures.fsspec'] def __a ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Union[str, Any] ): # Mark tests as "unit" by default if not marked as "integration" (or already marked as "unit") for item in items: if any(marker in item.keywords for marker in ['''integration''', '''unit'''] ): continue item.add_marker(pytest.mark.unit ) def __a ( lowerCAmelCase__ : Dict ): config.addinivalue_line('''markers''' , '''torchaudio_latest: mark test to run with torchaudio>=0.12''' ) @pytest.fixture(autouse=lowerCAmelCase__ ) def __a ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any ): # test_hf_cache_home = tmp_path_factory.mktemp("cache") # TODO: why a cache dir per test function does not work? a__ : Optional[Any] = tmp_path_factory.getbasetemp() / '''cache''' a__ : List[Any] = test_hf_cache_home / '''datasets''' a__ : Optional[int] = test_hf_cache_home / '''metrics''' a__ : Dict = test_hf_cache_home / '''modules''' monkeypatch.setattr('''datasets.config.HF_DATASETS_CACHE''' , str(lowerCAmelCase__ ) ) monkeypatch.setattr('''datasets.config.HF_METRICS_CACHE''' , str(lowerCAmelCase__ ) ) monkeypatch.setattr('''datasets.config.HF_MODULES_CACHE''' , str(lowerCAmelCase__ ) ) a__ : List[str] = test_hf_datasets_cache / '''downloads''' monkeypatch.setattr('''datasets.config.DOWNLOADED_DATASETS_PATH''' , str(lowerCAmelCase__ ) ) a__ : str = test_hf_datasets_cache / '''downloads''' / '''extracted''' monkeypatch.setattr('''datasets.config.EXTRACTED_DATASETS_PATH''' , str(lowerCAmelCase__ ) ) @pytest.fixture(autouse=lowerCAmelCase__ , scope='''session''' ) def __a ( ): datasets.disable_progress_bar() @pytest.fixture(autouse=lowerCAmelCase__ ) def __a ( lowerCAmelCase__ : Optional[int] ): # don't take tests into account when counting downloads monkeypatch.setattr('''datasets.config.HF_UPDATE_DOWNLOAD_COUNTS''' , lowerCAmelCase__ ) @pytest.fixture def __a ( lowerCAmelCase__ : Tuple ): # Required to suppress RemovedIn20Warning when feature(s) are not compatible with SQLAlchemy 2.0 # To be removed once SQLAlchemy 2.0 supported monkeypatch.setattr('''sqlalchemy.util.deprecations.SILENCE_UBER_WARNING''' , lowerCAmelCase__ )
688
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = LxmertTokenizer __UpperCamelCase = LxmertTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' super().setUp() a__ : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : int , A__ : int ) -> int: '''simple docstring''' a__ : List[Any] = '''UNwant\u00E9d,running''' a__ : Optional[int] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ : Optional[int] = self.tokenizer_class(self.vocab_file ) a__ : List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [7, 4, 5, 1_0, 8, 9] ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__ : Union[str, Any] = self.get_tokenizer() a__ : Union[str, Any] = self.get_rust_tokenizer() a__ : str = '''I was born in 92000, and this is falsé.''' a__ : Tuple = tokenizer.tokenize(A__ ) a__ : Tuple = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) a__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : str = tokenizer.encode(A__ ) a__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ )
688
1
'''simple docstring''' from __future__ import annotations import os from typing import Any import requests __SCREAMING_SNAKE_CASE = 'https://api.github.com' # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user __SCREAMING_SNAKE_CASE = BASE_URL + '/user' # https://github.com/settings/tokens __SCREAMING_SNAKE_CASE = os.environ.get('USER_TOKEN', '') def __a ( lowerCAmelCase__ : str ): a__ : List[Any] = { '''Authorization''': F'token {auth_token}', '''Accept''': '''application/vnd.github.v3+json''', } return requests.get(lowerCAmelCase__ , headers=lowerCAmelCase__ ).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(f'{key}: {value}') else: raise ValueError('\'USER_TOKEN\' field cannot be empty.')
688
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file a__ : Dict = TapasConfig.from_json_file(lowerCAmelCase__ ) # set absolute/relative position embeddings parameter a__ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": a__ : Optional[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WTQ": # run_task_main.py hparams a__ : List[str] = 4 a__ : Optional[int] = True # hparam_utils.py hparams a__ : List[Any] = 0.664694 a__ : List[Any] = 0.207951 a__ : Union[str, Any] = 0.121194 a__ : Optional[Any] = True a__ : Optional[int] = True a__ : List[str] = False a__ : Union[str, Any] = 0.0352513 a__ : Any = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams a__ : Tuple = 4 a__ : Dict = False # hparam_utils.py hparams a__ : str = 36.4519 a__ : str = 0.903421 a__ : Optional[Any] = 222.088 a__ : Dict = True a__ : Dict = True a__ : Dict = True a__ : str = 0.763141 a__ : List[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "TABFACT": a__ : List[str] = TapasForSequenceClassification(config=lowerCAmelCase__ ) elif task == "MLM": a__ : Tuple = TapasForMaskedLM(config=lowerCAmelCase__ ) elif task == "INTERMEDIATE_PRETRAINING": a__ : List[str] = TapasModel(config=lowerCAmelCase__ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase__ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) a__ : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase__ ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
688
1
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __a ( lowerCAmelCase__ : List[Any] ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ): a__ : Dict = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue a__ : Any = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) a__ : int = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) a__ : Optional[Any] = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) a__ : Dict = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) a__ : List[str] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) a__ : List[Any] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) a__ : str = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) a__ : List[Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) a__ : List[Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) a__ : str = key.replace('''image_encoder.module''' , '''flava.image_model''' ) a__ : Dict = key.replace('''text_encoder.module''' , '''flava.text_model''' ) a__ : List[Any] = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) a__ : List[str] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) a__ : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' ) a__ : Any = key.replace('''image_projection''' , '''flava.image_projection''' ) a__ : Any = value.float() for key, value in codebook_state_dict.items(): a__ : List[str] = value return upgrade @torch.no_grad() def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict=None ): if config_path is not None: a__ : Tuple = FlavaConfig.from_pretrained(lowerCAmelCase__ ) else: a__ : Optional[int] = FlavaConfig() a__ : List[Any] = FlavaForPreTraining(lowerCAmelCase__ ).eval() a__ : Optional[int] = convert_dalle_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , save_checkpoint=lowerCAmelCase__ ) if os.path.exists(lowerCAmelCase__ ): a__ : List[str] = torch.load(lowerCAmelCase__ , map_location='''cpu''' ) else: a__ : Dict = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' ) a__ : List[Any] = upgrade_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) a__ : Any = hf_model.state_dict() a__ : Optional[Any] = count_parameters(lowerCAmelCase__ ) a__ : int = count_parameters(lowerCAmelCase__ ) + count_parameters(lowerCAmelCase__ ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
688
'''simple docstring''' 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_fnet import FNetTokenizer else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } __SCREAMING_SNAKE_CASE = { 'google/fnet-base': 5_1_2, 'google/fnet-large': 5_1_2, } __SCREAMING_SNAKE_CASE = '▁' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "token_type_ids"] __UpperCamelCase = FNetTokenizer def __init__( self : Any , A__ : Any=None , A__ : int=None , A__ : List[str]=False , A__ : int=True , A__ : str=True , A__ : List[Any]="<unk>" , A__ : Dict="[SEP]" , A__ : List[str]="<pad>" , A__ : Union[str, Any]="[CLS]" , A__ : Dict="[MASK]" , **A__ : Tuple , ) -> List[str]: '''simple docstring''' a__ : Optional[int] = ( AddedToken(A__ , lstrip=A__ , rstrip=A__ , normalized=A__ ) if isinstance(A__ , A__ ) else mask_token ) super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , **A__ , ) a__ : Optional[Any] = do_lower_case a__ : Dict = remove_space a__ : List[Any] = keep_accents a__ : Optional[Any] = vocab_file a__ : Any = False if not self.vocab_file else True def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : List[Any] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Dict = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : Tuple , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(A__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return a__ : Union[str, Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ): copyfile(self.vocab_file , A__ ) return (out_vocab_file,)
688
1
'''simple docstring''' import math from numpy import inf from scipy.integrate import quad def __a ( lowerCAmelCase__ : float ): if num <= 0: raise ValueError('''math domain error''' ) return quad(lowerCAmelCase__ , 0 , lowerCAmelCase__ , args=(lowerCAmelCase__) )[0] def __a ( lowerCAmelCase__ : float , lowerCAmelCase__ : float ): return math.pow(lowerCAmelCase__ , z - 1 ) * math.exp(-x ) if __name__ == "__main__": from doctest import testmod testmod()
688
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { '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' ), }, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': 5_1_2, 'distilbert-base-uncased-distilled-squad': 5_1_2, 'distilbert-base-cased': 5_1_2, 'distilbert-base-cased-distilled-squad': 5_1_2, 'distilbert-base-german-cased': 5_1_2, 'distilbert-base-multilingual-cased': 5_1_2, } __SCREAMING_SNAKE_CASE = { '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 lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = DistilBertTokenizer def __init__( self : str , A__ : Optional[Any]=None , A__ : Any=None , A__ : Tuple=True , A__ : List[Any]="[UNK]" , A__ : List[str]="[SEP]" , A__ : Tuple="[PAD]" , A__ : Optional[int]="[CLS]" , A__ : Union[str, Any]="[MASK]" , A__ : List[str]=True , A__ : Any=None , **A__ : int , ) -> str: '''simple docstring''' super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , tokenize_chinese_chars=A__ , strip_accents=A__ , **A__ , ) a__ : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , A__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , A__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , A__ ) != tokenize_chinese_chars ): a__ : int = getattr(A__ , normalizer_state.pop('''type''' ) ) a__ : List[Any] = do_lower_case a__ : str = strip_accents a__ : List[str] = tokenize_chinese_chars a__ : Dict = normalizer_class(**A__ ) a__ : List[Any] = do_lower_case def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Dict=None ) -> List[str]: '''simple docstring''' a__ : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : int , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : List[str] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : str , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' a__ : int = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
688
1
'''simple docstring''' import hashlib import unittest from typing import Dict import numpy as np from transformers import ( MODEL_FOR_MASK_GENERATION_MAPPING, TF_MODEL_FOR_MASK_GENERATION_MAPPING, is_vision_available, pipeline, ) from transformers.pipelines import MaskGenerationPipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class lowerCAmelCase__ : """simple docstring""" @staticmethod def __lowerCAmelCase ( *A__ : Dict , **A__ : Dict ) -> Optional[int]: '''simple docstring''' pass def __a ( lowerCAmelCase__ : Image ): a__ : Optional[Any] = hashlib.mda(image.tobytes() ) return m.hexdigest()[:10] def __a ( lowerCAmelCase__ : Image ): a__ : List[str] = np.array(lowerCAmelCase__ ) a__ : List[Any] = npimg.shape return {"hash": hashimage(lowerCAmelCase__ ), "shape": shape} @is_pipeline_test @require_vision @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" __UpperCamelCase = dict( (list(MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if MODEL_FOR_MASK_GENERATION_MAPPING else []) ) __UpperCamelCase = dict( (list(TF_MODEL_FOR_MASK_GENERATION_MAPPING.items() ) if TF_MODEL_FOR_MASK_GENERATION_MAPPING else []) ) def __lowerCAmelCase ( self : Tuple , A__ : Optional[Any] , A__ : List[Any] , A__ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' a__ : Optional[Any] = MaskGenerationPipeline(model=A__ , image_processor=A__ ) return image_segmenter, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def __lowerCAmelCase ( self : List[str] , A__ : Optional[Any] , A__ : str ) -> Tuple: '''simple docstring''' pass @require_tf @unittest.skip('''Image segmentation not implemented in TF''' ) def __lowerCAmelCase ( self : List[str] ) -> Tuple: '''simple docstring''' pass @slow @require_torch def __lowerCAmelCase ( self : int ) -> Tuple: '''simple docstring''' a__ : Optional[int] = pipeline('''mask-generation''' , model='''facebook/sam-vit-huge''' ) a__ : Tuple = image_segmenter('''http://images.cocodataset.org/val2017/000000039769.jpg''' , points_per_batch=2_5_6 ) # Shortening by hashing a__ : Tuple = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(A__ ), "scores": outputs["scores"][i]}] # fmt: off self.assertEqual( nested_simplify(A__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 1.021}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 1.0_053}, {'''mask''': {'''hash''': '''e2d0b7a0b7''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_967}, {'''mask''': {'''hash''': '''453c7844bd''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.993}, {'''mask''': {'''hash''': '''3d44f2926d''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_909}, {'''mask''': {'''hash''': '''64033ddc3f''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_879}, {'''mask''': {'''hash''': '''801064ff79''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_834}, {'''mask''': {'''hash''': '''6172f276ef''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_716}, {'''mask''': {'''hash''': '''b49e60e084''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_612}, {'''mask''': {'''hash''': '''a811e775fd''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_599}, {'''mask''': {'''hash''': '''a6a8ebcf4b''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_552}, {'''mask''': {'''hash''': '''9d8257e080''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_532}, {'''mask''': {'''hash''': '''32de6454a8''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_516}, {'''mask''': {'''hash''': '''af3d4af2c8''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_499}, {'''mask''': {'''hash''': '''3c6db475fb''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_483}, {'''mask''': {'''hash''': '''c290813fb9''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_464}, {'''mask''': {'''hash''': '''b6f0b8f606''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''92ce16bfdf''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.943}, {'''mask''': {'''hash''': '''c749b25868''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_408}, {'''mask''': {'''hash''': '''efb6cab859''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_335}, {'''mask''': {'''hash''': '''1ff2eafb30''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_326}, {'''mask''': {'''hash''': '''788b798e24''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.9_262}, {'''mask''': {'''hash''': '''abea804f0e''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.8_999}, {'''mask''': {'''hash''': '''7b9e8ddb73''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.8_986}, {'''mask''': {'''hash''': '''cd24047c8a''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.8_984}, {'''mask''': {'''hash''': '''6943e6bcbd''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.8_873}, {'''mask''': {'''hash''': '''b5f47c9191''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 0.8_871} ] , ) # fmt: on @require_torch @slow def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' a__ : Any = '''facebook/sam-vit-huge''' a__ : Optional[Any] = pipeline('''mask-generation''' , model=A__ ) a__ : Tuple = image_segmenter( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , pred_iou_thresh=1 , points_per_batch=2_5_6 ) # Shortening by hashing a__ : List[Any] = [] for i, o in enumerate(outputs['''masks'''] ): new_outupt += [{"mask": mask_to_test_readable(A__ ), "scores": outputs["scores"][i]}] self.assertEqual( nested_simplify(A__ , decimals=4 ) , [ {'''mask''': {'''hash''': '''115ad19f5f''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 1.0_444}, {'''mask''': {'''hash''': '''6affa964c6''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 1.0_210}, {'''mask''': {'''hash''': '''dfe28a0388''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 1.0_167}, {'''mask''': {'''hash''': '''c0a5f4a318''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 1.0_132}, {'''mask''': {'''hash''': '''fe8065c197''', '''shape''': (4_8_0, 6_4_0)}, '''scores''': 1.0_053}, ] , )
688
'''simple docstring''' from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __SCREAMING_SNAKE_CASE = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right __SCREAMING_SNAKE_CASE = tuple[int, int] class lowerCAmelCase__ : """simple docstring""" def __init__( self : str , A__ : int , A__ : int , A__ : int , A__ : int , A__ : int , A__ : Node | None , ) -> None: '''simple docstring''' a__ : Optional[int] = pos_x a__ : str = pos_y a__ : Optional[int] = (pos_y, pos_x) a__ : List[str] = goal_x a__ : Any = goal_y a__ : Any = g_cost a__ : Optional[int] = parent a__ : Union[str, Any] = self.calculate_heuristic() a__ : List[Any] = self.g_cost + self.h_cost def __lowerCAmelCase ( self : Union[str, Any] ) -> float: '''simple docstring''' a__ : List[str] = self.pos_x - self.goal_x a__ : List[str] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(A__ ) + abs(A__ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : List[Any] , A__ : Node ) -> bool: '''simple docstring''' return self.f_cost < other.f_cost class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] , A__ : TPosition , A__ : TPosition ) -> Optional[Any]: '''simple docstring''' a__ : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , A__ ) a__ : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , A__ ) a__ : Dict = [self.start] a__ : list[Node] = [] a__ : str = False def __lowerCAmelCase ( self : List[str] ) -> list[TPosition]: '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() a__ : Dict = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(A__ ) self.closed_nodes.append(A__ ) a__ : List[Any] = self.get_successors(A__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[int] = self.open_nodes.pop(self.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(A__ ) else: self.open_nodes.append(A__ ) return [self.start.pos] def __lowerCAmelCase ( self : Optional[Any] , A__ : Node ) -> list[Node]: '''simple docstring''' a__ : Optional[int] = [] for action in delta: a__ : List[Any] = parent.pos_x + action[1] a__ : Tuple = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(A__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( A__ , A__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , A__ , ) ) return successors def __lowerCAmelCase ( self : List[Any] , A__ : Node | None ) -> list[TPosition]: '''simple docstring''' a__ : Union[str, Any] = node a__ : Optional[Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) a__ : Any = current_node.parent path.reverse() return path class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , A__ : TPosition , A__ : TPosition ) -> None: '''simple docstring''' a__ : str = AStar(A__ , A__ ) a__ : Optional[int] = AStar(A__ , A__ ) a__ : List[str] = False def __lowerCAmelCase ( self : Tuple ) -> list[TPosition]: '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() a__ : int = self.fwd_astar.open_nodes.pop(0 ) a__ : List[Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( A__ , A__ ) self.fwd_astar.closed_nodes.append(A__ ) self.bwd_astar.closed_nodes.append(A__ ) a__ : Tuple = current_bwd_node a__ : Optional[int] = current_fwd_node a__ : Optional[int] = { self.fwd_astar: self.fwd_astar.get_successors(A__ ), self.bwd_astar: self.bwd_astar.get_successors(A__ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[Any] = astar.open_nodes.pop( astar.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(A__ ) else: astar.open_nodes.append(A__ ) return [self.fwd_astar.start.pos] def __lowerCAmelCase ( self : List[str] , A__ : Node , A__ : Node ) -> list[TPosition]: '''simple docstring''' a__ : str = self.fwd_astar.retrace_path(A__ ) a__ : List[str] = self.bwd_astar.retrace_path(A__ ) bwd_path.pop() bwd_path.reverse() a__ : Optional[int] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] __SCREAMING_SNAKE_CASE = (0, 0) __SCREAMING_SNAKE_CASE = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = AStar(init, goal) __SCREAMING_SNAKE_CASE = a_star.search() __SCREAMING_SNAKE_CASE = time.time() - start_time print(f'AStar execution time = {end_time:f} seconds') __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = BidirectionalAStar(init, goal) __SCREAMING_SNAKE_CASE = time.time() - bd_start_time print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
688
1
'''simple docstring''' from argparse import ArgumentParser from datasets.commands.convert import ConvertCommand from datasets.commands.dummy_data import DummyDataCommand from datasets.commands.env import EnvironmentCommand from datasets.commands.run_beam import RunBeamCommand from datasets.commands.test import TestCommand from datasets.utils.logging import set_verbosity_info def __a ( lowerCAmelCase__ : Dict ): return {key.lstrip('''-''' ): value for key, value in zip(unknown_args[::2] , unknown_args[1::2] )} def __a ( ): a__ : int = ArgumentParser( '''HuggingFace Datasets CLI tool''' , usage='''datasets-cli <command> [<args>]''' , allow_abbrev=lowerCAmelCase__ ) a__ : List[Any] = parser.add_subparsers(help='''datasets-cli command helpers''' ) set_verbosity_info() # Register commands ConvertCommand.register_subcommand(lowerCAmelCase__ ) EnvironmentCommand.register_subcommand(lowerCAmelCase__ ) TestCommand.register_subcommand(lowerCAmelCase__ ) RunBeamCommand.register_subcommand(lowerCAmelCase__ ) DummyDataCommand.register_subcommand(lowerCAmelCase__ ) # Parse args a__ , a__ : Union[str, Any] = parser.parse_known_args() if not hasattr(lowerCAmelCase__ , '''func''' ): parser.print_help() exit(1 ) a__ : Optional[Any] = parse_unknown_args(lowerCAmelCase__ ) # Run a__ : int = args.func(lowerCAmelCase__ , **lowerCAmelCase__ ) service.run() if __name__ == "__main__": main()
688
'''simple docstring''' import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] ): # Construct model if gpta_config_file == "": a__ : Union[str, Any] = GPTaConfig() else: a__ : Dict = GPTaConfig.from_json_file(lowerCAmelCase__ ) a__ : Optional[int] = GPTaModel(lowerCAmelCase__ ) # Load weights from numpy load_tf_weights_in_gpta(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model a__ : int = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME a__ : Union[str, Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , lowerCAmelCase__ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--gpt2_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
688
1
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'facebook/wav2vec2-base-960h': 'https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json', # See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2 } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "wav2vec2" def __init__( self : Any , A__ : Dict=3_2 , A__ : Union[str, Any]=7_6_8 , A__ : Any=1_2 , A__ : List[Any]=1_2 , A__ : Tuple=3_0_7_2 , A__ : Dict="gelu" , A__ : Optional[int]=0.1 , A__ : Optional[int]=0.1 , A__ : Optional[int]=0.1 , A__ : Optional[int]=0.0 , A__ : Optional[int]=0.0 , A__ : List[Any]=0.1 , A__ : Any=0.1 , A__ : Dict=0.02 , A__ : str=1E-5 , A__ : Tuple="group" , A__ : Dict="gelu" , A__ : List[Any]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , A__ : Tuple=(5, 2, 2, 2, 2, 2, 2) , A__ : Tuple=(1_0, 3, 3, 3, 3, 2, 2) , A__ : List[str]=False , A__ : List[str]=1_2_8 , A__ : List[str]=1_6 , A__ : List[str]=False , A__ : str=True , A__ : str=0.05 , A__ : Optional[int]=1_0 , A__ : List[str]=2 , A__ : str=0.0 , A__ : int=1_0 , A__ : Dict=0 , A__ : List[str]=3_2_0 , A__ : Any=2 , A__ : int=0.1 , A__ : Optional[int]=1_0_0 , A__ : List[str]=2_5_6 , A__ : Union[str, Any]=2_5_6 , A__ : int=0.1 , A__ : Dict="sum" , A__ : Any=False , A__ : Optional[int]=False , A__ : List[Any]=2_5_6 , A__ : Any=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0) , A__ : Union[str, Any]=(5, 3, 3, 1, 1) , A__ : Union[str, Any]=(1, 2, 3, 1, 1) , A__ : Dict=5_1_2 , A__ : Union[str, Any]=0 , A__ : int=1 , A__ : Any=2 , A__ : Any=False , A__ : Tuple=3 , A__ : List[str]=2 , A__ : Tuple=3 , A__ : Dict=None , A__ : List[str]=None , **A__ : Optional[Any] , ) -> int: '''simple docstring''' super().__init__(**A__ , pad_token_id=A__ , bos_token_id=A__ , eos_token_id=A__ ) a__ : Optional[Any] = hidden_size a__ : Any = feat_extract_norm a__ : str = feat_extract_activation a__ : Tuple = list(A__ ) a__ : Tuple = list(A__ ) a__ : List[str] = list(A__ ) a__ : Any = conv_bias a__ : Dict = num_conv_pos_embeddings a__ : int = num_conv_pos_embedding_groups a__ : Optional[Any] = len(self.conv_dim ) a__ : str = num_hidden_layers a__ : Any = intermediate_size a__ : List[str] = hidden_act a__ : str = num_attention_heads a__ : int = hidden_dropout a__ : int = attention_dropout a__ : Union[str, Any] = activation_dropout a__ : Tuple = feat_proj_dropout a__ : Optional[Any] = final_dropout a__ : Optional[int] = layerdrop a__ : int = layer_norm_eps a__ : int = initializer_range a__ : List[Any] = vocab_size a__ : Dict = do_stable_layer_norm a__ : Dict = 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 a__ : int = apply_spec_augment a__ : Any = mask_time_prob a__ : List[Any] = mask_time_length a__ : int = mask_time_min_masks a__ : Optional[int] = mask_feature_prob a__ : Optional[int] = mask_feature_length a__ : List[Any] = mask_feature_min_masks # parameters for pretraining with codevector quantized representations a__ : int = num_codevectors_per_group a__ : Optional[int] = num_codevector_groups a__ : Dict = contrastive_logits_temperature a__ : List[str] = feat_quantizer_dropout a__ : Any = num_negatives a__ : Any = codevector_dim a__ : int = proj_codevector_dim a__ : Optional[int] = diversity_loss_weight # ctc loss a__ : List[str] = ctc_loss_reduction a__ : Optional[int] = ctc_zero_infinity # adapter a__ : Optional[int] = add_adapter a__ : Optional[Any] = adapter_kernel_size a__ : str = adapter_stride a__ : str = num_adapter_layers a__ : Any = output_hidden_size or hidden_size a__ : Any = adapter_attn_dim # SequenceClassification-specific parameter. Feel free to ignore for other classes. a__ : Union[str, Any] = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. a__ : List[str] = list(A__ ) a__ : str = list(A__ ) a__ : Optional[int] = list(A__ ) a__ : str = xvector_output_dim @property def __lowerCAmelCase ( self : str ) -> Dict: '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
688
'''simple docstring''' import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } __SCREAMING_SNAKE_CASE = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } __SCREAMING_SNAKE_CASE = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: __SCREAMING_SNAKE_CASE = reader.read() __SCREAMING_SNAKE_CASE = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): __SCREAMING_SNAKE_CASE = UNetaDModel(**config) else: __SCREAMING_SNAKE_CASE = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel __SCREAMING_SNAKE_CASE = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) __SCREAMING_SNAKE_CASE = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: __SCREAMING_SNAKE_CASE = config[key] del config[key] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['down_block_types']] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: __SCREAMING_SNAKE_CASE = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) __SCREAMING_SNAKE_CASE = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue __SCREAMING_SNAKE_CASE = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: __SCREAMING_SNAKE_CASE = param_value __SCREAMING_SNAKE_CASE = True if not has_changed: __SCREAMING_SNAKE_CASE = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
688
1
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ : """simple docstring""" def __init__( self : str ) -> Dict: '''simple docstring''' a__ : List[str] = False def __lowerCAmelCase ( self : Tuple , A__ : Optional[int] , A__ : Optional[Any] , A__ : List[str] , A__ : Tuple ) -> Optional[int]: '''simple docstring''' if not self.initialized: a__ : Optional[Any] = RagRetriever( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : Union[str, Any] = True def __lowerCAmelCase ( self : Tuple ) -> Tuple: '''simple docstring''' self.retriever.index.init_index() def __lowerCAmelCase ( self : List[Any] , A__ : List[Any] , A__ : Optional[int] ) -> List[Any]: '''simple docstring''' a__ , a__ : Optional[Any] = self.retriever._main_retrieve(A__ , A__ ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : Optional[int] , A__ : List[Any] , A__ : List[Any] , A__ : str , A__ : Any=None ) -> Optional[Any]: '''simple docstring''' if index is not None and index.is_initialized() and len(A__ ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : List[str] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(A__ , A__ , A__ , A__ ) for worker in self.retrieval_workers ] ) def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: '''simple docstring''' logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[int] , A__ : int ) -> Dict: '''simple docstring''' if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. a__ : List[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] a__ , a__ : Tuple = ray.get(random_worker.retrieve.remote(A__ , A__ ) ) else: a__ , a__ : int = self._main_retrieve(A__ , A__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[Any] , A__ : Any=None , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return super(A__ , cls ).get_tokenizers(A__ , A__ , **A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[int] , A__ : Union[str, Any] , A__ : Union[str, Any]=None , **A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Dict = kwargs.pop('''config''' , A__ ) or RagConfig.from_pretrained(A__ , **A__ ) a__ : Dict = RagTokenizer.from_pretrained(A__ , config=A__ ) a__ : str = rag_tokenizer.question_encoder a__ : List[str] = rag_tokenizer.generator if indexed_dataset is not None: a__ : List[Any] = '''custom''' a__ : List[Any] = CustomHFIndex(config.retrieval_vector_size , A__ ) else: a__ : Optional[Any] = cls._build_index(A__ ) return cls( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , retrieval_workers=A__ , index=A__ , )
688
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = (KDPMaDiscreteScheduler,) __UpperCamelCase = 10 def __lowerCAmelCase ( self : Optional[Any] , **A__ : Optional[int] ) -> int: '''simple docstring''' a__ : Optional[int] = { '''num_train_timesteps''': 1_1_0_0, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**A__ ) return config def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=A__ ) def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=A__ , beta_end=A__ ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A__ ) def __lowerCAmelCase ( self : str ) -> Optional[int]: '''simple docstring''' a__ : Any = self.scheduler_classes[0] a__ : str = self.get_scheduler_config(prediction_type='''v_prediction''' ) a__ : Dict = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : Tuple = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Dict = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : Optional[Any] = scheduler.scale_model_input(A__ , A__ ) a__ : Union[str, Any] = model(A__ , A__ ) a__ : List[str] = scheduler.step(A__ , A__ , A__ ) a__ : Optional[Any] = output.prev_sample a__ : Tuple = torch.sum(torch.abs(A__ ) ) a__ : Optional[int] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_4286_5017_0972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' if torch_device == "mps": return a__ : List[Any] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : Tuple = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : List[Any] = self.dummy_model() a__ : Any = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Any = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : str = scheduler.scale_model_input(A__ , A__ ) a__ : List[str] = model(A__ , A__ ) a__ : str = scheduler.step(A__ , A__ , A__ ) a__ : List[Any] = output.prev_sample a__ : Dict = torch.sum(torch.abs(A__ ) ) a__ : Optional[Any] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' if torch_device == "mps": return a__ : Optional[int] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : List[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps , device=A__ ) a__ : Union[str, Any] = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter.to(A__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: a__ : Optional[int] = scheduler.scale_model_input(A__ , A__ ) a__ : List[Any] = model(A__ , A__ ) a__ : Any = scheduler.step(A__ , A__ , A__ ) a__ : List[str] = output.prev_sample a__ : Any = torch.sum(torch.abs(A__ ) ) a__ : Union[str, Any] = torch.mean(torch.abs(A__ ) ) if str(A__ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
688
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'alibaba-damo/mgp-str-base': 'https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json', } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "mgp-str" def __init__( self : int , A__ : int=[3_2, 1_2_8] , A__ : Optional[int]=4 , A__ : int=3 , A__ : Any=2_7 , A__ : Dict=3_8 , A__ : Optional[Any]=5_0_2_5_7 , A__ : Tuple=3_0_5_2_2 , A__ : List[Any]=7_6_8 , A__ : int=1_2 , A__ : int=1_2 , A__ : Dict=4.0 , A__ : Tuple=True , A__ : Union[str, Any]=False , A__ : List[str]=1E-5 , A__ : Tuple=0.0 , A__ : Optional[int]=0.0 , A__ : Union[str, Any]=0.0 , A__ : Optional[Any]=False , A__ : Union[str, Any]=0.02 , **A__ : List[Any] , ) -> int: '''simple docstring''' super().__init__(**A__ ) a__ : Dict = image_size a__ : Union[str, Any] = patch_size a__ : Union[str, Any] = num_channels a__ : Dict = max_token_length a__ : Union[str, Any] = num_character_labels a__ : Union[str, Any] = num_bpe_labels a__ : Any = num_wordpiece_labels a__ : Tuple = hidden_size a__ : Dict = num_hidden_layers a__ : Optional[Any] = num_attention_heads a__ : int = mlp_ratio a__ : Optional[int] = distilled a__ : Tuple = layer_norm_eps a__ : str = drop_rate a__ : str = qkv_bias a__ : List[str] = attn_drop_rate a__ : Union[str, Any] = drop_path_rate a__ : List[str] = output_aa_attentions a__ : Optional[int] = initializer_range
688
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None a__ , a__ : List[Any] = get_aligned_output_features_output_indices(A__ , A__ , A__ ) self.assertEqual(A__ , ['''c'''] ) self.assertEqual(A__ , [2] ) # Out indices set to match out features a__ , a__ : Optional[int] = get_aligned_output_features_output_indices(['''a''', '''c'''] , A__ , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features set to match out indices a__ , a__ : int = get_aligned_output_features_output_indices(A__ , [0, 2] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features selected from negative indices a__ , a__ : List[str] = get_aligned_output_features_output_indices(A__ , [-3, -1] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [-3, -1] ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , A__ ) # Out features must be a list with self.assertRaises(A__ ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(A__ ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : Optional[Any] = BackboneMixin() a__ : int = ['''a''', '''b''', '''c'''] a__ : List[Any] = ['''a''', '''c'''] a__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly a__ : Dict = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) a__ : int = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
688
1
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : str , A__ : List[str] , A__ : Dict , A__ : int ) -> Optional[Any]: '''simple docstring''' a__ : Dict = None a__ : Optional[Any] = None a__ : List[str] = graph self._normalize_graph(A__ , A__ ) a__ : int = len(A__ ) a__ : Any = None def __lowerCAmelCase ( self : Optional[int] , A__ : Dict , A__ : str ) -> Optional[int]: '''simple docstring''' if sources is int: a__ : int = [sources] if sinks is int: a__ : Union[str, Any] = [sinks] if len(A__ ) == 0 or len(A__ ) == 0: return a__ : Dict = sources[0] a__ : int = sinks[0] # make fake vertex if there are more # than one source or sink if len(A__ ) > 1 or len(A__ ) > 1: a__ : List[Any] = 0 for i in sources: max_input_flow += sum(self.graph[i] ) a__ : List[str] = len(self.graph ) + 1 for room in self.graph: room.insert(0 , 0 ) self.graph.insert(0 , [0] * size ) for i in sources: a__ : str = max_input_flow a__ : Tuple = 0 a__ : Optional[Any] = len(self.graph ) + 1 for room in self.graph: room.append(0 ) self.graph.append([0] * size ) for i in sinks: a__ : str = max_input_flow a__ : int = size - 1 def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' if self.maximum_flow_algorithm is None: raise Exception('''You need to set maximum flow algorithm before.''' ) if self.source_index is None or self.sink_index is None: return 0 self.maximum_flow_algorithm.execute() return self.maximum_flow_algorithm.getMaximumFlow() def __lowerCAmelCase ( self : Dict , A__ : int ) -> Optional[int]: '''simple docstring''' a__ : Dict = algorithm(self ) class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[Any] , A__ : Any ) -> Tuple: '''simple docstring''' a__ : Optional[int] = flow_network a__ : Optional[int] = flow_network.verticesCount a__ : Optional[int] = flow_network.sourceIndex a__ : List[str] = flow_network.sinkIndex # it's just a reference, so you shouldn't change # it in your algorithms, use deep copy before doing that a__ : List[Any] = flow_network.graph a__ : str = False def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' if not self.executed: self._algorithm() a__ : List[str] = True def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' pass class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : List[str] , A__ : List[str] ) -> Union[str, Any]: '''simple docstring''' super().__init__(A__ ) # use this to save your result a__ : List[Any] = -1 def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' if not self.executed: raise Exception('''You should execute algorithm before using its result!''' ) return self.maximum_flow class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : List[Any] , A__ : Optional[Any] ) -> str: '''simple docstring''' super().__init__(A__ ) a__ : Dict = [[0] * self.verticies_count for i in range(self.verticies_count )] a__ : Dict = [0] * self.verticies_count a__ : List[Any] = [0] * self.verticies_count def __lowerCAmelCase ( self : List[str] ) -> Dict: '''simple docstring''' a__ : Any = self.verticies_count # push some substance to graph for nextvertex_index, bandwidth in enumerate(self.graph[self.source_index] ): self.preflow[self.source_index][nextvertex_index] += bandwidth self.preflow[nextvertex_index][self.source_index] -= bandwidth self.excesses[nextvertex_index] += bandwidth # Relabel-to-front selection rule a__ : Optional[Any] = [ i for i in range(self.verticies_count ) if i != self.source_index and i != self.sink_index ] # move through list a__ : List[Any] = 0 while i < len(A__ ): a__ : Any = vertices_list[i] a__ : Dict = self.heights[vertex_index] self.process_vertex(A__ ) if self.heights[vertex_index] > previous_height: # if it was relabeled, swap elements # and start from 0 index vertices_list.insert(0 , vertices_list.pop(A__ ) ) a__ : str = 0 else: i += 1 a__ : int = sum(self.preflow[self.source_index] ) def __lowerCAmelCase ( self : List[Any] , A__ : Any ) -> Optional[int]: '''simple docstring''' while self.excesses[vertex_index] > 0: for neighbour_index in range(self.verticies_count ): # if it's neighbour and current vertex is higher if ( self.graph[vertex_index][neighbour_index] - self.preflow[vertex_index][neighbour_index] > 0 and self.heights[vertex_index] > self.heights[neighbour_index] ): self.push(A__ , A__ ) self.relabel(A__ ) def __lowerCAmelCase ( self : Optional[int] , A__ : List[str] , A__ : int ) -> List[Any]: '''simple docstring''' a__ : List[Any] = min( self.excesses[from_index] , self.graph[from_index][to_index] - self.preflow[from_index][to_index] , ) self.preflow[from_index][to_index] += preflow_delta self.preflow[to_index][from_index] -= preflow_delta self.excesses[from_index] -= preflow_delta self.excesses[to_index] += preflow_delta def __lowerCAmelCase ( self : Dict , A__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' a__ : List[str] = None for to_index in range(self.verticies_count ): if ( self.graph[vertex_index][to_index] - self.preflow[vertex_index][to_index] > 0 ) and (min_height is None or self.heights[to_index] < min_height): a__ : int = self.heights[to_index] if min_height is not None: a__ : Optional[Any] = min_height + 1 if __name__ == "__main__": __SCREAMING_SNAKE_CASE = [0] __SCREAMING_SNAKE_CASE = [3] # graph = [ # [0, 0, 4, 6, 0, 0], # [0, 0, 5, 2, 0, 0], # [0, 0, 0, 0, 4, 4], # [0, 0, 0, 0, 6, 6], # [0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0], # ] __SCREAMING_SNAKE_CASE = [[0, 7, 0, 0], [0, 0, 6, 0], [0, 0, 0, 8], [9, 0, 0, 0]] # prepare our network __SCREAMING_SNAKE_CASE = FlowNetwork(graph, entrances, exits) # set algorithm flow_network.set_maximum_flow_algorithm(PushRelabelExecutor) # and calculate __SCREAMING_SNAKE_CASE = flow_network.find_maximum_flow() print(f'maximum flow is {maximum_flow}')
688
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __a ( lowerCAmelCase__ : List[Any] ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ): a__ : Dict = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue a__ : Any = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) a__ : int = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) a__ : Optional[Any] = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) a__ : Dict = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) a__ : List[str] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) a__ : List[Any] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) a__ : str = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) a__ : List[Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) a__ : List[Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) a__ : str = key.replace('''image_encoder.module''' , '''flava.image_model''' ) a__ : Dict = key.replace('''text_encoder.module''' , '''flava.text_model''' ) a__ : List[Any] = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) a__ : List[str] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) a__ : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' ) a__ : Any = key.replace('''image_projection''' , '''flava.image_projection''' ) a__ : Any = value.float() for key, value in codebook_state_dict.items(): a__ : List[str] = value return upgrade @torch.no_grad() def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict=None ): if config_path is not None: a__ : Tuple = FlavaConfig.from_pretrained(lowerCAmelCase__ ) else: a__ : Optional[int] = FlavaConfig() a__ : List[Any] = FlavaForPreTraining(lowerCAmelCase__ ).eval() a__ : Optional[int] = convert_dalle_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , save_checkpoint=lowerCAmelCase__ ) if os.path.exists(lowerCAmelCase__ ): a__ : List[str] = torch.load(lowerCAmelCase__ , map_location='''cpu''' ) else: a__ : Dict = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' ) a__ : List[Any] = upgrade_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) a__ : Any = hf_model.state_dict() a__ : Optional[Any] = count_parameters(lowerCAmelCase__ ) a__ : int = count_parameters(lowerCAmelCase__ ) + count_parameters(lowerCAmelCase__ ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
688
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available __SCREAMING_SNAKE_CASE = { 'configuration_ernie': ['ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ErnieConfig', 'ErnieOnnxConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST', 'ErnieForCausalLM', 'ErnieForMaskedLM', 'ErnieForMultipleChoice', 'ErnieForNextSentencePrediction', 'ErnieForPreTraining', 'ErnieForQuestionAnswering', 'ErnieForSequenceClassification', 'ErnieForTokenClassification', 'ErnieModel', 'ErniePreTrainedModel', ] if TYPE_CHECKING: from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ernie import ( ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST, ErnieForCausalLM, ErnieForMaskedLM, ErnieForMultipleChoice, ErnieForNextSentencePrediction, ErnieForPreTraining, ErnieForQuestionAnswering, ErnieForSequenceClassification, ErnieForTokenClassification, ErnieModel, ErniePreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
688
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass def __a ( lowerCAmelCase__ : List[str] ): for shard in shards: for i in range(lowerCAmelCase__ ): yield {"i": i, "shard": shard} def __a ( ): a__ : str = int(os.environ['''RANK'''] ) a__ : int = int(os.environ['''WORLD_SIZE'''] ) a__ : str = ArgumentParser() parser.add_argument('''--streaming''' , type=lowerCAmelCase__ ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase__ ) parser.add_argument('''--num_workers''' , type=lowerCAmelCase__ , default=0 ) a__ : int = parser.parse_args() a__ : List[str] = args.streaming a__ : Dict = args.num_workers a__ : Dict = {'''shards''': [F'shard_{shard_idx}' for shard_idx in range(lowerCAmelCase__ )]} a__ : Tuple = IterableDataset.from_generator(lowerCAmelCase__ , gen_kwargs=lowerCAmelCase__ ) if not streaming: a__ : str = Dataset.from_list(list(lowerCAmelCase__ ) ) a__ : Optional[int] = split_dataset_by_node(lowerCAmelCase__ , rank=lowerCAmelCase__ , world_size=lowerCAmelCase__ ) a__ : Dict = torch.utils.data.DataLoader(lowerCAmelCase__ , num_workers=lowerCAmelCase__ ) a__ : str = NUM_SHARDS * NUM_ITEMS_PER_SHARD a__ : Dict = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) a__ : str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'local_size {local_size} != expected_local_size {expected_local_size}' ) if __name__ == "__main__": main()
688
1
'''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 ( lowerCAmelCase__ : List[Any] ): a__ : Any = checkpoints.load_tax_checkpoint(lowerCAmelCase__ ) a__ : str = flatten_dict(lowerCAmelCase__ ) return flax_params def __a ( lowerCAmelCase__ : int ): a__ : Optional[int] = {} a__ : Optional[Any] = { '''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''', } a__ : Union[str, Any] = { '''query''': '''attention.query''', '''key''': '''attention.key''', '''value''': '''attention.value''', '''output.dense''': '''output''', '''encoder_decoder_attention.o''': '''encoder_decoder_attention.attention.o''', '''pre_self_attention_layer_norm''': '''self_attention.layer_norm''', '''pre_cross_attention_layer_norm''': '''encoder_decoder_attention.layer_norm''', '''mlp.''': '''mlp.DenseReluDense.''', '''pre_mlp_layer_norm''': '''mlp.layer_norm''', '''self_attention.o''': '''self_attention.attention.o''', '''decoder.embeddings.embedding''': '''decoder.embed_tokens.weight''', '''decoder.relpos_bias.rel_embedding''': '''decoder.layer.0.self_attention.attention.relative_attention_bias.weight''', '''decoder.decoder_norm.weight''': '''decoder.final_layer_norm.weight''', '''decoder.logits_dense.weight''': '''decoder.lm_head.weight''', } for key in flax_dict.keys(): if "target" in key: # remove the first prefix from the key a__ : int = '''.'''.join(key[1:] ) # rename the key for old, new in CONVERSION_MAPPING.items(): a__ : List[Any] = new_key.replace(lowerCAmelCase__ , lowerCAmelCase__ ) if "decoder" in new_key: for old, new in DECODER_CONVERSION_MAPPING.items(): a__ : Optional[int] = new_key.replace(lowerCAmelCase__ , lowerCAmelCase__ ) if "layers" in new_key and "decoder" not in new_key: # use regex to replace the layer number a__ : Optional[int] = re.sub(r'''layers_(\d+)''' , r'''layer.\1''' , lowerCAmelCase__ ) a__ : Optional[int] = new_key.replace('''encoder''' , '''encoder.encoder''' ) elif "layers" in new_key and "decoder" in new_key: # use regex to replace the layer number a__ : Dict = re.sub(r'''layers_(\d+)''' , r'''layer.\1''' , lowerCAmelCase__ ) a__ : Any = flax_dict[key] a__ : Union[str, Any] = {} # convert converted_dict into torch format for key in converted_dict.keys(): if ("embed_tokens" not in key) and ("embedder" not in key): a__ : Optional[int] = torch.from_numpy(converted_dict[key].T ) else: a__ : Optional[int] = torch.from_numpy(converted_dict[key] ) return converted_torch_dict def __a ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Dict=False , lowerCAmelCase__ : Tuple=False ): a__ : Tuple = get_flax_param(lowerCAmelCase__ ) if not use_large: a__ : Union[str, Any] = PixaStructVisionConfig() a__ : Optional[Any] = PixaStructTextConfig() else: a__ : Tuple = PixaStructVisionConfig( hidden_size=1536 , d_ff=3968 , num_attention_heads=24 , num_hidden_layers=18 ) a__ : Union[str, Any] = PixaStructTextConfig(hidden_size=1536 , d_ff=3968 , num_heads=24 , num_layers=18 ) a__ : List[str] = PixaStructConfig( vision_config=encoder_config.to_dict() , text_config=decoder_config.to_dict() , is_vqa=lowerCAmelCase__ ) a__ : List[str] = PixaStructForConditionalGeneration(lowerCAmelCase__ ) a__ : int = rename_and_convert_flax_params(lowerCAmelCase__ ) model.load_state_dict(lowerCAmelCase__ ) a__ : Tuple = AutoTokenizer.from_pretrained('''ybelkada/test-pix2struct-tokenizer''' ) a__ : str = PixaStructImageProcessor() a__ : str = PixaStructProcessor(image_processor=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ ) if use_large: a__ : Dict = 4096 a__ : int = True # mkdir if needed os.makedirs(lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) model.save_pretrained(lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) print('''Model saved in {}'''.format(lowerCAmelCase__ ) ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = 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.') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_pixastruct_original_pytorch_checkpoint_to_hf( args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large )
688
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __SCREAMING_SNAKE_CASE = open # noqa: we just need to have a builtin inside this module to test it properly
688
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "swin2sr" __UpperCamelCase = { "hidden_size": "embed_dim", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] , A__ : int=6_4 , A__ : List[Any]=1 , A__ : List[Any]=3 , A__ : Any=1_8_0 , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Dict=8 , A__ : Any=2.0 , A__ : Optional[int]=True , A__ : Union[str, Any]=0.0 , A__ : Union[str, Any]=0.0 , A__ : List[str]=0.1 , A__ : Any="gelu" , A__ : Tuple=False , A__ : Optional[int]=0.02 , A__ : List[Any]=1E-5 , A__ : Any=2 , A__ : Union[str, Any]=1.0 , A__ : Dict="1conv" , A__ : Optional[Any]="pixelshuffle" , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : List[str] = image_size a__ : Optional[Any] = patch_size a__ : Dict = num_channels a__ : Optional[int] = embed_dim a__ : int = depths a__ : Optional[int] = len(A__ ) a__ : Dict = num_heads a__ : List[Any] = window_size a__ : Optional[int] = mlp_ratio a__ : Optional[int] = qkv_bias a__ : Union[str, Any] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Union[str, Any] = drop_path_rate a__ : int = hidden_act a__ : int = use_absolute_embeddings a__ : Dict = layer_norm_eps a__ : List[str] = initializer_range a__ : List[Any] = upscale a__ : List[Any] = img_range a__ : Optional[int] = resi_connection a__ : int = upsampler
688
'''simple docstring''' import enum import shutil import sys __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = shutil.get_terminal_size() __SCREAMING_SNAKE_CASE = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase__ ( enum.Enum ): """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 1 def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict="" ): sys.stdout.write(str(lowerCAmelCase__ ) + end ) sys.stdout.flush() def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : int="" ): forceWrite(F'\u001b[{color}m{content}\u001b[0m' , lowerCAmelCase__ ) def __a ( ): forceWrite('''\r''' ) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : str ): forceWrite(F'\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}' ) def __a ( ): forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def __a ( ): reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
688
1
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version __SCREAMING_SNAKE_CASE = get_logger(__name__) class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = "dummy_data" __UpperCamelCase = "datasets" __UpperCamelCase = False def __init__( self : Any , A__ : str , A__ : str , A__ : Union[Version, str] , A__ : Optional[str] = None , A__ : bool = False , A__ : bool = True , A__ : Optional[List[Callable]] = None , ) -> int: '''simple docstring''' a__ : Tuple = 0 a__ : Any = dataset_name a__ : int = cache_dir a__ : str = use_local_dummy_data a__ : List[str] = config # download_callbacks take a single url as input a__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root a__ : str = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general a__ : Optional[Any] = str(A__ ) # to be downloaded a__ : Tuple = None a__ : Tuple = None @property def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' if self._dummy_file is None: a__ : Dict = self.download_dummy_data() return self._dummy_file @property def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('''dummy''' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('''dummy''' , self.version_name ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : int = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) a__ : str = cached_path( A__ , cache_dir=self.cache_dir , extract_compressed_file=A__ , force_extract=A__ ) return os.path.join(A__ , self.dummy_file_name ) @property def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self._bucket_url is None: a__ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) ) return self._bucket_url @property def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , *A__ : int ) -> Union[str, Any]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested a__ : Tuple = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned a__ : Union[str, Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(A__ , A__ ): return self.create_dummy_data_dict(A__ , A__ ) elif isinstance(A__ , (list, tuple) ): return self.create_dummy_data_list(A__ , A__ ) else: return self.create_dummy_data_single(A__ , A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Any , *A__ : int ) -> Any: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Any , A__ : Optional[int] , A__ : Optional[Any] ) -> int: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , *A__ : List[Any] , **A__ : str ) -> Optional[Any]: '''simple docstring''' return path def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' return {} def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[str] ) -> Any: '''simple docstring''' a__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A__ , A__ ): for single_url in single_urls: download_callback(A__ ) else: a__ : Dict = single_urls download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A__ , A__ ): a__ : Optional[int] = [os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) for x in single_urls] else: a__ : Optional[Any] = single_urls a__ : Tuple = os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) a__ : List[str] = value # make sure that values are unique if all(isinstance(A__ , A__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique a__ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : str = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one a__ : Union[str, Any] = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , A__ ) ) for url in data_url ) a__ : Optional[Any] = all( url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): a__ : Dict = [data_url[0]] * len(A__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Optional[int] = os.path.join(A__ , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) ) dummy_data_list.append(A__ ) return dummy_data_list def __lowerCAmelCase ( self : Dict , A__ : Dict , A__ : str ) -> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Union[str, Any] = os.path.join(A__ , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) ) if os.path.exists(A__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' pass def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: '''simple docstring''' pass def __lowerCAmelCase ( self : Any , A__ : Tuple ) -> Any: '''simple docstring''' def _iter_archive_members(A__ : str ): # this preserves the order of the members inside the ZIP archive a__ : Dict = Path(self.dummy_file ).parent a__ : Tuple = path.relative_to(A__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: a__ : Optional[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A__ ) a__ : str = Path(A__ ) a__ : Optional[Any] = _iter_archive_members(A__ ) if self.use_local_dummy_data else path.rglob('''*''' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ): yield file_path.relative_to(A__ ).as_posix(), file_path.open('''rb''' ) def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> Tuple: '''simple docstring''' if not isinstance(A__ , A__ ): a__ : int = [paths] for path in paths: if os.path.isfile(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): return yield path else: for dirpath, dirnames, filenames in os.walk(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): continue dirnames.sort() for filename in sorted(A__ ): if filename.startswith(('''.''', '''__''') ): continue yield os.path.join(A__ , A__ )
688
'''simple docstring''' import inspect import unittest class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' try: import diffusers # noqa: F401 except ImportError: assert False def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' import diffusers from diffusers.dependency_versions_table import deps a__ : Optional[int] = inspect.getmembers(A__ , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": a__ : int = '''k-diffusion''' elif backend == "invisible_watermark": a__ : int = '''invisible-watermark''' assert backend in deps, F'{backend} is not in the deps table!'
688
1
'''simple docstring''' # DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim from dataclasses import dataclass from typing import Optional, Tuple, Union import flax import jax import jax.numpy as jnp from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils_flax import ( CommonSchedulerState, FlaxKarrasDiffusionSchedulers, FlaxSchedulerMixin, FlaxSchedulerOutput, add_noise_common, get_velocity_common, ) @flax.struct.dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = 42 # setable values __UpperCamelCase = 42 __UpperCamelCase = 42 __UpperCamelCase = None @classmethod def __lowerCAmelCase ( cls : Tuple , A__ : CommonSchedulerState , A__ : jnp.ndarray , A__ : jnp.ndarray ) -> Union[str, Any]: '''simple docstring''' return cls(common=A__ , init_noise_sigma=A__ , timesteps=A__ ) @dataclass class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = 42 class lowerCAmelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = [e.name for e in FlaxKarrasDiffusionSchedulers] __UpperCamelCase = 42 @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' return True @register_to_config def __init__( self : List[str] , A__ : int = 1_0_0_0 , A__ : float = 0.0_001 , A__ : float = 0.02 , A__ : str = "linear" , A__ : Optional[jnp.ndarray] = None , A__ : str = "fixed_small" , A__ : bool = True , A__ : str = "epsilon" , A__ : jnp.dtype = jnp.floataa , ) -> str: '''simple docstring''' a__ : List[Any] = dtype def __lowerCAmelCase ( self : str , A__ : Optional[CommonSchedulerState] = None ) -> DDPMSchedulerState: '''simple docstring''' if common is None: a__ : List[str] = CommonSchedulerState.create(self ) # standard deviation of the initial noise distribution a__ : int = jnp.array(1.0 , dtype=self.dtype ) a__ : List[Any] = jnp.arange(0 , self.config.num_train_timesteps ).round()[::-1] return DDPMSchedulerState.create( common=A__ , init_noise_sigma=A__ , timesteps=A__ , ) def __lowerCAmelCase ( self : List[str] , A__ : DDPMSchedulerState , A__ : jnp.ndarray , A__ : Optional[int] = None ) -> jnp.ndarray: '''simple docstring''' return sample def __lowerCAmelCase ( self : str , A__ : DDPMSchedulerState , A__ : int , A__ : Tuple = () ) -> DDPMSchedulerState: '''simple docstring''' a__ : Dict = self.config.num_train_timesteps // num_inference_steps # creates integer timesteps by multiplying by ratio # rounding to avoid issues when num_inference_step is power of 3 a__ : Optional[int] = (jnp.arange(0 , A__ ) * step_ratio).round()[::-1] return state.replace( num_inference_steps=A__ , timesteps=A__ , ) def __lowerCAmelCase ( self : List[str] , A__ : DDPMSchedulerState , A__ : List[Any] , A__ : Optional[Any]=None , A__ : Any=None ) -> List[Any]: '''simple docstring''' a__ : str = state.common.alphas_cumprod[t] a__ : int = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) # 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 a__ : int = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * state.common.betas[t] if variance_type is None: a__ : Union[str, Any] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small": a__ : Union[str, Any] = jnp.clip(A__ , a_min=1E-20 ) # for rl-diffuser https://arxiv.org/abs/2205.09991 elif variance_type == "fixed_small_log": a__ : Any = jnp.log(jnp.clip(A__ , a_min=1E-20 ) ) elif variance_type == "fixed_large": a__ : Optional[Any] = state.common.betas[t] elif variance_type == "fixed_large_log": # Glide max_log a__ : Optional[int] = jnp.log(state.common.betas[t] ) elif variance_type == "learned": return predicted_variance elif variance_type == "learned_range": a__ : str = variance a__ : str = state.common.betas[t] a__ : Union[str, Any] = (predicted_variance + 1) / 2 a__ : Optional[int] = frac * max_log + (1 - frac) * min_log return variance def __lowerCAmelCase ( self : Optional[Any] , A__ : DDPMSchedulerState , A__ : jnp.ndarray , A__ : int , A__ : jnp.ndarray , A__ : Optional[jax.random.KeyArray] = None , A__ : bool = True , ) -> Union[FlaxDDPMSchedulerOutput, Tuple]: '''simple docstring''' a__ : Optional[int] = timestep if key is None: a__ : int = jax.random.PRNGKey(0 ) if model_output.shape[1] == sample.shape[1] * 2 and self.config.variance_type in ["learned", "learned_range"]: a__ , a__ : Tuple = jnp.split(A__ , sample.shape[1] , axis=1 ) else: a__ : List[str] = None # 1. compute alphas, betas a__ : int = state.common.alphas_cumprod[t] a__ : Tuple = jnp.where(t > 0 , state.common.alphas_cumprod[t - 1] , jnp.array(1.0 , dtype=self.dtype ) ) a__ : Optional[Any] = 1 - alpha_prod_t a__ : str = 1 - alpha_prod_t_prev # 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": a__ : Union[str, Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": a__ : List[Any] = model_output elif self.config.prediction_type == "v_prediction": a__ : List[Any] = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output else: raise ValueError( F'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample` ' ''' for the FlaxDDPMScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: a__ : Dict = jnp.clip(A__ , -1 , 1 ) # 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 a__ : List[Any] = (alpha_prod_t_prev ** 0.5 * state.common.betas[t]) / beta_prod_t a__ : str = state.common.alphas[t] ** 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 a__ : Any = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise def random_variance(): a__ : Optional[int] = jax.random.split(A__ , num=1 ) a__ : Optional[int] = jax.random.normal(A__ , shape=model_output.shape , dtype=self.dtype ) return (self._get_variance(A__ , A__ , predicted_variance=A__ ) ** 0.5) * noise a__ : Tuple = jnp.where(t > 0 , random_variance() , jnp.zeros(model_output.shape , dtype=self.dtype ) ) a__ : Optional[int] = pred_prev_sample + variance if not return_dict: return (pred_prev_sample, state) return FlaxDDPMSchedulerOutput(prev_sample=A__ , state=A__ ) def __lowerCAmelCase ( self : List[Any] , A__ : DDPMSchedulerState , A__ : jnp.ndarray , A__ : jnp.ndarray , A__ : jnp.ndarray , ) -> jnp.ndarray: '''simple docstring''' return add_noise_common(state.common , A__ , A__ , A__ ) def __lowerCAmelCase ( self : Dict , A__ : DDPMSchedulerState , A__ : jnp.ndarray , A__ : jnp.ndarray , A__ : jnp.ndarray , ) -> jnp.ndarray: '''simple docstring''' return get_velocity_common(state.common , A__ , A__ , A__ ) def __len__( self : Dict ) -> int: '''simple docstring''' return self.config.num_train_timesteps
688
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __a ( lowerCAmelCase__ : Dict ): a__ , a__ : int = image.size a__ , a__ : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 a__ : Tuple = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) a__ : List[Any] = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 255.0 a__ : Any = image[None].transpose(0 , 3 , 1 , 2 ) a__ : Dict = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , A__ : VQModel , A__ : UNetaDModel , A__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> str: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : List[str] , A__ : Union[torch.Tensor, PIL.Image.Image] = None , A__ : Optional[int] = 1 , A__ : Optional[int] = 1_0_0 , A__ : Optional[float] = 0.0 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' if isinstance(A__ , PIL.Image.Image ): a__ : List[Any] = 1 elif isinstance(A__ , torch.Tensor ): a__ : List[str] = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(A__ )}' ) if isinstance(A__ , PIL.Image.Image ): a__ : Union[str, Any] = preprocess(A__ ) a__ , a__ : Dict = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image a__ : Optional[int] = (batch_size, self.unet.config.in_channels // 2, height, width) a__ : Optional[int] = next(self.unet.parameters() ).dtype a__ : List[str] = randn_tensor(A__ , generator=A__ , device=self.device , dtype=A__ ) a__ : Any = image.to(device=self.device , dtype=A__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(A__ , device=self.device ) a__ : int = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler a__ : str = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a__ : Union[str, Any] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a__ : str = {} if accepts_eta: a__ : Dict = eta for t in self.progress_bar(A__ ): # concat latents and low resolution image in the channel dimension. a__ : str = torch.cat([latents, image] , dim=1 ) a__ : Optional[Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual a__ : Union[str, Any] = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VQVAE a__ : List[Any] = self.vqvae.decode(A__ ).sample a__ : List[Any] = torch.clamp(A__ , -1.0 , 1.0 ) a__ : Optional[Any] = image / 2 + 0.5 a__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a__ : Union[str, Any] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'salesforce/blip2-opt-2.7b': 'https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json', } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "blip_2_vision_model" def __init__( self : List[str] , A__ : int=1_4_0_8 , A__ : Any=6_1_4_4 , A__ : List[str]=3_9 , A__ : Dict=1_6 , A__ : Any=2_2_4 , A__ : Optional[int]=1_4 , A__ : Union[str, Any]="gelu" , A__ : Dict=0.00_001 , A__ : Any=0.0 , A__ : Union[str, Any]=1E-10 , A__ : Any=True , **A__ : List[str] , ) -> Tuple: '''simple docstring''' super().__init__(**A__ ) a__ : Any = hidden_size a__ : Any = intermediate_size a__ : int = num_hidden_layers a__ : int = num_attention_heads a__ : Tuple = patch_size a__ : Optional[Any] = image_size a__ : List[Any] = initializer_range a__ : str = attention_dropout a__ : Union[str, Any] = layer_norm_eps a__ : List[Any] = hidden_act a__ : List[Any] = qkv_bias @classmethod def __lowerCAmelCase ( cls : Union[str, Any] , A__ : Union[str, os.PathLike] , **A__ : str ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(A__ ) a__ , a__ : List[Any] = cls.get_config_dict(A__ , **A__ ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": a__ : Dict = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A__ , **A__ ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "blip_2_qformer" def __init__( self : Union[str, Any] , A__ : Union[str, Any]=3_0_5_2_2 , A__ : List[Any]=7_6_8 , A__ : Any=1_2 , A__ : Any=1_2 , A__ : List[str]=3_0_7_2 , A__ : Any="gelu" , A__ : Dict=0.1 , A__ : Optional[Any]=0.1 , A__ : int=5_1_2 , A__ : Union[str, Any]=0.02 , A__ : Tuple=1E-12 , A__ : Tuple=0 , A__ : Dict="absolute" , A__ : Optional[Any]=2 , A__ : Optional[int]=1_4_0_8 , **A__ : int , ) -> List[str]: '''simple docstring''' super().__init__(pad_token_id=A__ , **A__ ) a__ : Dict = vocab_size a__ : Union[str, Any] = hidden_size a__ : Union[str, Any] = num_hidden_layers a__ : Optional[Any] = num_attention_heads a__ : List[str] = hidden_act a__ : int = intermediate_size a__ : str = hidden_dropout_prob a__ : Tuple = attention_probs_dropout_prob a__ : Union[str, Any] = max_position_embeddings a__ : Dict = initializer_range a__ : str = layer_norm_eps a__ : Union[str, Any] = position_embedding_type a__ : List[Any] = cross_attention_frequency a__ : Union[str, Any] = encoder_hidden_size @classmethod def __lowerCAmelCase ( cls : Union[str, Any] , A__ : Union[str, os.PathLike] , **A__ : List[str] ) -> "PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(A__ ) a__ , a__ : Optional[int] = cls.get_config_dict(A__ , **A__ ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": a__ : Any = config_dict['''qformer_config'''] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(A__ , **A__ ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "blip-2" __UpperCamelCase = True def __init__( self : int , A__ : str=None , A__ : Union[str, Any]=None , A__ : List[Any]=None , A__ : Dict=3_2 , **A__ : List[Any] ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) if vision_config is None: a__ : List[str] = {} logger.info('''vision_config is None. initializing the Blip2VisionConfig with default values.''' ) if qformer_config is None: a__ : List[str] = {} logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.''' ) if text_config is None: a__ : List[Any] = {} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) a__ : int = BlipaVisionConfig(**A__ ) a__ : List[str] = BlipaQFormerConfig(**A__ ) a__ : Dict = text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' a__ : Optional[int] = CONFIG_MAPPING[text_model_type](**A__ ) a__ : Optional[int] = self.text_config.tie_word_embeddings a__ : Tuple = self.text_config.is_encoder_decoder a__ : List[Any] = num_query_tokens a__ : Dict = self.vision_config.hidden_size a__ : str = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES a__ : Optional[Any] = 1.0 a__ : Tuple = 0.02 @classmethod def __lowerCAmelCase ( cls : Optional[int] , A__ : BlipaVisionConfig , A__ : BlipaQFormerConfig , A__ : PretrainedConfig , **A__ : List[str] , ) -> List[str]: '''simple docstring''' return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **A__ , ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' a__ : int = copy.deepcopy(self.__dict__ ) a__ : Optional[Any] = self.vision_config.to_dict() a__ : Tuple = self.qformer_config.to_dict() a__ : str = self.text_config.to_dict() a__ : Optional[int] = self.__class__.model_type return output
688
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # pylint: disable=invalid-name __SCREAMING_SNAKE_CASE = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : str=8 ): a__ : Tuple = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a__ : Union[str, Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Dict , A__ : UNetaDConditionModel , A__ : DDPMScheduler , A__ : VQModel , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules( unet=A__ , scheduler=A__ , movq=A__ , ) a__ : Union[str, Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] , A__ : List[str] , A__ : Optional[Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if latents is None: a__ : List[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__ : int = latents.to(A__ ) a__ : Tuple = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : Union[str, Any] , A__ : int=0 ) -> str: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a__ : Union[str, Any] = torch.device(F'cuda:{gpu_id}' ) a__ : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A__ , A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple=0 ) -> Dict: '''simple docstring''' if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) a__ : int = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=A__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a__ : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: a__ , a__ : List[str] = cpu_offload_with_hook(A__ , A__ , prev_module_hook=A__ ) # We'll offload the last model manually. a__ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.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 @torch.no_grad() @replace_example_docstring(A__ ) def __call__( self : Any , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : torch.FloatTensor , A__ : int = 5_1_2 , A__ : int = 5_1_2 , A__ : int = 1_0_0 , A__ : float = 4.0 , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> str: '''simple docstring''' a__ : Optional[Any] = self._execution_device a__ : List[str] = guidance_scale > 1.0 if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : Optional[int] = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) a__ : Union[str, Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a__ : Tuple = image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = negative_image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = hint.repeat_interleave(A__ , dim=0 ) a__ : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) a__ : Tuple = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) self.scheduler.set_timesteps(A__ , device=A__ ) a__ : int = self.scheduler.timesteps a__ : str = self.movq.config.latent_channels a__ , a__ : Optional[int] = downscale_height_and_width(A__ , A__ , self.movq_scale_factor ) # create initial latent a__ : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A__ , A__ , A__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance a__ : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ : List[str] = {'''image_embeds''': image_embeds, '''hint''': hint} a__ : Union[str, Any] = self.unet( sample=A__ , timestep=A__ , encoder_hidden_states=A__ , added_cond_kwargs=A__ , return_dict=A__ , )[0] if do_classifier_free_guidance: a__ , a__ : Dict = noise_pred.split(latents.shape[1] , dim=1 ) a__ , a__ : Dict = noise_pred.chunk(2 ) a__ , a__ : Optional[Any] = variance_pred.chunk(2 ) a__ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a__ , a__ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step( A__ , A__ , A__ , generator=A__ , )[0] # post-processing a__ : Tuple = self.movq.decode(A__ , force_not_quantize=A__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: a__ : Union[str, Any] = image * 0.5 + 0.5 a__ : str = image.clamp(0 , 1 ) a__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ : int = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' from .testing import ( are_the_same_tensors, execute_subprocess_async, require_bnb, require_cpu, require_cuda, require_huggingface_suite, require_mps, require_multi_gpu, require_multi_xpu, require_safetensors, require_single_gpu, require_single_xpu, require_torch_min_version, require_tpu, require_xpu, skip, slow, ) from .training import RegressionDataset, RegressionModel, RegressionModelaXPU from .scripts import test_script, test_sync, test_ops # isort: skip
688
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } __SCREAMING_SNAKE_CASE = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def __a ( lowerCAmelCase__ : Union[str, Any] ): with open(lowerCAmelCase__ , '''r''' ) as f: a__ : Optional[int] = f.read().splitlines() return [l.strip() for l in lines] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[str] , A__ : int , A__ : Union[str, Any]="<unk>" , A__ : Tuple="<cls>" , A__ : List[Any]="<pad>" , A__ : Optional[int]="<mask>" , A__ : List[Any]="<eos>" , **A__ : Optional[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) a__ : Union[str, Any] = load_vocab_file(A__ ) a__ : int = dict(enumerate(self.all_tokens ) ) a__ : str = {tok: ind for ind, tok in enumerate(self.all_tokens )} a__ : List[Any] = unk_token a__ : Any = cls_token a__ : Any = pad_token a__ : Any = mask_token a__ : Any = eos_token a__ : int = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCAmelCase ( self : Any , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , **A__ : str ) -> List[Any]: '''simple docstring''' return text.split() def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int]=False ) -> Tuple: '''simple docstring''' return len(self._id_to_token ) def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCAmelCase ( self : Any , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : List[Any] , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Tuple = [self.cls_token_id] a__ : Union[str, Any] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCAmelCase ( self : Tuple , A__ : List , A__ : Optional[List] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] a__ : Any = [1] + ([0] * len(A__ )) + [1] if token_ids_a is not None: mask += [0] * len(A__ ) + [1] return mask def __lowerCAmelCase ( self : Any , A__ : Dict , A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = os.path.join(A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(A__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return self.get_vocab_size(with_added_tokens=A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Union[List[str], List[AddedToken]] , A__ : bool = False ) -> int: '''simple docstring''' return super()._add_tokens(A__ , special_tokens=A__ )
688
1
'''simple docstring''' 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_fnet import FNetTokenizer else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } __SCREAMING_SNAKE_CASE = { 'google/fnet-base': 5_1_2, 'google/fnet-large': 5_1_2, } __SCREAMING_SNAKE_CASE = '▁' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "token_type_ids"] __UpperCamelCase = FNetTokenizer def __init__( self : Any , A__ : Any=None , A__ : int=None , A__ : List[str]=False , A__ : int=True , A__ : str=True , A__ : List[Any]="<unk>" , A__ : Dict="[SEP]" , A__ : List[str]="<pad>" , A__ : Union[str, Any]="[CLS]" , A__ : Dict="[MASK]" , **A__ : Tuple , ) -> List[str]: '''simple docstring''' a__ : Optional[int] = ( AddedToken(A__ , lstrip=A__ , rstrip=A__ , normalized=A__ ) if isinstance(A__ , A__ ) else mask_token ) super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , **A__ , ) a__ : Optional[Any] = do_lower_case a__ : Dict = remove_space a__ : List[Any] = keep_accents a__ : Optional[Any] = vocab_file a__ : Any = False if not self.vocab_file else True def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : List[Any] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Dict = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : Tuple , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(A__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return a__ : Union[str, Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ): copyfile(self.vocab_file , A__ ) return (out_vocab_file,)
688
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ : """simple docstring""" def __init__( self : str ) -> Dict: '''simple docstring''' a__ : List[str] = False def __lowerCAmelCase ( self : Tuple , A__ : Optional[int] , A__ : Optional[Any] , A__ : List[str] , A__ : Tuple ) -> Optional[int]: '''simple docstring''' if not self.initialized: a__ : Optional[Any] = RagRetriever( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : Union[str, Any] = True def __lowerCAmelCase ( self : Tuple ) -> Tuple: '''simple docstring''' self.retriever.index.init_index() def __lowerCAmelCase ( self : List[Any] , A__ : List[Any] , A__ : Optional[int] ) -> List[Any]: '''simple docstring''' a__ , a__ : Optional[Any] = self.retriever._main_retrieve(A__ , A__ ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : Optional[int] , A__ : List[Any] , A__ : List[Any] , A__ : str , A__ : Any=None ) -> Optional[Any]: '''simple docstring''' if index is not None and index.is_initialized() and len(A__ ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : List[str] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(A__ , A__ , A__ , A__ ) for worker in self.retrieval_workers ] ) def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: '''simple docstring''' logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[int] , A__ : int ) -> Dict: '''simple docstring''' if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. a__ : List[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] a__ , a__ : Tuple = ray.get(random_worker.retrieve.remote(A__ , A__ ) ) else: a__ , a__ : int = self._main_retrieve(A__ , A__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[Any] , A__ : Any=None , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return super(A__ , cls ).get_tokenizers(A__ , A__ , **A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[int] , A__ : Union[str, Any] , A__ : Union[str, Any]=None , **A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Dict = kwargs.pop('''config''' , A__ ) or RagConfig.from_pretrained(A__ , **A__ ) a__ : Dict = RagTokenizer.from_pretrained(A__ , config=A__ ) a__ : str = rag_tokenizer.question_encoder a__ : List[str] = rag_tokenizer.generator if indexed_dataset is not None: a__ : List[Any] = '''custom''' a__ : List[Any] = CustomHFIndex(config.retrieval_vector_size , A__ ) else: a__ : Optional[Any] = cls._build_index(A__ ) return cls( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , retrieval_workers=A__ , index=A__ , )
688
1
'''simple docstring''' import string from math import logaa def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ): a__ : Tuple = document.translate( str.maketrans('''''' , '''''' , string.punctuation ) ).replace('''\n''' , '''''' ) a__ : Any = document_without_punctuation.split(''' ''' ) # word tokenization return len([word for word in tokenize_document if word.lower() == term.lower()] ) def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : str ): a__ : List[str] = corpus.lower().translate( str.maketrans('''''' , '''''' , string.punctuation ) ) # strip all punctuation and replace it with '' a__ : Dict = corpus_without_punctuation.split('''\n''' ) a__ : List[str] = term.lower() return (len([doc for doc in docs if term in doc] ), len(lowerCAmelCase__ )) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : int , lowerCAmelCase__ : Union[str, Any]=False ): if smoothing: if n == 0: raise ValueError('''log10(0) is undefined.''' ) return round(1 + logaa(n / (1 + df) ) , 3 ) if df == 0: raise ZeroDivisionError('''df must be > 0''' ) elif n == 0: raise ValueError('''log10(0) is undefined.''' ) return round(logaa(n / df ) , 3 ) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): return round(tf * idf , 3 )
688
'''simple docstring''' def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): a__ : List[str] = len(lowerCAmelCase__ ) a__ : int = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): a__ : Dict = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
688
1
'''simple docstring''' import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class lowerCAmelCase__ : """simple docstring""" def __init__( self : Dict , A__ : List[Any] , A__ : List[str]=1_3 , A__ : List[Any]=7 , A__ : Any=True , A__ : str=True , A__ : Dict=True , A__ : Optional[int]=True , A__ : int=9_9 , A__ : Any=6_4 , A__ : Dict=3_2 , A__ : Optional[Any]=5 , A__ : Optional[int]=4 , A__ : Any=3_7 , A__ : str="gelu" , A__ : Optional[Any]=0.1 , A__ : Union[str, Any]=0.1 , A__ : List[Any]=5_1_2 , A__ : Tuple=1_6 , A__ : Dict=2 , A__ : List[str]=0.02 , A__ : List[str]=3 , A__ : Dict=4 , A__ : Optional[Any]=None , ) -> str: '''simple docstring''' a__ : Optional[Any] = parent a__ : List[Any] = batch_size a__ : List[str] = seq_length a__ : List[Any] = is_training a__ : Dict = use_input_mask a__ : List[Any] = use_token_type_ids a__ : int = use_labels a__ : Dict = vocab_size a__ : List[Any] = hidden_size a__ : Any = embedding_size a__ : List[Any] = num_hidden_layers a__ : List[Any] = num_attention_heads a__ : Union[str, Any] = intermediate_size a__ : Optional[int] = hidden_act a__ : Optional[int] = hidden_dropout_prob a__ : Optional[Any] = attention_probs_dropout_prob a__ : List[str] = max_position_embeddings a__ : List[str] = type_vocab_size a__ : Optional[Any] = type_sequence_label_size a__ : Optional[int] = initializer_range a__ : Any = num_labels a__ : Optional[Any] = num_choices a__ : str = scope def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' a__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Any = None if self.use_input_mask: a__ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) a__ : Optional[Any] = None if self.use_token_type_ids: a__ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a__ : int = None a__ : Tuple = None a__ : List[Any] = None if self.use_labels: a__ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a__ : int = ids_tensor([self.batch_size] , self.num_choices ) a__ : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self : str ) -> Optional[int]: '''simple docstring''' return MegatronBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=A__ , initializer_range=self.initializer_range , ) def __lowerCAmelCase ( self : Tuple , A__ : Any , A__ : Dict , A__ : List[Any] , A__ : List[Any] , A__ : Union[str, Any] , A__ : Any , A__ : List[str] ) -> Dict: '''simple docstring''' a__ : Union[str, Any] = MegatronBertModel(config=A__ ) model.to(A__ ) model.eval() a__ : List[Any] = model(A__ , attention_mask=A__ , token_type_ids=A__ ) a__ : int = model(A__ , token_type_ids=A__ ) a__ : Union[str, Any] = model(A__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __lowerCAmelCase ( self : int , A__ : Tuple , A__ : Union[str, Any] , A__ : Union[str, Any] , A__ : Tuple , A__ : List[str] , A__ : List[str] , A__ : int ) -> Optional[Any]: '''simple docstring''' a__ : Any = MegatronBertForMaskedLM(config=A__ ) model.to(A__ ) model.eval() a__ : List[Any] = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : int , A__ : str , A__ : Union[str, Any] , A__ : str , A__ : Optional[int] , A__ : str , A__ : int , A__ : Union[str, Any] ) -> Any: '''simple docstring''' a__ : int = MegatronBertForCausalLM(config=A__ ) model.to(A__ ) model.eval() a__ : Tuple = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[Any] , A__ : Dict , A__ : List[Any] , A__ : Tuple , A__ : int , A__ : Tuple , A__ : str ) -> List[Any]: '''simple docstring''' a__ : str = MegatronBertForNextSentencePrediction(config=A__ ) model.to(A__ ) model.eval() a__ : List[Any] = model( A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __lowerCAmelCase ( self : str , A__ : Optional[int] , A__ : List[Any] , A__ : List[str] , A__ : Any , A__ : Any , A__ : str , A__ : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : int = MegatronBertForPreTraining(config=A__ ) model.to(A__ ) model.eval() a__ : Dict = model( A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ , next_sentence_label=A__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Any , A__ : Dict , A__ : Any , A__ : Dict , A__ : Optional[int] , A__ : Dict , A__ : int ) -> List[Any]: '''simple docstring''' a__ : Tuple = MegatronBertForQuestionAnswering(config=A__ ) model.to(A__ ) model.eval() a__ : Any = model( A__ , attention_mask=A__ , token_type_ids=A__ , start_positions=A__ , end_positions=A__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : Any , A__ : Dict , A__ : Optional[int] , A__ : int , A__ : str , A__ : Optional[Any] ) -> List[Any]: '''simple docstring''' a__ : List[Any] = self.num_labels a__ : Dict = MegatronBertForSequenceClassification(A__ ) model.to(A__ ) model.eval() a__ : int = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self : List[str] , A__ : str , A__ : Union[str, Any] , A__ : Tuple , A__ : Union[str, Any] , A__ : Any , A__ : int , A__ : Tuple ) -> Any: '''simple docstring''' a__ : Dict = self.num_labels a__ : int = MegatronBertForTokenClassification(config=A__ ) model.to(A__ ) model.eval() a__ : List[Any] = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self : Optional[Any] , A__ : Dict , A__ : Optional[int] , A__ : Tuple , A__ : str , A__ : Dict , A__ : Any , A__ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' a__ : Optional[Any] = self.num_choices a__ : str = MegatronBertForMultipleChoice(config=A__ ) model.to(A__ ) model.eval() a__ : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : Dict = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : Dict = model( A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self : Optional[int] ) -> Optional[Any]: '''simple docstring''' a__ : Dict = self.prepare_config_and_inputs() ( ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ) : Tuple = config_and_inputs a__ : Tuple = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": MegatronBertModel, "fill-mask": MegatronBertForMaskedLM, "question-answering": MegatronBertForQuestionAnswering, "text-classification": MegatronBertForSequenceClassification, "text-generation": MegatronBertForCausalLM, "token-classification": MegatronBertForTokenClassification, "zero-shot": MegatronBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = True # test_resize_embeddings = False __UpperCamelCase = False def __lowerCAmelCase ( self : List[str] , A__ : Dict , A__ : List[str] , A__ : Any=False ) -> List[str]: '''simple docstring''' a__ : Any = super()._prepare_for_class(A__ , A__ , return_labels=A__ ) if return_labels: if model_class in get_values(A__ ): a__ : Any = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=A__ ) a__ : int = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=A__ ) return inputs_dict def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' a__ : int = MegatronBertModelTester(self ) a__ : Union[str, Any] = ConfigTester(self , config_class=A__ , hidden_size=3_7 ) def __lowerCAmelCase ( self : List[str] ) -> Dict: '''simple docstring''' self.config_tester.run_common_tests() def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' a__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*A__ ) def __lowerCAmelCase ( self : List[Any] ) -> Optional[Any]: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*A__ ) def __lowerCAmelCase ( self : Any ) -> Optional[Any]: '''simple docstring''' a__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*A__ ) def __lowerCAmelCase ( self : str ) -> Any: '''simple docstring''' a__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*A__ ) def __lowerCAmelCase ( self : Any ) -> Tuple: '''simple docstring''' a__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*A__ ) def __lowerCAmelCase ( self : int ) -> int: '''simple docstring''' a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*A__ ) def __lowerCAmelCase ( self : Optional[int] ) -> Union[str, Any]: '''simple docstring''' a__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*A__ ) def __lowerCAmelCase ( self : int ) -> Tuple: '''simple docstring''' a__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*A__ ) def __a ( lowerCAmelCase__ : Optional[Any] ): return torch.tensor( lowerCAmelCase__ , dtype=torch.long , device=lowerCAmelCase__ , ) __SCREAMING_SNAKE_CASE = 1e-4 @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow @unittest.skip('''Model is not available.''' ) def __lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] = '''nvidia/megatron-bert-uncased-345m''' if "MYDIR" in os.environ: a__ : Union[str, Any] = os.path.join(os.environ['''MYDIR'''] , A__ ) a__ : List[Any] = MegatronBertModel.from_pretrained(A__ ) model.to(A__ ) model.half() a__ : Optional[int] = _long_tensor([[1_0_1, 7_1_1_0, 1_0_0_5, 1_0_5_6, 2_0_2_3, 1_1_3_3_3, 1_7_4_1_3, 1_0_2_9, 1_0_2]] ) with torch.no_grad(): a__ : Tuple = model(A__ )[0] a__ : Union[str, Any] = torch.Size((1, 9, 1_0_2_4) ) self.assertEqual(output.shape , A__ ) a__ : Any = [-0.6_040, -0.2_517, -0.1_025, 0.3_420, -0.6_758, -0.0_017, -0.1_089, -0.1_990, 0.5_728] for ii in range(3 ): for jj in range(3 ): a__ : List[Any] = output[0, ii, jj] a__ : List[Any] = expected[3 * ii + jj] a__ : int = '''ii={} jj={} a={} b={}'''.format(A__ , A__ , A__ , A__ ) self.assertTrue(math.isclose(A__ , A__ , rel_tol=A__ , abs_tol=A__ ) , msg=A__ )
688
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "swin2sr" __UpperCamelCase = { "hidden_size": "embed_dim", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] , A__ : int=6_4 , A__ : List[Any]=1 , A__ : List[Any]=3 , A__ : Any=1_8_0 , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Dict=8 , A__ : Any=2.0 , A__ : Optional[int]=True , A__ : Union[str, Any]=0.0 , A__ : Union[str, Any]=0.0 , A__ : List[str]=0.1 , A__ : Any="gelu" , A__ : Tuple=False , A__ : Optional[int]=0.02 , A__ : List[Any]=1E-5 , A__ : Any=2 , A__ : Union[str, Any]=1.0 , A__ : Dict="1conv" , A__ : Optional[Any]="pixelshuffle" , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : List[str] = image_size a__ : Optional[Any] = patch_size a__ : Dict = num_channels a__ : Optional[int] = embed_dim a__ : int = depths a__ : Optional[int] = len(A__ ) a__ : Dict = num_heads a__ : List[Any] = window_size a__ : Optional[int] = mlp_ratio a__ : Optional[int] = qkv_bias a__ : Union[str, Any] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Union[str, Any] = drop_path_rate a__ : int = hidden_act a__ : int = use_absolute_embeddings a__ : Dict = layer_norm_eps a__ : List[str] = initializer_range a__ : List[Any] = upscale a__ : List[Any] = img_range a__ : Optional[int] = resi_connection a__ : int = upsampler
688
1
'''simple docstring''' import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Any ): if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def __a ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : str ): return max(metric_fn(lowerCAmelCase__ , lowerCAmelCase__ ) for gt in ground_truths ) def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : int ): a__ : Union[str, Any] = [line.strip() for line in open(lowerCAmelCase__ , '''r''' ).readlines()] a__ : Union[str, Any] = [] if args.gold_data_mode == "qa": a__ : Dict = pd.read_csv(lowerCAmelCase__ , sep='''\t''' , header=lowerCAmelCase__ ) for answer_list in data[1]: a__ : Any = ast.literal_eval(lowerCAmelCase__ ) answers.append(lowerCAmelCase__ ) else: a__ : int = [line.strip() for line in open(lowerCAmelCase__ , '''r''' ).readlines()] a__ : List[Any] = [[reference] for reference in references] a__ : Optional[int] = 0 for prediction, ground_truths in zip(lowerCAmelCase__ , lowerCAmelCase__ ): total += 1 em += metric_max_over_ground_truths(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) fa += metric_max_over_ground_truths(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) a__ : List[str] = 100.0 * em / total a__ : List[str] = 100.0 * fa / total logger.info(F'F1: {fa:.2f}' ) logger.info(F'EM: {em:.2f}' ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[int] ): a__ : List[str] = args.k a__ : Dict = [line.strip() for line in open(lowerCAmelCase__ , '''r''' ).readlines()] a__ : Any = [line.strip() for line in open(lowerCAmelCase__ , '''r''' ).readlines()] a__ : Optional[Any] = 0 for hypo, reference in zip(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : List[str] = set(hypo.split('''\t''' )[:k] ) a__ : Tuple = set(reference.split('''\t''' ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k a__ : Optional[Any] = 100.0 * em / total logger.info(F'Precision@{k}: {em: .2f}' ) def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : Any , lowerCAmelCase__ : List[str] ): def strip_title(lowerCAmelCase__ : Optional[int] ): if title.startswith('''"''' ): a__ : Optional[Any] = title[1:] if title.endswith('''"''' ): a__ : str = title[:-1] return title a__ : List[Any] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase__ , return_tensors='''pt''' , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , )['''input_ids'''].to(args.device ) a__ : Optional[Any] = rag_model.rag.question_encoder(lowerCAmelCase__ ) a__ : List[Any] = question_enc_outputs[0] a__ : Any = rag_model.retriever( lowerCAmelCase__ , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors='''pt''' , ) a__ : Union[str, Any] = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) a__ : str = [] for docs in all_docs: a__ : Any = [strip_title(lowerCAmelCase__ ) for title in docs['''title''']] provenance_strings.append('''\t'''.join(lowerCAmelCase__ ) ) return provenance_strings def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[str] ): with torch.no_grad(): a__ : Dict = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( lowerCAmelCase__ , return_tensors='''pt''' , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ ) a__ : Tuple = inputs_dict.input_ids.to(args.device ) a__ : Optional[int] = inputs_dict.attention_mask.to(args.device ) a__ : Optional[Any] = rag_model.generate( # rag_model overwrites generate lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=lowerCAmelCase__ , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) a__ : str = rag_model.retriever.generator_tokenizer.batch_decode(lowerCAmelCase__ , skip_special_tokens=lowerCAmelCase__ ) if args.print_predictions: for q, a in zip(lowerCAmelCase__ , lowerCAmelCase__ ): logger.info('''Q: {} - A: {}'''.format(lowerCAmelCase__ , lowerCAmelCase__ ) ) return answers def __a ( ): a__ : Optional[int] = argparse.ArgumentParser() parser.add_argument( '''--model_type''' , choices=['''rag_sequence''', '''rag_token''', '''bart'''] , type=lowerCAmelCase__ , help=( '''RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the''' ''' model_name_or_path''' ) , ) parser.add_argument( '''--index_name''' , default=lowerCAmelCase__ , choices=['''exact''', '''compressed''', '''legacy'''] , type=lowerCAmelCase__ , help='''RAG model retriever type''' , ) parser.add_argument( '''--index_path''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , help='''Path to the retrieval index''' , ) parser.add_argument('''--n_docs''' , default=5 , type=lowerCAmelCase__ , help='''Number of retrieved docs''' ) parser.add_argument( '''--model_name_or_path''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''Path to pretrained checkpoints or model identifier from huggingface.co/models''' , ) parser.add_argument( '''--eval_mode''' , choices=['''e2e''', '''retrieval'''] , default='''e2e''' , type=lowerCAmelCase__ , help=( '''Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates''' ''' precision@k.''' ) , ) parser.add_argument('''--k''' , default=1 , type=lowerCAmelCase__ , help='''k for the precision@k calculation''' ) parser.add_argument( '''--evaluation_set''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''Path to a file containing evaluation samples''' , ) parser.add_argument( '''--gold_data_path''' , default=lowerCAmelCase__ , type=lowerCAmelCase__ , required=lowerCAmelCase__ , help='''Path to a tab-separated file with gold samples''' , ) parser.add_argument( '''--gold_data_mode''' , default='''qa''' , type=lowerCAmelCase__ , choices=['''qa''', '''ans'''] , help=( '''Format of the gold data file''' '''qa - a single line in the following format: question [tab] answer_list''' '''ans - a single line of the gold file contains the expected answer string''' ) , ) parser.add_argument( '''--predictions_path''' , type=lowerCAmelCase__ , default='''predictions.txt''' , help='''Name of the predictions file, to be stored in the checkpoints directory''' , ) parser.add_argument( '''--eval_all_checkpoints''' , action='''store_true''' , help='''Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number''' , ) parser.add_argument( '''--eval_batch_size''' , default=8 , type=lowerCAmelCase__ , help='''Batch size per GPU/CPU for evaluation.''' , ) parser.add_argument( '''--recalculate''' , help='''Recalculate predictions even if the prediction file exists''' , action='''store_true''' , ) parser.add_argument( '''--num_beams''' , default=4 , type=lowerCAmelCase__ , help='''Number of beams to be used when generating answers''' , ) parser.add_argument('''--min_length''' , default=1 , type=lowerCAmelCase__ , help='''Min length of the generated answers''' ) parser.add_argument('''--max_length''' , default=50 , type=lowerCAmelCase__ , help='''Max length of the generated answers''' ) parser.add_argument( '''--print_predictions''' , action='''store_true''' , help='''If True, prints predictions while evaluating.''' , ) parser.add_argument( '''--print_docs''' , action='''store_true''' , help='''If True, prints docs retried while generating.''' , ) a__ : Dict = parser.parse_args() a__ : List[str] = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' ) return args def __a ( lowerCAmelCase__ : int ): a__ : List[str] = {} if args.model_type is None: a__ : Optional[Any] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith('''rag''' ): a__ : Tuple = RagTokenForGeneration if args.model_type == '''rag_token''' else RagSequenceForGeneration a__ : List[Any] = args.n_docs if args.index_name is not None: a__ : str = args.index_name if args.index_path is not None: a__ : Tuple = args.index_path else: a__ : Tuple = BartForConditionalGeneration a__ : str = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info('''Evaluate the following checkpoints: %s''' , lowerCAmelCase__ ) a__ : List[str] = get_scores if args.eval_mode == '''e2e''' else get_precision_at_k a__ : Optional[int] = evaluate_batch_eae if args.eval_mode == '''e2e''' else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info('''Calculating metrics based on an existing predictions file: {}'''.format(args.predictions_path ) ) score_fn(lowerCAmelCase__ , args.predictions_path , args.gold_data_path ) continue logger.info('''***** Running evaluation for {} *****'''.format(lowerCAmelCase__ ) ) logger.info(''' Batch size = %d''' , args.eval_batch_size ) logger.info(''' Predictions will be stored under {}'''.format(args.predictions_path ) ) if args.model_type.startswith('''rag''' ): a__ : Any = RagRetriever.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Tuple = model_class.from_pretrained(lowerCAmelCase__ , retriever=lowerCAmelCase__ , **lowerCAmelCase__ ) model.retriever.init_retrieval() else: a__ : str = model_class.from_pretrained(lowerCAmelCase__ , **lowerCAmelCase__ ) model.to(args.device ) with open(args.evaluation_set , '''r''' ) as eval_file, open(args.predictions_path , '''w''' ) as preds_file: a__ : List[Any] = [] for line in tqdm(lowerCAmelCase__ ): questions.append(line.strip() ) if len(lowerCAmelCase__ ) == args.eval_batch_size: a__ : Optional[int] = evaluate_batch_fn(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) preds_file.write('''\n'''.join(lowerCAmelCase__ ) + '''\n''' ) preds_file.flush() a__ : List[str] = [] if len(lowerCAmelCase__ ) > 0: a__ : str = evaluate_batch_fn(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) preds_file.write('''\n'''.join(lowerCAmelCase__ ) ) preds_file.flush() score_fn(lowerCAmelCase__ , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = get_args() main(args)
688
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : int = 0 def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[Any] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[Any] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[int] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict() config_dict.pop('''image_processor_type''' ) a__ : Union[str, Any] = CLIPImageProcessor(**A__ ) # save in new folder model_config.save_pretrained(A__ ) config.save_pretrained(A__ ) a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ ) # make sure private variable is not incorrectly saved a__ : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''clip-base is not a local folder and is not a valid model identifier''' ): a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' with self.assertRaises(A__ ): a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoImageProcessor.register(A__ , A__ ) with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[str] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = CustomImageProcessor.from_pretrained(A__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = True try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # If remote code is not set, the default is to use local a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. a__ : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub a__ : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(A__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
688
1
'''simple docstring''' def __a ( lowerCAmelCase__ : str ): return " ".join( ''''''.join(word[::-1] ) if len(lowerCAmelCase__ ) > 4 else word for word in sentence.split() ) if __name__ == "__main__": import doctest doctest.testmod() print(reverse_long_words('Hey wollef sroirraw'))
688
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version __SCREAMING_SNAKE_CASE = get_logger(__name__) class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = "dummy_data" __UpperCamelCase = "datasets" __UpperCamelCase = False def __init__( self : Any , A__ : str , A__ : str , A__ : Union[Version, str] , A__ : Optional[str] = None , A__ : bool = False , A__ : bool = True , A__ : Optional[List[Callable]] = None , ) -> int: '''simple docstring''' a__ : Tuple = 0 a__ : Any = dataset_name a__ : int = cache_dir a__ : str = use_local_dummy_data a__ : List[str] = config # download_callbacks take a single url as input a__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root a__ : str = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general a__ : Optional[Any] = str(A__ ) # to be downloaded a__ : Tuple = None a__ : Tuple = None @property def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' if self._dummy_file is None: a__ : Dict = self.download_dummy_data() return self._dummy_file @property def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('''dummy''' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('''dummy''' , self.version_name ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : int = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) a__ : str = cached_path( A__ , cache_dir=self.cache_dir , extract_compressed_file=A__ , force_extract=A__ ) return os.path.join(A__ , self.dummy_file_name ) @property def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self._bucket_url is None: a__ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) ) return self._bucket_url @property def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , *A__ : int ) -> Union[str, Any]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested a__ : Tuple = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned a__ : Union[str, Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(A__ , A__ ): return self.create_dummy_data_dict(A__ , A__ ) elif isinstance(A__ , (list, tuple) ): return self.create_dummy_data_list(A__ , A__ ) else: return self.create_dummy_data_single(A__ , A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Any , *A__ : int ) -> Any: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Any , A__ : Optional[int] , A__ : Optional[Any] ) -> int: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , *A__ : List[Any] , **A__ : str ) -> Optional[Any]: '''simple docstring''' return path def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' return {} def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[str] ) -> Any: '''simple docstring''' a__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A__ , A__ ): for single_url in single_urls: download_callback(A__ ) else: a__ : Dict = single_urls download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A__ , A__ ): a__ : Optional[int] = [os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) for x in single_urls] else: a__ : Optional[Any] = single_urls a__ : Tuple = os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) a__ : List[str] = value # make sure that values are unique if all(isinstance(A__ , A__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique a__ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : str = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one a__ : Union[str, Any] = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , A__ ) ) for url in data_url ) a__ : Optional[Any] = all( url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): a__ : Dict = [data_url[0]] * len(A__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Optional[int] = os.path.join(A__ , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) ) dummy_data_list.append(A__ ) return dummy_data_list def __lowerCAmelCase ( self : Dict , A__ : Dict , A__ : str ) -> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Union[str, Any] = os.path.join(A__ , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) ) if os.path.exists(A__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' pass def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: '''simple docstring''' pass def __lowerCAmelCase ( self : Any , A__ : Tuple ) -> Any: '''simple docstring''' def _iter_archive_members(A__ : str ): # this preserves the order of the members inside the ZIP archive a__ : Dict = Path(self.dummy_file ).parent a__ : Tuple = path.relative_to(A__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: a__ : Optional[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A__ ) a__ : str = Path(A__ ) a__ : Optional[Any] = _iter_archive_members(A__ ) if self.use_local_dummy_data else path.rglob('''*''' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ): yield file_path.relative_to(A__ ).as_posix(), file_path.open('''rb''' ) def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> Tuple: '''simple docstring''' if not isinstance(A__ , A__ ): a__ : int = [paths] for path in paths: if os.path.isfile(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): return yield path else: for dirpath, dirnames, filenames in os.walk(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): continue dirnames.sort() for filename in sorted(A__ ): if filename.startswith(('''.''', '''__''') ): continue yield os.path.join(A__ , A__ )
688
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __SCREAMING_SNAKE_CASE = {'configuration_mbart': ['MBART_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MBartConfig', 'MBartOnnxConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = ['MBartTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = ['MBartTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'MBART_PRETRAINED_MODEL_ARCHIVE_LIST', 'MBartForCausalLM', 'MBartForConditionalGeneration', 'MBartForQuestionAnswering', 'MBartForSequenceClassification', 'MBartModel', 'MBartPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'TFMBartForConditionalGeneration', 'TFMBartModel', 'TFMBartPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'FlaxMBartForConditionalGeneration', 'FlaxMBartForQuestionAnswering', 'FlaxMBartForSequenceClassification', 'FlaxMBartModel', 'FlaxMBartPreTrainedModel', ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
688
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = LxmertTokenizer __UpperCamelCase = LxmertTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' super().setUp() a__ : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : int , A__ : int ) -> int: '''simple docstring''' a__ : List[Any] = '''UNwant\u00E9d,running''' a__ : Optional[int] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ : Optional[int] = self.tokenizer_class(self.vocab_file ) a__ : List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [7, 4, 5, 1_0, 8, 9] ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__ : Union[str, Any] = self.get_tokenizer() a__ : Union[str, Any] = self.get_rust_tokenizer() a__ : str = '''I was born in 92000, and this is falsé.''' a__ : Tuple = tokenizer.tokenize(A__ ) a__ : Tuple = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) a__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : str = tokenizer.encode(A__ ) a__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ )
688
1
'''simple docstring''' from pathlib import Path import numpy as np from PIL import Image def __a ( lowerCAmelCase__ : np.ndarray ): a__ , a__ , a__ : Dict = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def __a ( lowerCAmelCase__ : np.ndarray ): return (gray > 127) & (gray <= 255) def __a ( lowerCAmelCase__ : np.ndarray , lowerCAmelCase__ : np.ndarray ): a__ : Any = np.zeros_like(lowerCAmelCase__ ) a__ : Optional[Any] = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image a__ : int = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): a__ : Optional[int] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() a__ : str = int(summation > 0 ) return output if __name__ == "__main__": # read original image __SCREAMING_SNAKE_CASE = Path(__file__).resolve().parent / 'image_data' / 'lena.jpg' __SCREAMING_SNAKE_CASE = np.array(Image.open(lena_path)) # kernel to be applied __SCREAMING_SNAKE_CASE = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) __SCREAMING_SNAKE_CASE = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image __SCREAMING_SNAKE_CASE = Image.fromarray(output).convert('RGB') pil_img.save('result_dilation.png')
688
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file a__ : Dict = TapasConfig.from_json_file(lowerCAmelCase__ ) # set absolute/relative position embeddings parameter a__ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": a__ : Optional[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WTQ": # run_task_main.py hparams a__ : List[str] = 4 a__ : Optional[int] = True # hparam_utils.py hparams a__ : List[Any] = 0.664694 a__ : List[Any] = 0.207951 a__ : Union[str, Any] = 0.121194 a__ : Optional[Any] = True a__ : Optional[int] = True a__ : List[str] = False a__ : Union[str, Any] = 0.0352513 a__ : Any = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams a__ : Tuple = 4 a__ : Dict = False # hparam_utils.py hparams a__ : str = 36.4519 a__ : str = 0.903421 a__ : Optional[Any] = 222.088 a__ : Dict = True a__ : Dict = True a__ : Dict = True a__ : str = 0.763141 a__ : List[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "TABFACT": a__ : List[str] = TapasForSequenceClassification(config=lowerCAmelCase__ ) elif task == "MLM": a__ : Tuple = TapasForMaskedLM(config=lowerCAmelCase__ ) elif task == "INTERMEDIATE_PRETRAINING": a__ : List[str] = TapasModel(config=lowerCAmelCase__ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase__ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) a__ : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase__ ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
688
1
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device if is_torch_available(): from transformers import AutoModelForSeqaSeqLM, AutoTokenizer @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def __lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' a__ : int = AutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''' , return_dict=A__ ).to(A__ ) a__ : Optional[int] = AutoTokenizer.from_pretrained('''google/mt5-small''' ) a__ : Optional[Any] = tokenizer('''Hello there''' , return_tensors='''pt''' ).input_ids a__ : Optional[int] = tokenizer('''Hi I am''' , return_tensors='''pt''' ).input_ids a__ : Any = model(input_ids.to(A__ ) , labels=labels.to(A__ ) ).loss a__ : str = -(labels.shape[-1] * loss.item()) a__ : Dict = -84.9_127 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
688
'''simple docstring''' 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_fnet import FNetTokenizer else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } __SCREAMING_SNAKE_CASE = { 'google/fnet-base': 5_1_2, 'google/fnet-large': 5_1_2, } __SCREAMING_SNAKE_CASE = '▁' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "token_type_ids"] __UpperCamelCase = FNetTokenizer def __init__( self : Any , A__ : Any=None , A__ : int=None , A__ : List[str]=False , A__ : int=True , A__ : str=True , A__ : List[Any]="<unk>" , A__ : Dict="[SEP]" , A__ : List[str]="<pad>" , A__ : Union[str, Any]="[CLS]" , A__ : Dict="[MASK]" , **A__ : Tuple , ) -> List[str]: '''simple docstring''' a__ : Optional[int] = ( AddedToken(A__ , lstrip=A__ , rstrip=A__ , normalized=A__ ) if isinstance(A__ , A__ ) else mask_token ) super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , **A__ , ) a__ : Optional[Any] = do_lower_case a__ : Dict = remove_space a__ : List[Any] = keep_accents a__ : Optional[Any] = vocab_file a__ : Any = False if not self.vocab_file else True def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : List[Any] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Dict = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : Tuple , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(A__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return a__ : Union[str, Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ): copyfile(self.vocab_file , A__ ) return (out_vocab_file,)
688
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int=False ): a__ : Optional[int] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F'blocks.{i}.norm1.weight', F'deit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((F'blocks.{i}.norm1.bias', F'deit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((F'blocks.{i}.attn.proj.weight', F'deit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((F'blocks.{i}.attn.proj.bias', F'deit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((F'blocks.{i}.norm2.weight', F'deit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((F'blocks.{i}.norm2.bias', F'deit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc1.weight', F'deit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc1.bias', F'deit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((F'blocks.{i}.mlp.fc2.weight', F'deit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((F'blocks.{i}.mlp.fc2.bias', F'deit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ('''cls_token''', '''deit.embeddings.cls_token'''), ('''dist_token''', '''deit.embeddings.distillation_token'''), ('''patch_embed.proj.weight''', '''deit.embeddings.patch_embeddings.projection.weight'''), ('''patch_embed.proj.bias''', '''deit.embeddings.patch_embeddings.projection.bias'''), ('''pos_embed''', '''deit.embeddings.position_embeddings'''), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('''norm.weight''', '''layernorm.weight'''), ('''norm.bias''', '''layernorm.bias'''), ('''pre_logits.fc.weight''', '''pooler.dense.weight'''), ('''pre_logits.fc.bias''', '''pooler.dense.bias'''), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" a__ : int = [(pair[0], pair[1][4:]) if pair[1].startswith('''deit''' ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ('''norm.weight''', '''deit.layernorm.weight'''), ('''norm.bias''', '''deit.layernorm.bias'''), ('''head.weight''', '''cls_classifier.weight'''), ('''head.bias''', '''cls_classifier.bias'''), ('''head_dist.weight''', '''distillation_classifier.weight'''), ('''head_dist.bias''', '''distillation_classifier.bias'''), ] ) return rename_keys def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Union[str, Any]=False ): for i in range(config.num_hidden_layers ): if base_model: a__ : Optional[int] = '''''' else: a__ : Optional[int] = '''deit.''' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) a__ : Union[str, Any] = state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) a__ : Optional[int] = state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict a__ : Optional[int] = in_proj_weight[ : config.hidden_size, : ] a__ : List[Any] = in_proj_bias[: config.hidden_size] a__ : List[str] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] a__ : Dict = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] a__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] a__ : str = in_proj_bias[-config.hidden_size :] def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : str ): a__ : Optional[int] = dct.pop(lowerCAmelCase__ ) a__ : Tuple = val def __a ( ): a__ : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' a__ : Dict = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return im @torch.no_grad() def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[Any] ): a__ : Any = DeiTConfig() # all deit models have fine-tuned heads a__ : Optional[int] = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size a__ : Dict = 1000 a__ : Union[str, Any] = '''huggingface/label-files''' a__ : Optional[Any] = '''imagenet-1k-id2label.json''' a__ : Tuple = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type='''dataset''' ) , '''r''' ) ) a__ : List[Any] = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} a__ : int = idalabel a__ : List[str] = {v: k for k, v in idalabel.items()} a__ : List[Any] = int(deit_name[-6:-4] ) a__ : List[str] = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith('''tiny''' ): a__ : Optional[int] = 192 a__ : Any = 768 a__ : Tuple = 12 a__ : Dict = 3 elif deit_name[9:].startswith('''small''' ): a__ : List[Any] = 384 a__ : List[str] = 1536 a__ : int = 12 a__ : List[str] = 6 if deit_name[9:].startswith('''base''' ): pass elif deit_name[4:].startswith('''large''' ): a__ : Union[str, Any] = 1024 a__ : List[str] = 4096 a__ : Any = 24 a__ : List[str] = 16 # load original model from timm a__ : List[str] = timm.create_model(lowerCAmelCase__ , pretrained=lowerCAmelCase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys a__ : str = timm_model.state_dict() a__ : Optional[Any] = create_rename_keys(lowerCAmelCase__ , lowerCAmelCase__ ) for src, dest in rename_keys: rename_key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) read_in_q_k_v(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # load HuggingFace model a__ : Any = DeiTForImageClassificationWithTeacher(lowerCAmelCase__ ).eval() model.load_state_dict(lowerCAmelCase__ ) # Check outputs on an image, prepared by DeiTImageProcessor a__ : Dict = int( (256 / 224) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 a__ : List[str] = DeiTImageProcessor(size=lowerCAmelCase__ , crop_size=config.image_size ) a__ : Optional[Any] = image_processor(images=prepare_img() , return_tensors='''pt''' ) a__ : List[str] = encoding['''pixel_values'''] a__ : Tuple = model(lowerCAmelCase__ ) a__ : Tuple = timm_model(lowerCAmelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowerCAmelCase__ , outputs.logits , atol=1E-3 ) Path(lowerCAmelCase__ ).mkdir(exist_ok=lowerCAmelCase__ ) print(F'Saving model {deit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase__ ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--deit_name', default='vit_deit_base_distilled_patch16_224', type=str, help='Name of the DeiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
688
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { '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' ), }, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': 5_1_2, 'distilbert-base-uncased-distilled-squad': 5_1_2, 'distilbert-base-cased': 5_1_2, 'distilbert-base-cased-distilled-squad': 5_1_2, 'distilbert-base-german-cased': 5_1_2, 'distilbert-base-multilingual-cased': 5_1_2, } __SCREAMING_SNAKE_CASE = { '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 lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = DistilBertTokenizer def __init__( self : str , A__ : Optional[Any]=None , A__ : Any=None , A__ : Tuple=True , A__ : List[Any]="[UNK]" , A__ : List[str]="[SEP]" , A__ : Tuple="[PAD]" , A__ : Optional[int]="[CLS]" , A__ : Union[str, Any]="[MASK]" , A__ : List[str]=True , A__ : Any=None , **A__ : int , ) -> str: '''simple docstring''' super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , tokenize_chinese_chars=A__ , strip_accents=A__ , **A__ , ) a__ : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , A__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , A__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , A__ ) != tokenize_chinese_chars ): a__ : int = getattr(A__ , normalizer_state.pop('''type''' ) ) a__ : List[Any] = do_lower_case a__ : str = strip_accents a__ : List[str] = tokenize_chinese_chars a__ : Dict = normalizer_class(**A__ ) a__ : List[Any] = do_lower_case def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Dict=None ) -> List[str]: '''simple docstring''' a__ : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : int , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : List[str] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : str , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' a__ : int = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
688
1
'''simple docstring''' import json import os import unittest from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = BioGptTokenizer __UpperCamelCase = False def __lowerCAmelCase ( self : int ) -> Optional[Any]: '''simple docstring''' super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt a__ : int = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''w</w>''', '''r</w>''', '''t</w>''', '''lo''', '''low''', '''er</w>''', '''low</w>''', '''lowest</w>''', '''newer</w>''', '''wider</w>''', '''<unk>''', ] a__ : Any = dict(zip(A__ , range(len(A__ ) ) ) ) a__ : Any = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', ''''''] a__ : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) a__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' ) as fp: fp.write(json.dumps(A__ ) ) with open(self.merges_file , '''w''' ) as fp: fp.write('''\n'''.join(A__ ) ) def __lowerCAmelCase ( self : List[Any] , A__ : Union[str, Any] ) -> List[str]: '''simple docstring''' a__ : Dict = '''lower newer''' a__ : List[Any] = '''lower newer''' return input_text, output_text def __lowerCAmelCase ( self : Optional[int] ) -> List[str]: '''simple docstring''' a__ : Optional[Any] = BioGptTokenizer(self.vocab_file , self.merges_file ) a__ : Any = '''lower''' a__ : Dict = ['''low''', '''er</w>'''] a__ : List[Any] = tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Union[str, Any] = tokens + ['''<unk>'''] a__ : str = [1_4, 1_5, 2_0] self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , A__ ) @slow def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' a__ : List[str] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) a__ : Union[str, Any] = tokenizer.encode('''sequence builders''' , add_special_tokens=A__ ) a__ : Any = tokenizer.encode('''multi-sequence build''' , add_special_tokens=A__ ) a__ : Union[str, Any] = tokenizer.build_inputs_with_special_tokens(A__ ) a__ : Optional[int] = tokenizer.build_inputs_with_special_tokens(A__ , A__ ) self.assertTrue(encoded_sentence == [2] + text ) self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
688
'''simple docstring''' from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __SCREAMING_SNAKE_CASE = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right __SCREAMING_SNAKE_CASE = tuple[int, int] class lowerCAmelCase__ : """simple docstring""" def __init__( self : str , A__ : int , A__ : int , A__ : int , A__ : int , A__ : int , A__ : Node | None , ) -> None: '''simple docstring''' a__ : Optional[int] = pos_x a__ : str = pos_y a__ : Optional[int] = (pos_y, pos_x) a__ : List[str] = goal_x a__ : Any = goal_y a__ : Any = g_cost a__ : Optional[int] = parent a__ : Union[str, Any] = self.calculate_heuristic() a__ : List[Any] = self.g_cost + self.h_cost def __lowerCAmelCase ( self : Union[str, Any] ) -> float: '''simple docstring''' a__ : List[str] = self.pos_x - self.goal_x a__ : List[str] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(A__ ) + abs(A__ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : List[Any] , A__ : Node ) -> bool: '''simple docstring''' return self.f_cost < other.f_cost class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] , A__ : TPosition , A__ : TPosition ) -> Optional[Any]: '''simple docstring''' a__ : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , A__ ) a__ : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , A__ ) a__ : Dict = [self.start] a__ : list[Node] = [] a__ : str = False def __lowerCAmelCase ( self : List[str] ) -> list[TPosition]: '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() a__ : Dict = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(A__ ) self.closed_nodes.append(A__ ) a__ : List[Any] = self.get_successors(A__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[int] = self.open_nodes.pop(self.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(A__ ) else: self.open_nodes.append(A__ ) return [self.start.pos] def __lowerCAmelCase ( self : Optional[Any] , A__ : Node ) -> list[Node]: '''simple docstring''' a__ : Optional[int] = [] for action in delta: a__ : List[Any] = parent.pos_x + action[1] a__ : Tuple = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(A__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( A__ , A__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , A__ , ) ) return successors def __lowerCAmelCase ( self : List[Any] , A__ : Node | None ) -> list[TPosition]: '''simple docstring''' a__ : Union[str, Any] = node a__ : Optional[Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) a__ : Any = current_node.parent path.reverse() return path class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , A__ : TPosition , A__ : TPosition ) -> None: '''simple docstring''' a__ : str = AStar(A__ , A__ ) a__ : Optional[int] = AStar(A__ , A__ ) a__ : List[str] = False def __lowerCAmelCase ( self : Tuple ) -> list[TPosition]: '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() a__ : int = self.fwd_astar.open_nodes.pop(0 ) a__ : List[Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( A__ , A__ ) self.fwd_astar.closed_nodes.append(A__ ) self.bwd_astar.closed_nodes.append(A__ ) a__ : Tuple = current_bwd_node a__ : Optional[int] = current_fwd_node a__ : Optional[int] = { self.fwd_astar: self.fwd_astar.get_successors(A__ ), self.bwd_astar: self.bwd_astar.get_successors(A__ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[Any] = astar.open_nodes.pop( astar.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(A__ ) else: astar.open_nodes.append(A__ ) return [self.fwd_astar.start.pos] def __lowerCAmelCase ( self : List[str] , A__ : Node , A__ : Node ) -> list[TPosition]: '''simple docstring''' a__ : str = self.fwd_astar.retrace_path(A__ ) a__ : List[str] = self.bwd_astar.retrace_path(A__ ) bwd_path.pop() bwd_path.reverse() a__ : Optional[int] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] __SCREAMING_SNAKE_CASE = (0, 0) __SCREAMING_SNAKE_CASE = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = AStar(init, goal) __SCREAMING_SNAKE_CASE = a_star.search() __SCREAMING_SNAKE_CASE = time.time() - start_time print(f'AStar execution time = {end_time:f} seconds') __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = BidirectionalAStar(init, goal) __SCREAMING_SNAKE_CASE = time.time() - bd_start_time print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
688
1
'''simple docstring''' # XXX: we want transformers master here - in the absense of conftest manipulating sys.path: # hack it in for now: import sys from pathlib import Path __SCREAMING_SNAKE_CASE = Path(__file__).resolve().parents[3] / 'src' sys.path.insert(1, str(git_repo_path)) import dataclasses # noqa import io # noqa import itertools # noqa import json # noqa import os # noqa import unittest # noqa from copy import deepcopy # noqa from parameterized import parameterized # noqa from transformers import TrainingArguments, is_torch_available # noqa from transformers.deepspeed import is_deepspeed_available # noqa from transformers.file_utils import WEIGHTS_NAME # noqa from transformers.testing_utils import ( # noqa CaptureLogger, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, mockenv_context, require_deepspeed, require_torch_gpu, require_torch_multi_gpu, slow, ) from transformers.trainer_utils import set_seed # noqa set_seed(4_2) __SCREAMING_SNAKE_CASE = {'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'} __SCREAMING_SNAKE_CASE = 'zero2' __SCREAMING_SNAKE_CASE = 'zero3' __SCREAMING_SNAKE_CASE = [ZEROa, ZEROa] def __a ( lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[Any] ): # customize the test name generator function as we want both params to appear in the sub-test # name, as by default it shows only the first param a__ : Dict = parameterized.to_safe_name('''_'''.join(str(lowerCAmelCase__ ) for x in param.args ) ) return F'{func.__name__}_{param_based_name}' # Cartesian-product of zero stages with models to test __SCREAMING_SNAKE_CASE = list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" @parameterized.expand(A__ , name_func=A__ ) def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[Any] , A__ : int ) -> Union[str, Any]: '''simple docstring''' self.run_and_check( stage=A__ , model=A__ , distributed=A__ , fpaa=A__ , ) @require_torch_multi_gpu @parameterized.expand(A__ , name_func=A__ ) def __lowerCAmelCase ( self : str , A__ : Tuple , A__ : Optional[int] ) -> Tuple: '''simple docstring''' self.run_and_check( stage=A__ , model=A__ , distributed=A__ , fpaa=A__ , ) @parameterized.expand(A__ , name_func=A__ ) def __lowerCAmelCase ( self : Optional[int] , A__ : str , A__ : Any ) -> List[str]: '''simple docstring''' self.run_and_check( stage=A__ , model=A__ , distributed=A__ , fpaa=A__ , ) @require_torch_multi_gpu @parameterized.expand(A__ , name_func=A__ ) def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Union[str, Any] ) -> Dict: '''simple docstring''' self.run_and_check( stage=A__ , model=A__ , distributed=A__ , fpaa=A__ , ) def __lowerCAmelCase ( self : List[str] , A__ : Tuple ) -> Optional[Any]: '''simple docstring''' pass def __lowerCAmelCase ( self : Optional[int] , A__ : str , A__ : str , A__ : int = 1_0 , A__ : bool = True , A__ : bool = True , A__ : bool = True , ) -> List[Any]: '''simple docstring''' a__ : Any = models[model] a__ : List[Any] = self.run_trainer( stage=A__ , model_name=A__ , eval_steps=A__ , num_train_epochs=1 , distributed=A__ , fpaa=A__ , ) self.do_checks(A__ ) return output_dir def __lowerCAmelCase ( self : Optional[int] , A__ : str , A__ : str , A__ : int = 1_0 , A__ : int = 1 , A__ : bool = True , A__ : bool = True , ) -> Optional[int]: '''simple docstring''' a__ : str = self.get_auto_remove_tmp_dir('''./xxx''' , after=A__ ) a__ : str = F'\n --model_name_or_path {model_name}\n --dataset_name hf-internal-testing/librispeech_asr_dummy\n --dataset_config_name clean\n --train_split_name validation\n --validation_split_name validation\n --output_dir {output_dir}\n --num_train_epochs {str(A__ )}\n --per_device_train_batch_size 2\n --per_device_eval_batch_size 2\n --evaluation_strategy steps\n --learning_rate 5e-4\n --warmup_steps 8\n --orthography timit\n --preprocessing_num_workers 1\n --group_by_length\n --freeze_feature_extractor\n --report_to none\n --save_steps 0\n --eval_steps {eval_steps}\n --report_to none\n '.split() if fpaa: args.extend(['''--fp16'''] ) # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true, # hence the separate config files a__ : Union[str, Any] = F'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split() a__ : int = [F'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py'] a__ : int = self.get_launcher(A__ ) a__ : List[str] = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(A__ , env=self.get_env() ) return output_dir def __lowerCAmelCase ( self : List[Any] , A__ : Union[str, Any]=False ) -> List[Any]: '''simple docstring''' a__ : int = min(2 , get_gpu_count() ) if distributed else 1 return F'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()
688
'''simple docstring''' import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] ): # Construct model if gpta_config_file == "": a__ : Union[str, Any] = GPTaConfig() else: a__ : Dict = GPTaConfig.from_json_file(lowerCAmelCase__ ) a__ : Optional[int] = GPTaModel(lowerCAmelCase__ ) # Load weights from numpy load_tf_weights_in_gpta(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model a__ : int = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME a__ : Union[str, Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , lowerCAmelCase__ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--gpt2_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
688
1
'''simple docstring''' from math import pi def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): return 2 * pi * radius * (angle / 360) if __name__ == "__main__": print(arc_length(9_0, 1_0))
688
'''simple docstring''' import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } __SCREAMING_SNAKE_CASE = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } __SCREAMING_SNAKE_CASE = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: __SCREAMING_SNAKE_CASE = reader.read() __SCREAMING_SNAKE_CASE = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): __SCREAMING_SNAKE_CASE = UNetaDModel(**config) else: __SCREAMING_SNAKE_CASE = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel __SCREAMING_SNAKE_CASE = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) __SCREAMING_SNAKE_CASE = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: __SCREAMING_SNAKE_CASE = config[key] del config[key] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['down_block_types']] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: __SCREAMING_SNAKE_CASE = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) __SCREAMING_SNAKE_CASE = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue __SCREAMING_SNAKE_CASE = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: __SCREAMING_SNAKE_CASE = param_value __SCREAMING_SNAKE_CASE = True if not has_changed: __SCREAMING_SNAKE_CASE = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
688
1
'''simple docstring''' class lowerCAmelCase__ : """simple docstring""" def __init__( self : str ) -> List[Any]: '''simple docstring''' a__ : List[str] = '''''' a__ : Union[str, Any] = '''''' a__ : Dict = [] def __lowerCAmelCase ( self : str , A__ : int , A__ : int ) -> int: '''simple docstring''' if m == -1: return n + 1 elif n == -1: return m + 1 elif self.dp[m][n] > -1: return self.dp[m][n] else: if self.worda[m] == self.worda[n]: a__ : Optional[int] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) else: a__ : List[Any] = self.__min_dist_top_down_dp(A__ , n - 1 ) a__ : Optional[Any] = self.__min_dist_top_down_dp(m - 1 , A__ ) a__ : Union[str, Any] = self.__min_dist_top_down_dp(m - 1 , n - 1 ) a__ : Any = 1 + min(A__ , A__ , A__ ) return self.dp[m][n] def __lowerCAmelCase ( self : List[str] , A__ : str , A__ : str ) -> int: '''simple docstring''' a__ : Any = worda a__ : Tuple = worda a__ : Optional[int] = [[-1 for _ in range(len(A__ ) )] for _ in range(len(A__ ) )] return self.__min_dist_top_down_dp(len(A__ ) - 1 , len(A__ ) - 1 ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : str , A__ : str ) -> int: '''simple docstring''' a__ : Tuple = worda a__ : int = worda a__ : Optional[Any] = len(A__ ) a__ : List[Any] = len(A__ ) a__ : Union[str, Any] = [[0 for _ in range(n + 1 )] for _ in range(m + 1 )] for i in range(m + 1 ): for j in range(n + 1 ): if i == 0: # first string is empty a__ : Any = j elif j == 0: # second string is empty a__ : int = i elif worda[i - 1] == worda[j - 1]: # last characters are equal a__ : Optional[Any] = self.dp[i - 1][j - 1] else: a__ : int = self.dp[i][j - 1] a__ : Optional[int] = self.dp[i - 1][j] a__ : List[Any] = self.dp[i - 1][j - 1] a__ : Any = 1 + min(A__ , A__ , A__ ) return self.dp[m][n] if __name__ == "__main__": __SCREAMING_SNAKE_CASE = EditDistance() print('****************** Testing Edit Distance DP Algorithm ******************') print() __SCREAMING_SNAKE_CASE = input('Enter the first string: ').strip() __SCREAMING_SNAKE_CASE = input('Enter the second string: ').strip() print() print(f'The minimum edit distance is: {solver.min_dist_top_down(Sa, Sa)}') print(f'The minimum edit distance is: {solver.min_dist_bottom_up(Sa, Sa)}') print() print('*************** End of Testing Edit Distance DP Algorithm ***************')
688
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = (KDPMaDiscreteScheduler,) __UpperCamelCase = 10 def __lowerCAmelCase ( self : Optional[Any] , **A__ : Optional[int] ) -> int: '''simple docstring''' a__ : Optional[int] = { '''num_train_timesteps''': 1_1_0_0, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**A__ ) return config def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=A__ ) def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=A__ , beta_end=A__ ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A__ ) def __lowerCAmelCase ( self : str ) -> Optional[int]: '''simple docstring''' a__ : Any = self.scheduler_classes[0] a__ : str = self.get_scheduler_config(prediction_type='''v_prediction''' ) a__ : Dict = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : Tuple = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Dict = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : Optional[Any] = scheduler.scale_model_input(A__ , A__ ) a__ : Union[str, Any] = model(A__ , A__ ) a__ : List[str] = scheduler.step(A__ , A__ , A__ ) a__ : Optional[Any] = output.prev_sample a__ : Tuple = torch.sum(torch.abs(A__ ) ) a__ : Optional[int] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_4286_5017_0972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' if torch_device == "mps": return a__ : List[Any] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : Tuple = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : List[Any] = self.dummy_model() a__ : Any = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Any = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : str = scheduler.scale_model_input(A__ , A__ ) a__ : List[str] = model(A__ , A__ ) a__ : str = scheduler.step(A__ , A__ , A__ ) a__ : List[Any] = output.prev_sample a__ : Dict = torch.sum(torch.abs(A__ ) ) a__ : Optional[Any] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' if torch_device == "mps": return a__ : Optional[int] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : List[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps , device=A__ ) a__ : Union[str, Any] = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter.to(A__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: a__ : Optional[int] = scheduler.scale_model_input(A__ , A__ ) a__ : List[Any] = model(A__ , A__ ) a__ : Any = scheduler.step(A__ , A__ , A__ ) a__ : List[str] = output.prev_sample a__ : Any = torch.sum(torch.abs(A__ ) ) a__ : Union[str, Any] = torch.mean(torch.abs(A__ ) ) if str(A__ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
688
1
'''simple docstring''' import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Union[str, Any] , A__ : Any , A__ : Any , A__ : List[Any] ) -> Dict: '''simple docstring''' a__ : List[Any] = dataset a__ : Tuple = process a__ : Optional[Any] = params def __len__( self : List[Any] ) -> List[Any]: '''simple docstring''' return len(self.dataset ) def __getitem__( self : Tuple , A__ : List[str] ) -> Optional[int]: '''simple docstring''' a__ : Any = self.dataset[i] a__ : Optional[Any] = self.process(A__ , **self.params ) return processed class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Tuple , A__ : Union[str, Any] , A__ : Any , A__ : str , A__ : Tuple=None ) -> Union[str, Any]: '''simple docstring''' a__ : Any = loader a__ : str = infer a__ : Dict = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether a__ : Optional[Any] = None a__ : List[Any] = loader_batch_size # Internal bookkeeping a__ : Tuple = None a__ : Optional[int] = None def __len__( self : List[Any] ) -> Any: '''simple docstring''' return len(self.loader ) def __iter__( self : List[str] ) -> Tuple: '''simple docstring''' a__ : Tuple = iter(self.loader ) return self def __lowerCAmelCase ( self : List[str] ) -> Tuple: '''simple docstring''' if isinstance(self._loader_batch_data , torch.Tensor ): # Batch data is simple tensor, just fetch the slice a__ : Tuple = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) a__ : Tuple = {} for k, element in self._loader_batch_data.items(): if isinstance(A__ , A__ ): # Convert ModelOutput to tuple first a__ : Optional[int] = element.to_tuple() if isinstance(element[0] , torch.Tensor ): a__ : Optional[int] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): a__ : str = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(A__ , A__ ): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0] , torch.Tensor ): a__ : Optional[int] = tuple(el[self._loader_batch_index].unsqueeze(0 ) for el in element ) elif isinstance(element[0] , np.ndarray ): a__ : Optional[int] = tuple(np.expand_dims(el[self._loader_batch_index] , 0 ) for el in element ) continue if element is None: # This can happen for optional data that get passed around a__ : Optional[int] = None elif isinstance(element[self._loader_batch_index] , torch.Tensor ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers a__ : Dict = element[self._loader_batch_index].unsqueeze(0 ) elif isinstance(element[self._loader_batch_index] , np.ndarray ): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers a__ : Dict = np.expand_dims(element[self._loader_batch_index] , 0 ) else: # This is typically a list, so no need to `unsqueeze`. a__ : List[str] = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 a__ : Dict = self._loader_batch_data.__class__(A__ ) self._loader_batch_index += 1 return result def __lowerCAmelCase ( self : List[Any] ) -> int: '''simple docstring''' if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch a__ : int = next(self.iterator ) a__ : int = self.infer(A__ , **self.params ) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(A__ , torch.Tensor ): a__ : Any = processed else: a__ : List[str] = list(processed.keys() )[0] a__ : Dict = processed[key] if isinstance(A__ , A__ ): a__ : Tuple = len(A__ ) else: a__ : Optional[Any] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. a__ : List[str] = observed_batch_size # Setting internal index to unwrap the batch a__ : List[str] = processed a__ : Tuple = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : List[Any] , A__ : Optional[int] , A__ : Tuple , A__ : Optional[int] , A__ : Optional[Any]=None ) -> Optional[Any]: '''simple docstring''' super().__init__(A__ , A__ , A__ ) def __iter__( self : Optional[Any] ) -> str: '''simple docstring''' a__ : Union[str, Any] = iter(self.loader ) a__ : Dict = None return self def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' if self.subiterator is None: a__ : Dict = self.infer(next(self.iterator ) , **self.params ) try: # Try to return next item a__ : Tuple = next(self.subiterator ) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators a__ : Tuple = self.infer(next(self.iterator ) , **self.params ) a__ : Optional[Any] = next(self.subiterator ) return processed class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __iter__( self : str ) -> Optional[int]: '''simple docstring''' a__ : Dict = iter(self.loader ) return self def __lowerCAmelCase ( self : str ) -> Tuple: '''simple docstring''' a__ : Dict = False a__ : List[str] = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: a__ : List[str] = self.loader_batch_item() a__ : List[str] = item.pop('''is_last''' ) accumulator.append(A__ ) if is_last: return accumulator while not is_last: a__ : Optional[int] = self.infer(next(self.iterator ) , **self.params ) if self.loader_batch_size is not None: if isinstance(A__ , torch.Tensor ): a__ : int = processed else: a__ : int = list(processed.keys() )[0] a__ : List[str] = processed[key] if isinstance(A__ , A__ ): a__ : List[Any] = len(A__ ) else: a__ : Union[str, Any] = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. a__ : str = observed_batch_size a__ : int = processed a__ : Union[str, Any] = 0 while self._loader_batch_index < self.loader_batch_size: a__ : Dict = self.loader_batch_item() a__ : Any = item.pop('''is_last''' ) accumulator.append(A__ ) if is_last: return accumulator else: a__ : Tuple = processed a__ : List[str] = item.pop('''is_last''' ) accumulator.append(A__ ) return accumulator class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : int , A__ : Dataset , A__ : str ) -> int: '''simple docstring''' a__ : Any = dataset a__ : List[Any] = key def __len__( self : str ) -> int: '''simple docstring''' return len(self.dataset ) def __getitem__( self : int , A__ : List[str] ) -> str: '''simple docstring''' return self.dataset[i][self.key] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : List[Any] , A__ : Dataset , A__ : str , A__ : str ) -> List[str]: '''simple docstring''' a__ : Any = dataset a__ : Optional[Any] = keya a__ : Any = keya def __len__( self : Optional[int] ) -> List[Any]: '''simple docstring''' return len(self.dataset ) def __getitem__( self : Tuple , A__ : Union[str, Any] ) -> str: '''simple docstring''' return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
688
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None a__ , a__ : List[Any] = get_aligned_output_features_output_indices(A__ , A__ , A__ ) self.assertEqual(A__ , ['''c'''] ) self.assertEqual(A__ , [2] ) # Out indices set to match out features a__ , a__ : Optional[int] = get_aligned_output_features_output_indices(['''a''', '''c'''] , A__ , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features set to match out indices a__ , a__ : int = get_aligned_output_features_output_indices(A__ , [0, 2] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features selected from negative indices a__ , a__ : List[str] = get_aligned_output_features_output_indices(A__ , [-3, -1] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [-3, -1] ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , A__ ) # Out features must be a list with self.assertRaises(A__ ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(A__ ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : Optional[Any] = BackboneMixin() a__ : int = ['''a''', '''b''', '''c'''] a__ : List[Any] = ['''a''', '''c'''] a__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly a__ : Dict = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) a__ : int = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
688
1
'''simple docstring''' import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING __SCREAMING_SNAKE_CASE = { 'facebook/mask2former-swin-small-coco-instance': ( 'https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "mask2former" __UpperCamelCase = ["swin"] __UpperCamelCase = {"hidden_size": "hidden_dim"} def __init__( self : Tuple , A__ : Optional[Dict] = None , A__ : int = 2_5_6 , A__ : int = 2_5_6 , A__ : int = 2_5_6 , A__ : int = 1_0_2_4 , A__ : str = "relu" , A__ : int = 6 , A__ : int = 1_0 , A__ : int = 8 , A__ : float = 0.0 , A__ : int = 2_0_4_8 , A__ : bool = False , A__ : bool = False , A__ : int = 4 , A__ : int = 2_5_5 , A__ : int = 1_0_0 , A__ : float = 0.1 , A__ : float = 2.0 , A__ : float = 5.0 , A__ : float = 5.0 , A__ : int = 1_2_5_4_4 , A__ : float = 3.0 , A__ : float = 0.75 , A__ : float = 0.02 , A__ : float = 1.0 , A__ : bool = True , A__ : List[int] = [4, 8, 1_6, 3_2] , A__ : bool = None , **A__ : Any , ) -> str: '''simple docstring''' if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.''' ) a__ : Union[str, Any] = CONFIG_MAPPING['''swin''']( image_size=2_2_4 , in_channels=3 , patch_size=4 , embed_dim=9_6 , depths=[2, 2, 1_8, 2] , num_heads=[3, 6, 1_2, 2_4] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=A__ , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(A__ , A__ ): a__ : Tuple = backbone_config.pop('''model_type''' ) a__ : Optional[Any] = CONFIG_MAPPING[backbone_model_type] a__ : int = config_class.from_dict(A__ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. ' F'Supported model types: {",".join(self.backbones_supported )}' ) a__ : List[Any] = backbone_config a__ : Union[str, Any] = feature_size a__ : List[Any] = mask_feature_size a__ : Dict = hidden_dim a__ : int = encoder_feedforward_dim a__ : Dict = activation_function a__ : Any = encoder_layers a__ : List[str] = decoder_layers a__ : List[str] = num_attention_heads a__ : Tuple = dropout a__ : Union[str, Any] = dim_feedforward a__ : Any = pre_norm a__ : Union[str, Any] = enforce_input_projection a__ : List[Any] = common_stride a__ : Dict = ignore_value a__ : List[Any] = num_queries a__ : List[str] = no_object_weight a__ : Tuple = class_weight a__ : Any = mask_weight a__ : Tuple = dice_weight a__ : Any = train_num_points a__ : Optional[Any] = oversample_ratio a__ : Tuple = importance_sample_ratio a__ : Optional[Any] = init_std a__ : List[str] = init_xavier_std a__ : int = use_auxiliary_loss a__ : Tuple = feature_strides a__ : List[Any] = output_auxiliary_logits a__ : Optional[int] = decoder_layers super().__init__(**A__ ) @classmethod def __lowerCAmelCase ( cls : Dict , A__ : PretrainedConfig , **A__ : str ) -> List[Any]: '''simple docstring''' return cls( backbone_config=A__ , **A__ , ) def __lowerCAmelCase ( self : List[Any] ) -> Dict[str, any]: '''simple docstring''' a__ : Any = copy.deepcopy(self.__dict__ ) a__ : int = self.backbone_config.to_dict() a__ : str = self.__class__.model_type return output
688
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __a ( lowerCAmelCase__ : List[Any] ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ): a__ : Dict = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue a__ : Any = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) a__ : int = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) a__ : Optional[Any] = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) a__ : Dict = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) a__ : List[str] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) a__ : List[Any] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) a__ : str = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) a__ : List[Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) a__ : List[Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) a__ : str = key.replace('''image_encoder.module''' , '''flava.image_model''' ) a__ : Dict = key.replace('''text_encoder.module''' , '''flava.text_model''' ) a__ : List[Any] = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) a__ : List[str] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) a__ : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' ) a__ : Any = key.replace('''image_projection''' , '''flava.image_projection''' ) a__ : Any = value.float() for key, value in codebook_state_dict.items(): a__ : List[str] = value return upgrade @torch.no_grad() def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict=None ): if config_path is not None: a__ : Tuple = FlavaConfig.from_pretrained(lowerCAmelCase__ ) else: a__ : Optional[int] = FlavaConfig() a__ : List[Any] = FlavaForPreTraining(lowerCAmelCase__ ).eval() a__ : Optional[int] = convert_dalle_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , save_checkpoint=lowerCAmelCase__ ) if os.path.exists(lowerCAmelCase__ ): a__ : List[str] = torch.load(lowerCAmelCase__ , map_location='''cpu''' ) else: a__ : Dict = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' ) a__ : List[Any] = upgrade_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) a__ : Any = hf_model.state_dict() a__ : Optional[Any] = count_parameters(lowerCAmelCase__ ) a__ : int = count_parameters(lowerCAmelCase__ ) + count_parameters(lowerCAmelCase__ ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
688
1
'''simple docstring''' def __a ( lowerCAmelCase__ : int = 1000000 ): a__ : Tuple = [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 , lowerCAmelCase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
688
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass def __a ( lowerCAmelCase__ : List[str] ): for shard in shards: for i in range(lowerCAmelCase__ ): yield {"i": i, "shard": shard} def __a ( ): a__ : str = int(os.environ['''RANK'''] ) a__ : int = int(os.environ['''WORLD_SIZE'''] ) a__ : str = ArgumentParser() parser.add_argument('''--streaming''' , type=lowerCAmelCase__ ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase__ ) parser.add_argument('''--num_workers''' , type=lowerCAmelCase__ , default=0 ) a__ : int = parser.parse_args() a__ : List[str] = args.streaming a__ : Dict = args.num_workers a__ : Dict = {'''shards''': [F'shard_{shard_idx}' for shard_idx in range(lowerCAmelCase__ )]} a__ : Tuple = IterableDataset.from_generator(lowerCAmelCase__ , gen_kwargs=lowerCAmelCase__ ) if not streaming: a__ : str = Dataset.from_list(list(lowerCAmelCase__ ) ) a__ : Optional[int] = split_dataset_by_node(lowerCAmelCase__ , rank=lowerCAmelCase__ , world_size=lowerCAmelCase__ ) a__ : Dict = torch.utils.data.DataLoader(lowerCAmelCase__ , num_workers=lowerCAmelCase__ ) a__ : str = NUM_SHARDS * NUM_ITEMS_PER_SHARD a__ : Dict = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) a__ : str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'local_size {local_size} != expected_local_size {expected_local_size}' ) if __name__ == "__main__": main()
688
1
'''simple docstring''' import unittest from transformers import DebertaVaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaVaForMaskedLM, DebertaVaForMultipleChoice, DebertaVaForQuestionAnswering, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaModel, ) from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Union[str, Any] , A__ : str , A__ : Optional[int]=1_3 , A__ : Any=7 , A__ : Optional[int]=True , A__ : List[Any]=True , A__ : Optional[int]=True , A__ : Optional[Any]=True , A__ : Optional[Any]=9_9 , A__ : Optional[Any]=3_2 , A__ : Optional[Any]=5 , A__ : Optional[Any]=4 , A__ : Optional[int]=3_7 , A__ : List[str]="gelu" , A__ : int=0.1 , A__ : str=0.1 , A__ : Optional[int]=5_1_2 , A__ : str=1_6 , A__ : List[str]=2 , A__ : str=0.02 , A__ : Any=False , A__ : Optional[Any]=True , A__ : List[str]="None" , A__ : Optional[int]=3 , A__ : Tuple=4 , A__ : Dict=None , ) -> Union[str, Any]: '''simple docstring''' a__ : Optional[int] = parent a__ : Any = batch_size a__ : Optional[int] = seq_length a__ : List[Any] = is_training a__ : Dict = use_input_mask a__ : Optional[Any] = use_token_type_ids a__ : Any = use_labels a__ : int = vocab_size a__ : Optional[int] = hidden_size a__ : List[Any] = num_hidden_layers a__ : Tuple = num_attention_heads a__ : Tuple = intermediate_size a__ : Union[str, Any] = hidden_act a__ : Union[str, Any] = hidden_dropout_prob a__ : List[Any] = attention_probs_dropout_prob a__ : List[str] = max_position_embeddings a__ : Any = type_vocab_size a__ : Dict = type_sequence_label_size a__ : int = initializer_range a__ : Union[str, Any] = num_labels a__ : Dict = num_choices a__ : str = relative_attention a__ : Optional[Any] = position_biased_input a__ : Union[str, Any] = pos_att_type a__ : Optional[int] = scope def __lowerCAmelCase ( self : Optional[int] ) -> Any: '''simple docstring''' a__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Optional[Any] = None if self.use_input_mask: a__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) a__ : Union[str, Any] = None if self.use_token_type_ids: a__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a__ : Any = None a__ : List[Any] = None a__ : Any = None if self.use_labels: a__ : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a__ : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) a__ : Any = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[Any]: '''simple docstring''' return DebertaVaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , ) def __lowerCAmelCase ( self : Dict , A__ : Optional[Any] ) -> List[str]: '''simple docstring''' self.parent.assertListEqual(list(result.loss.size() ) , [] ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , A__ : List[str] , A__ : Dict , A__ : List[Any] , A__ : Tuple , A__ : Any , A__ : Optional[Any] ) -> Dict: '''simple docstring''' a__ : Optional[Any] = DebertaVaModel(config=A__ ) model.to(A__ ) model.eval() a__ : Optional[Any] = model(A__ , attention_mask=A__ , token_type_ids=A__ )[0] a__ : str = model(A__ , token_type_ids=A__ )[0] a__ : Dict = model(A__ )[0] self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] ) def __lowerCAmelCase ( self : Any , A__ : Tuple , A__ : str , A__ : Union[str, Any] , A__ : str , A__ : int , A__ : int , A__ : Dict ) -> Dict: '''simple docstring''' a__ : Any = DebertaVaForMaskedLM(config=A__ ) model.to(A__ ) model.eval() a__ : List[Any] = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : Dict , A__ : List[Any] , A__ : Tuple , A__ : Union[str, Any] , A__ : List[str] , A__ : Optional[int] , A__ : Dict , A__ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : List[str] = self.num_labels a__ : List[Any] = DebertaVaForSequenceClassification(A__ ) model.to(A__ ) model.eval() a__ : List[Any] = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] ) self.check_loss_output(A__ ) def __lowerCAmelCase ( self : List[Any] , A__ : Optional[int] , A__ : List[str] , A__ : str , A__ : Dict , A__ : Dict , A__ : int , A__ : Dict ) -> Tuple: '''simple docstring''' a__ : Dict = self.num_labels a__ : Any = DebertaVaForTokenClassification(config=A__ ) model.to(A__ ) model.eval() a__ : Any = model(A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self : Tuple , A__ : Any , A__ : str , A__ : Optional[Any] , A__ : str , A__ : str , A__ : Any , A__ : str ) -> Union[str, Any]: '''simple docstring''' a__ : List[str] = DebertaVaForQuestionAnswering(config=A__ ) model.to(A__ ) model.eval() a__ : Dict = model( A__ , attention_mask=A__ , token_type_ids=A__ , start_positions=A__ , end_positions=A__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCAmelCase ( self : Optional[int] , A__ : Any , A__ : Optional[Any] , A__ : Any , A__ : List[str] , A__ : Any , A__ : int , A__ : str ) -> List[str]: '''simple docstring''' a__ : Union[str, Any] = DebertaVaForMultipleChoice(config=A__ ) model.to(A__ ) model.eval() a__ : Any = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : Union[str, Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : List[str] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : Tuple = model( A__ , attention_mask=A__ , token_type_ids=A__ , labels=A__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self : Optional[int] ) -> List[Any]: '''simple docstring''' a__ : Tuple = self.prepare_config_and_inputs() ( ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ) : Tuple = config_and_inputs a__ : Tuple = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = ( ( DebertaVaModel, DebertaVaForMaskedLM, DebertaVaForSequenceClassification, DebertaVaForTokenClassification, DebertaVaForQuestionAnswering, DebertaVaForMultipleChoice, ) if is_torch_available() else () ) __UpperCamelCase = ( { "feature-extraction": DebertaVaModel, "fill-mask": DebertaVaForMaskedLM, "question-answering": DebertaVaForQuestionAnswering, "text-classification": DebertaVaForSequenceClassification, "token-classification": DebertaVaForTokenClassification, "zero-shot": DebertaVaForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' a__ : Any = DebertaVaModelTester(self ) a__ : Optional[Any] = ConfigTester(self , config_class=A__ , hidden_size=3_7 ) def __lowerCAmelCase ( self : List[Any] ) -> Optional[int]: '''simple docstring''' self.config_tester.run_common_tests() def __lowerCAmelCase ( self : Dict ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*A__ ) def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*A__ ) def __lowerCAmelCase ( self : Union[str, Any] ) -> str: '''simple docstring''' a__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*A__ ) def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' a__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*A__ ) def __lowerCAmelCase ( self : Optional[int] ) -> Any: '''simple docstring''' a__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*A__ ) def __lowerCAmelCase ( self : List[str] ) -> str: '''simple docstring''' a__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_multiple_choice(*A__ ) @slow def __lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: '''simple docstring''' for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Any = DebertaVaModel.from_pretrained(A__ ) self.assertIsNotNone(A__ ) @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @unittest.skip(reason='''Model not available yet''' ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' pass @slow def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : List[str] = DebertaVaModel.from_pretrained('''microsoft/deberta-v2-xlarge''' ) a__ : Optional[int] = torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]] ) a__ : List[Any] = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): a__ : int = model(A__ , attention_mask=A__ )[0] # compare the actual values for a slice. a__ : str = torch.tensor( [[[0.2_356, 0.1_948, 0.0_369], [-0.1_063, 0.3_586, -0.5_152], [-0.6_399, -0.0_259, -0.2_525]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , A__ , atol=1E-4 ) , F'{output[:, 1:4, 1:4]}' )
688
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __SCREAMING_SNAKE_CASE = open # noqa: we just need to have a builtin inside this module to test it properly
688
1
'''simple docstring''' from __future__ import annotations import requests __SCREAMING_SNAKE_CASE = set( 'approved_at_utc approved_by author_flair_background_color\nauthor_flair_css_class author_flair_richtext author_flair_template_id author_fullname\nauthor_premium can_mod_post category clicked content_categories created_utc downs\nedited gilded gildings hidden hide_score is_created_from_ads_ui is_meta\nis_original_content is_reddit_media_domain is_video link_flair_css_class\nlink_flair_richtext link_flair_text link_flair_text_color media_embed mod_reason_title\nname permalink pwls quarantine saved score secure_media secure_media_embed selftext\nsubreddit subreddit_name_prefixed subreddit_type thumbnail title top_awarded_type\ntotal_awards_received ups upvote_ratio url user_reports'.split() ) def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : int = 1 , lowerCAmelCase__ : str = "new" , lowerCAmelCase__ : list | None = None ): a__ : Union[str, Any] = wanted_data or [] if invalid_search_terms := ", ".join(sorted(set(lowerCAmelCase__ ) - valid_terms ) ): a__ : Union[str, Any] = F'Invalid search term: {invalid_search_terms}' raise ValueError(lowerCAmelCase__ ) a__ : List[Any] = requests.get( F'https://reddit.com/r/{subreddit}/{age}.json?limit={limit}' , headers={'''User-agent''': '''A random string'''} , ) if response.status_code == 429: raise requests.HTTPError a__ : List[Any] = response.json() if not wanted_data: return {id_: data["data"]["children"][id_] for id_ in range(lowerCAmelCase__ )} a__ : Any = {} for id_ in range(lowerCAmelCase__ ): a__ : str = { item: data['''data''']['''children'''][id_]['''data'''][item] for item in wanted_data } return data_dict if __name__ == "__main__": # If you get Error 429, that means you are rate limited.Try after some time print(get_subreddit_data('learnpython', wanted_data=['title', 'url', 'selftext']))
688
'''simple docstring''' import enum import shutil import sys __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = shutil.get_terminal_size() __SCREAMING_SNAKE_CASE = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase__ ( enum.Enum ): """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 1 def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict="" ): sys.stdout.write(str(lowerCAmelCase__ ) + end ) sys.stdout.flush() def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : int="" ): forceWrite(F'\u001b[{color}m{content}\u001b[0m' , lowerCAmelCase__ ) def __a ( ): forceWrite('''\r''' ) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : str ): forceWrite(F'\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}' ) def __a ( ): forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def __a ( ): reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
688
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __SCREAMING_SNAKE_CASE = { 'configuration_blenderbot': [ 'BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlenderbotConfig', 'BlenderbotOnnxConfig', ], 'tokenization_blenderbot': ['BlenderbotTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = ['BlenderbotTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlenderbotForCausalLM', 'BlenderbotForConditionalGeneration', 'BlenderbotModel', 'BlenderbotPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'TFBlenderbotForConditionalGeneration', 'TFBlenderbotModel', 'TFBlenderbotPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'FlaxBlenderbotForConditionalGeneration', 'FlaxBlenderbotModel', 'FlaxBlenderbotPreTrainedModel', ] if TYPE_CHECKING: from .configuration_blenderbot import ( BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotConfig, BlenderbotOnnxConfig, ) from .tokenization_blenderbot import BlenderbotTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_fast import BlenderbotTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot import ( BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotForCausalLM, BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot import ( TFBlenderbotForConditionalGeneration, TFBlenderbotModel, TFBlenderbotPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, FlaxBlenderbotPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
688
'''simple docstring''' import inspect import unittest class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' try: import diffusers # noqa: F401 except ImportError: assert False def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' import diffusers from diffusers.dependency_versions_table import deps a__ : Optional[int] = inspect.getmembers(A__ , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": a__ : int = '''k-diffusion''' elif backend == "invisible_watermark": a__ : int = '''invisible-watermark''' assert backend in deps, F'{backend} is not in the deps table!'
688
1
'''simple docstring''' import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = BlenderbotSmallTokenizer __UpperCamelCase = False def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' super().setUp() a__ : Union[str, Any] = ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__'''] a__ : Tuple = dict(zip(A__ , range(len(A__ ) ) ) ) a__ : Tuple = ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', ''''''] a__ : Any = {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''} a__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) a__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(A__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(A__ ) ) def __lowerCAmelCase ( self : Optional[int] , **A__ : int ) -> Dict: '''simple docstring''' kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Optional[Any] ) -> Dict: '''simple docstring''' a__ : Any = '''adapt act apte''' a__ : int = '''adapt act apte''' return input_text, output_text def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) a__ : Union[str, Any] = '''adapt act apte''' a__ : Dict = ['''adapt''', '''act''', '''ap@@''', '''te'''] a__ : Any = tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] a__ : int = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , A__ ) def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : str = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) assert tok('''sam''' ).input_ids == [1_3_8_4] a__ : List[str] = '''I am a small frog.''' a__ : Optional[Any] = tok([src_text] , padding=A__ , truncation=A__ )['''input_ids'''] a__ : Dict = tok.batch_decode(A__ , skip_special_tokens=A__ , clean_up_tokenization_spaces=A__ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def __lowerCAmelCase ( self : List[Any] ) -> int: '''simple docstring''' a__ : Optional[int] = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) a__ : Tuple = '''I am a small frog .''' a__ : Union[str, Any] = '''.''' a__ : List[Any] = tok(A__ )['''input_ids'''] a__ : Optional[int] = tok(A__ )['''input_ids'''] assert encoded[-1] == encoded_dot[0]
688
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __a ( lowerCAmelCase__ : Dict ): a__ , a__ : int = image.size a__ , a__ : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 a__ : Tuple = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) a__ : List[Any] = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 255.0 a__ : Any = image[None].transpose(0 , 3 , 1 , 2 ) a__ : Dict = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , A__ : VQModel , A__ : UNetaDModel , A__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> str: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : List[str] , A__ : Union[torch.Tensor, PIL.Image.Image] = None , A__ : Optional[int] = 1 , A__ : Optional[int] = 1_0_0 , A__ : Optional[float] = 0.0 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' if isinstance(A__ , PIL.Image.Image ): a__ : List[Any] = 1 elif isinstance(A__ , torch.Tensor ): a__ : List[str] = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(A__ )}' ) if isinstance(A__ , PIL.Image.Image ): a__ : Union[str, Any] = preprocess(A__ ) a__ , a__ : Dict = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image a__ : Optional[int] = (batch_size, self.unet.config.in_channels // 2, height, width) a__ : Optional[int] = next(self.unet.parameters() ).dtype a__ : List[str] = randn_tensor(A__ , generator=A__ , device=self.device , dtype=A__ ) a__ : Any = image.to(device=self.device , dtype=A__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(A__ , device=self.device ) a__ : int = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler a__ : str = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a__ : Union[str, Any] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a__ : str = {} if accepts_eta: a__ : Dict = eta for t in self.progress_bar(A__ ): # concat latents and low resolution image in the channel dimension. a__ : str = torch.cat([latents, image] , dim=1 ) a__ : Optional[Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual a__ : Union[str, Any] = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VQVAE a__ : List[Any] = self.vqvae.decode(A__ ).sample a__ : List[Any] = torch.clamp(A__ , -1.0 , 1.0 ) a__ : Optional[Any] = image / 2 + 0.5 a__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a__ : Union[str, Any] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : int ): return int((input_a, input_a).count(1 ) != 0 ) def __a ( ): assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
688
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # pylint: disable=invalid-name __SCREAMING_SNAKE_CASE = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : str=8 ): a__ : Tuple = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a__ : Union[str, Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Dict , A__ : UNetaDConditionModel , A__ : DDPMScheduler , A__ : VQModel , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules( unet=A__ , scheduler=A__ , movq=A__ , ) a__ : Union[str, Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] , A__ : List[str] , A__ : Optional[Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if latents is None: a__ : List[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__ : int = latents.to(A__ ) a__ : Tuple = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : Union[str, Any] , A__ : int=0 ) -> str: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a__ : Union[str, Any] = torch.device(F'cuda:{gpu_id}' ) a__ : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A__ , A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple=0 ) -> Dict: '''simple docstring''' if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) a__ : int = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=A__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a__ : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: a__ , a__ : List[str] = cpu_offload_with_hook(A__ , A__ , prev_module_hook=A__ ) # We'll offload the last model manually. a__ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.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 @torch.no_grad() @replace_example_docstring(A__ ) def __call__( self : Any , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : torch.FloatTensor , A__ : int = 5_1_2 , A__ : int = 5_1_2 , A__ : int = 1_0_0 , A__ : float = 4.0 , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> str: '''simple docstring''' a__ : Optional[Any] = self._execution_device a__ : List[str] = guidance_scale > 1.0 if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : Optional[int] = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) a__ : Union[str, Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a__ : Tuple = image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = negative_image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = hint.repeat_interleave(A__ , dim=0 ) a__ : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) a__ : Tuple = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) self.scheduler.set_timesteps(A__ , device=A__ ) a__ : int = self.scheduler.timesteps a__ : str = self.movq.config.latent_channels a__ , a__ : Optional[int] = downscale_height_and_width(A__ , A__ , self.movq_scale_factor ) # create initial latent a__ : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A__ , A__ , A__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance a__ : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ : List[str] = {'''image_embeds''': image_embeds, '''hint''': hint} a__ : Union[str, Any] = self.unet( sample=A__ , timestep=A__ , encoder_hidden_states=A__ , added_cond_kwargs=A__ , return_dict=A__ , )[0] if do_classifier_free_guidance: a__ , a__ : Dict = noise_pred.split(latents.shape[1] , dim=1 ) a__ , a__ : Dict = noise_pred.chunk(2 ) a__ , a__ : Optional[Any] = variance_pred.chunk(2 ) a__ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a__ , a__ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step( A__ , A__ , A__ , generator=A__ , )[0] # post-processing a__ : Tuple = self.movq.decode(A__ , force_not_quantize=A__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: a__ : Union[str, Any] = image * 0.5 + 0.5 a__ : str = image.clamp(0 , 1 ) a__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ : int = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' import inspect import os import sys import unittest import accelerate from accelerate.test_utils import execute_subprocess_async, require_tpu class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' a__ : Optional[int] = inspect.getfile(accelerate.test_utils ) a__ : List[Any] = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) a__ : Any = os.path.sep.join(inspect.getfile(self.__class__ ).split(os.path.sep )[:-1] ) @require_tpu def __lowerCAmelCase ( self : List[str] ) -> List[Any]: '''simple docstring''' a__ : Dict = F'\n {self.test_dir}/xla_spawn.py\n --num_cores 8\n {self.test_file_path}\n '.split() a__ : Any = [sys.executable] + distributed_args execute_subprocess_async(A__ , env=os.environ.copy() )
688
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } __SCREAMING_SNAKE_CASE = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def __a ( lowerCAmelCase__ : Union[str, Any] ): with open(lowerCAmelCase__ , '''r''' ) as f: a__ : Optional[int] = f.read().splitlines() return [l.strip() for l in lines] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[str] , A__ : int , A__ : Union[str, Any]="<unk>" , A__ : Tuple="<cls>" , A__ : List[Any]="<pad>" , A__ : Optional[int]="<mask>" , A__ : List[Any]="<eos>" , **A__ : Optional[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) a__ : Union[str, Any] = load_vocab_file(A__ ) a__ : int = dict(enumerate(self.all_tokens ) ) a__ : str = {tok: ind for ind, tok in enumerate(self.all_tokens )} a__ : List[Any] = unk_token a__ : Any = cls_token a__ : Any = pad_token a__ : Any = mask_token a__ : Any = eos_token a__ : int = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCAmelCase ( self : Any , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , **A__ : str ) -> List[Any]: '''simple docstring''' return text.split() def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int]=False ) -> Tuple: '''simple docstring''' return len(self._id_to_token ) def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCAmelCase ( self : Any , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : List[Any] , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Tuple = [self.cls_token_id] a__ : Union[str, Any] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCAmelCase ( self : Tuple , A__ : List , A__ : Optional[List] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] a__ : Any = [1] + ([0] * len(A__ )) + [1] if token_ids_a is not None: mask += [0] * len(A__ ) + [1] return mask def __lowerCAmelCase ( self : Any , A__ : Dict , A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = os.path.join(A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(A__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return self.get_vocab_size(with_added_tokens=A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Union[List[str], List[AddedToken]] , A__ : bool = False ) -> int: '''simple docstring''' return super()._add_tokens(A__ , special_tokens=A__ )
688
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 __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spiece.model'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'TsinghuaAI/CPM-Generate': 'https://huggingface.co/TsinghuaAI/CPM-Generate/resolve/main/spiece.model', } } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Union[str, Any] , A__ : Union[str, Any] , A__ : Dict=False , A__ : Any=True , A__ : List[str]=False , A__ : Optional[Any]="<s>" , A__ : Tuple="</s>" , A__ : Dict="<unk>" , A__ : List[Any]="<sep>" , A__ : Tuple="<pad>" , A__ : str="<cls>" , A__ : List[Any]="<mask>" , A__ : Any=["<eop>", "<eod>"] , A__ : Optional[Dict[str, Any]] = None , **A__ : Tuple , ) -> None: '''simple docstring''' a__ : Dict = AddedToken(A__ , lstrip=A__ , rstrip=A__ ) if isinstance(A__ , A__ ) else mask_token a__ : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , bos_token=A__ , eos_token=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , additional_special_tokens=A__ , sp_model_kwargs=self.sp_model_kwargs , **A__ , ) a__ : Optional[Any] = 3 a__ : int = do_lower_case a__ : Any = remove_space a__ : List[Any] = keep_accents a__ : str = vocab_file a__ : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A__ ) 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.''' ) a__ : Optional[Any] = jieba a__ : Union[str, Any] = str.maketrans(''' \n''' , '''\u2582\u2583''' ) @property # Copied from transformers.models.xlnet.tokenization_xlnet.XLNetTokenizer.vocab_size def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' return len(self.sp_model ) def __lowerCAmelCase ( self : Dict ) -> Any: '''simple docstring''' a__ : int = {self.convert_ids_to_tokens(A__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Tuple ) -> List[Any]: '''simple docstring''' a__ : Any = self.__dict__.copy() a__ : Optional[Any] = None return state def __setstate__( self : Tuple , A__ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' a__ : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): a__ : Tuple = {} a__ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCAmelCase ( self : str , A__ : Dict ) -> str: '''simple docstring''' if self.remove_space: a__ : Dict = ''' '''.join(inputs.strip().split() ) else: a__ : Dict = inputs a__ : Optional[Any] = outputs.replace('''``''' , '''"''' ).replace('''\'\'''' , '''"''' ) if not self.keep_accents: a__ : List[str] = unicodedata.normalize('''NFKD''' , A__ ) a__ : Any = ''''''.join([c for c in outputs if not unicodedata.combining(A__ )] ) if self.do_lower_case: a__ : Dict = outputs.lower() return outputs def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> List[str]: '''simple docstring''' a__ : Dict = self.preprocess_text(A__ ) a__ : Optional[Any] = self.sp_model.encode(A__ , out_type=A__ ) a__ : Tuple = [] for piece in pieces: if len(A__ ) > 1 and piece[-1] == str(''',''' ) and piece[-2].isdigit(): a__ : Tuple = self.sp_model.EncodeAsPieces(piece[:-1].replace(A__ , '''''' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: a__ : Union[str, Any] = cur_pieces[1:] else: a__ : int = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(A__ ) else: new_pieces.append(A__ ) return new_pieces def __lowerCAmelCase ( self : int , A__ : Union[str, Any] ) -> str: '''simple docstring''' return self.sp_model.PieceToId(A__ ) def __lowerCAmelCase ( self : Optional[Any] , A__ : Optional[Any] ) -> int: '''simple docstring''' return self.sp_model.IdToPiece(A__ ) def __lowerCAmelCase ( self : int , A__ : List[Any] ) -> Any: '''simple docstring''' a__ : List[str] = ''''''.join(A__ ).replace(A__ , ''' ''' ).strip() return out_string def __lowerCAmelCase ( self : Any , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Union[str, Any] = [self.sep_token_id] a__ : Dict = [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 __lowerCAmelCase ( self : Optional[Any] , A__ : List[int] , A__ : Optional[List[int]] = None , A__ : bool = 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 not None: return ([0] * len(A__ )) + [1] + ([0] * len(A__ )) + [1, 1] return ([0] * len(A__ )) + [1, 1] def __lowerCAmelCase ( self : Optional[int] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : str = [self.sep_token_id] a__ : Optional[int] = [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 __lowerCAmelCase ( self : str , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(A__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return a__ : Optional[int] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , A__ ) elif not os.path.isfile(self.vocab_file ): with open(A__ , '''wb''' ) as fi: a__ : Tuple = self.sp_model.serialized_model_proto() fi.write(A__ ) return (out_vocab_file,) def __lowerCAmelCase ( self : int , *A__ : str , **A__ : List[str] ) -> Optional[int]: '''simple docstring''' a__ : str = super()._decode(*A__ , **A__ ) a__ : Any = text.replace(''' ''' , '''''' ).replace('''\u2582''' , ''' ''' ).replace('''\u2583''' , '''\n''' ) return text
688
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ : """simple docstring""" def __init__( self : str ) -> Dict: '''simple docstring''' a__ : List[str] = False def __lowerCAmelCase ( self : Tuple , A__ : Optional[int] , A__ : Optional[Any] , A__ : List[str] , A__ : Tuple ) -> Optional[int]: '''simple docstring''' if not self.initialized: a__ : Optional[Any] = RagRetriever( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : Union[str, Any] = True def __lowerCAmelCase ( self : Tuple ) -> Tuple: '''simple docstring''' self.retriever.index.init_index() def __lowerCAmelCase ( self : List[Any] , A__ : List[Any] , A__ : Optional[int] ) -> List[Any]: '''simple docstring''' a__ , a__ : Optional[Any] = self.retriever._main_retrieve(A__ , A__ ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : Optional[int] , A__ : List[Any] , A__ : List[Any] , A__ : str , A__ : Any=None ) -> Optional[Any]: '''simple docstring''' if index is not None and index.is_initialized() and len(A__ ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : List[str] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(A__ , A__ , A__ , A__ ) for worker in self.retrieval_workers ] ) def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: '''simple docstring''' logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[int] , A__ : int ) -> Dict: '''simple docstring''' if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. a__ : List[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] a__ , a__ : Tuple = ray.get(random_worker.retrieve.remote(A__ , A__ ) ) else: a__ , a__ : int = self._main_retrieve(A__ , A__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[Any] , A__ : Any=None , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return super(A__ , cls ).get_tokenizers(A__ , A__ , **A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[int] , A__ : Union[str, Any] , A__ : Union[str, Any]=None , **A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Dict = kwargs.pop('''config''' , A__ ) or RagConfig.from_pretrained(A__ , **A__ ) a__ : Dict = RagTokenizer.from_pretrained(A__ , config=A__ ) a__ : str = rag_tokenizer.question_encoder a__ : List[str] = rag_tokenizer.generator if indexed_dataset is not None: a__ : List[Any] = '''custom''' a__ : List[Any] = CustomHFIndex(config.retrieval_vector_size , A__ ) else: a__ : Optional[Any] = cls._build_index(A__ ) return cls( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , retrieval_workers=A__ , index=A__ , )
688
1
'''simple docstring''' import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, ) __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) def __a ( lowerCAmelCase__ : str ): a__ : str = git.Repo(search_parent_directories=lowerCAmelCase__ ) a__ : Union[str, Any] = { '''repo_id''': str(lowerCAmelCase__ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), } with open(os.path.join(lowerCAmelCase__ , '''git_log.json''' ) , '''w''' ) as f: json.dump(lowerCAmelCase__ , lowerCAmelCase__ , indent=4 ) def __a ( lowerCAmelCase__ : List[Any] ): if params.n_gpu <= 0: a__ : List[Any] = 0 a__ : List[str] = -1 a__ : Optional[Any] = True a__ : Optional[Any] = False return assert torch.cuda.is_available() logger.info('''Initializing GPUs''' ) if params.n_gpu > 1: assert params.local_rank != -1 a__ : Optional[Any] = int(os.environ['''WORLD_SIZE'''] ) a__ : str = int(os.environ['''N_GPU_NODE'''] ) a__ : Optional[int] = int(os.environ['''RANK'''] ) # number of nodes / node ID a__ : List[Any] = params.world_size // params.n_gpu_per_node a__ : str = params.global_rank // params.n_gpu_per_node a__ : Union[str, Any] = True assert params.n_nodes == int(os.environ['''N_NODES'''] ) assert params.node_id == int(os.environ['''NODE_RANK'''] ) # local job (single GPU) else: assert params.local_rank == -1 a__ : List[str] = 1 a__ : Tuple = 0 a__ : Optional[int] = 0 a__ : Union[str, Any] = 0 a__ : str = 1 a__ : Any = 1 a__ : str = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode a__ : str = params.node_id == 0 and params.local_rank == 0 a__ : Optional[int] = params.n_nodes > 1 # summary a__ : str = F'--- Global rank: {params.global_rank} - ' logger.info(PREFIX + '''Number of nodes: %i''' % params.n_nodes ) logger.info(PREFIX + '''Node ID : %i''' % params.node_id ) logger.info(PREFIX + '''Local rank : %i''' % params.local_rank ) logger.info(PREFIX + '''World size : %i''' % params.world_size ) logger.info(PREFIX + '''GPUs per node : %i''' % params.n_gpu_per_node ) logger.info(PREFIX + '''Master : %s''' % str(params.is_master ) ) logger.info(PREFIX + '''Multi-node : %s''' % str(params.multi_node ) ) logger.info(PREFIX + '''Multi-GPU : %s''' % str(params.multi_gpu ) ) logger.info(PREFIX + '''Hostname : %s''' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('''Initializing PyTorch distributed''' ) torch.distributed.init_process_group( init_method='''env://''' , backend='''nccl''' , ) def __a ( lowerCAmelCase__ : Union[str, Any] ): np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
688
'''simple docstring''' def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): a__ : List[str] = len(lowerCAmelCase__ ) a__ : int = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): a__ : Dict = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
688
1
'''simple docstring''' import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def __a ( lowerCAmelCase__ : bytes , lowerCAmelCase__ : int ): a__ : Union[str, Any] = F'{sampling_rate}' a__ : Dict = '''1''' a__ : Dict = '''f32le''' a__ : Tuple = [ '''ffmpeg''', '''-i''', '''pipe:0''', '''-ac''', ac, '''-ar''', ar, '''-f''', format_for_conversion, '''-hide_banner''', '''-loglevel''', '''quiet''', '''pipe:1''', ] try: with subprocess.Popen(lowerCAmelCase__ , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: a__ : Optional[Any] = ffmpeg_process.communicate(lowerCAmelCase__ ) except FileNotFoundError as error: raise ValueError('''ffmpeg was not found but is required to load audio files from filename''' ) from error a__ : Optional[int] = output_stream[0] a__ : Union[str, Any] = np.frombuffer(lowerCAmelCase__ , np.floataa ) if audio.shape[0] == 0: raise ValueError('''Malformed soundfile''' ) return audio def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : float , lowerCAmelCase__ : str = "f32le" , ): a__ : Dict = F'{sampling_rate}' a__ : Tuple = '''1''' if format_for_conversion == "s16le": a__ : int = 2 elif format_for_conversion == "f32le": a__ : Optional[Any] = 4 else: raise ValueError(F'Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`' ) a__ : Any = platform.system() if system == "Linux": a__ : List[str] = '''alsa''' a__ : int = '''default''' elif system == "Darwin": a__ : List[str] = '''avfoundation''' a__ : Union[str, Any] = ''':0''' elif system == "Windows": a__ : Any = '''dshow''' a__ : Tuple = '''default''' a__ : Optional[int] = [ '''ffmpeg''', '''-f''', format_, '''-i''', input_, '''-ac''', ac, '''-ar''', ar, '''-f''', format_for_conversion, '''-fflags''', '''nobuffer''', '''-hide_banner''', '''-loglevel''', '''quiet''', '''pipe:1''', ] a__ : str = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample a__ : Tuple = _ffmpeg_stream(lowerCAmelCase__ , lowerCAmelCase__ ) for item in iterator: yield item def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : float , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Optional[Union[Tuple[float, float], float]] = None , lowerCAmelCase__ : str = "f32le" , ): if stream_chunk_s is not None: a__ : Optional[int] = stream_chunk_s else: a__ : List[Any] = chunk_length_s a__ : Optional[Any] = ffmpeg_microphone(lowerCAmelCase__ , lowerCAmelCase__ , format_for_conversion=lowerCAmelCase__ ) if format_for_conversion == "s16le": a__ : Tuple = np.intaa a__ : int = 2 elif format_for_conversion == "f32le": a__ : Union[str, Any] = np.floataa a__ : Tuple = 4 else: raise ValueError(F'Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`' ) if stride_length_s is None: a__ : Dict = chunk_length_s / 6 a__ : Union[str, Any] = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(lowerCAmelCase__ , (int, float) ): a__ : Any = [stride_length_s, stride_length_s] a__ : Optional[int] = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample a__ : Tuple = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample a__ : Any = datetime.datetime.now() a__ : Optional[int] = datetime.timedelta(seconds=lowerCAmelCase__ ) for item in chunk_bytes_iter(lowerCAmelCase__ , lowerCAmelCase__ , stride=(stride_left, stride_right) , stream=lowerCAmelCase__ ): # Put everything back in numpy scale a__ : List[str] = np.frombuffer(item['''raw'''] , dtype=lowerCAmelCase__ ) a__ : Optional[Any] = ( item['''stride'''][0] // size_of_sample, item['''stride'''][1] // size_of_sample, ) a__ : Any = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : Tuple[int, int] , lowerCAmelCase__ : bool = False ): a__ : str = b'''''' a__ , a__ : Union[str, Any] = stride if stride_left + stride_right >= chunk_len: raise ValueError( F'Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}' ) a__ : Tuple = 0 for raw in iterator: acc += raw if stream and len(lowerCAmelCase__ ) < chunk_len: a__ : str = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(lowerCAmelCase__ ) >= chunk_len: # We are flushing the accumulator a__ : List[Any] = (_stride_left, stride_right) a__ : Optional[int] = {'''raw''': acc[:chunk_len], '''stride''': stride} if stream: a__ : Optional[Any] = False yield item a__ : Optional[Any] = stride_left a__ : List[str] = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(lowerCAmelCase__ ) > stride_left: a__ : Union[str, Any] = {'''raw''': acc, '''stride''': (_stride_left, 0)} if stream: a__ : Union[str, Any] = False yield item def __a ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : int ): a__ : List[str] = 2**24 # 16Mo try: with subprocess.Popen(lowerCAmelCase__ , stdout=subprocess.PIPE , bufsize=lowerCAmelCase__ ) as ffmpeg_process: while True: a__ : List[Any] = ffmpeg_process.stdout.read(lowerCAmelCase__ ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('''ffmpeg was not found but is required to stream audio files from filename''' ) from error
688
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "swin2sr" __UpperCamelCase = { "hidden_size": "embed_dim", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] , A__ : int=6_4 , A__ : List[Any]=1 , A__ : List[Any]=3 , A__ : Any=1_8_0 , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Dict=8 , A__ : Any=2.0 , A__ : Optional[int]=True , A__ : Union[str, Any]=0.0 , A__ : Union[str, Any]=0.0 , A__ : List[str]=0.1 , A__ : Any="gelu" , A__ : Tuple=False , A__ : Optional[int]=0.02 , A__ : List[Any]=1E-5 , A__ : Any=2 , A__ : Union[str, Any]=1.0 , A__ : Dict="1conv" , A__ : Optional[Any]="pixelshuffle" , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : List[str] = image_size a__ : Optional[Any] = patch_size a__ : Dict = num_channels a__ : Optional[int] = embed_dim a__ : int = depths a__ : Optional[int] = len(A__ ) a__ : Dict = num_heads a__ : List[Any] = window_size a__ : Optional[int] = mlp_ratio a__ : Optional[int] = qkv_bias a__ : Union[str, Any] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Union[str, Any] = drop_path_rate a__ : int = hidden_act a__ : int = use_absolute_embeddings a__ : Dict = layer_norm_eps a__ : List[str] = initializer_range a__ : List[Any] = upscale a__ : List[Any] = img_range a__ : Optional[int] = resi_connection a__ : int = upsampler
688
1
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __SCREAMING_SNAKE_CASE = 1_6 __SCREAMING_SNAKE_CASE = 3_2 def __a ( lowerCAmelCase__ : Accelerator , lowerCAmelCase__ : int = 16 , lowerCAmelCase__ : str = "bert-base-cased" ): a__ : Union[str, Any] = AutoTokenizer.from_pretrained(lowerCAmelCase__ ) a__ : Any = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(lowerCAmelCase__ : Tuple ): # max_length=None => use the model max length (it's actually the default) a__ : Dict = 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 a__ : Dict = datasets.map( lowerCAmelCase__ , batched=lowerCAmelCase__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=lowerCAmelCase__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library a__ : Optional[int] = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(lowerCAmelCase__ : Any ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowerCAmelCase__ , padding='''max_length''' , max_length=128 , return_tensors='''pt''' ) return tokenizer.pad(lowerCAmelCase__ , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. a__ : Optional[int] = DataLoader( tokenized_datasets['''train'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) a__ : Optional[Any] = DataLoader( tokenized_datasets['''validation'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) return train_dataloader, eval_dataloader def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : Any , lowerCAmelCase__ : Any ): model.eval() a__ : str = 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 ) with torch.no_grad(): a__ : Union[str, Any] = model(**lowerCAmelCase__ ) a__ : str = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times a__ , a__ : int = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowerCAmelCase__ ) - 1: a__ : int = predictions[: len(eval_dataloader.dataset ) - samples_seen] a__ : Optional[int] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowerCAmelCase__ , references=lowerCAmelCase__ , ) a__ : Any = metric.compute() return eval_metric["accuracy"] def __a ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[Any] ): # Initialize accelerator a__ : List[str] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a__ : Tuple = config['''lr'''] a__ : Union[str, Any] = int(config['''num_epochs'''] ) a__ : int = int(config['''seed'''] ) a__ : Dict = int(config['''batch_size'''] ) a__ : int = args.model_name_or_path set_seed(lowerCAmelCase__ ) a__ , a__ : str = get_dataloaders(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) a__ : int = AutoModelForSequenceClassification.from_pretrained(lowerCAmelCase__ , return_dict=lowerCAmelCase__ ) # Instantiate optimizer a__ : Tuple = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) a__ : Optional[Any] = optimizer_cls(params=model.parameters() , lr=lowerCAmelCase__ ) if accelerator.state.deepspeed_plugin is not None: a__ : Dict = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: a__ : Union[str, Any] = 1 a__ : str = (len(lowerCAmelCase__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): a__ : List[str] = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase__ , num_warmup_steps=0 , num_training_steps=lowerCAmelCase__ , ) else: a__ : Optional[int] = DummyScheduler(lowerCAmelCase__ , total_num_steps=lowerCAmelCase__ , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. a__ , a__ , a__ , a__ , a__ : Optional[int] = accelerator.prepare( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # We need to keep track of how many total steps we have iterated over a__ : Optional[Any] = 0 # We also need to keep track of the stating epoch so files are named properly a__ : List[Any] = 0 a__ : Tuple = evaluate.load('''glue''' , '''mrpc''' ) a__ : str = num_epochs if args.partial_train_epoch is not None: a__ : Tuple = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) a__ : Optional[Any] = args.resume_from_checkpoint.split('''epoch_''' )[1] a__ : Dict = '''''' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break a__ : Union[str, Any] = int(lowerCAmelCase__ ) + 1 a__ : Union[str, Any] = evaluation_loop(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) accelerator.print('''resumed checkpoint performance:''' , lowerCAmelCase__ ) accelerator.print('''resumed checkpoint\'s scheduler\'s lr:''' , lr_scheduler.get_lr()[0] ) accelerator.print('''resumed optimizers\'s lr:''' , optimizer.param_groups[0]['''lr'''] ) with open(os.path.join(args.output_dir , F'state_{starting_epoch-1}.json' ) , '''r''' ) as f: a__ : Dict = json.load(lowerCAmelCase__ ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model a__ : List[str] = {} for epoch in range(lowerCAmelCase__ , lowerCAmelCase__ ): model.train() for step, batch in enumerate(lowerCAmelCase__ ): a__ : Optional[Any] = model(**lowerCAmelCase__ ) a__ : str = outputs.loss a__ : int = loss / gradient_accumulation_steps accelerator.backward(lowerCAmelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 a__ : List[Any] = F'epoch_{epoch}' a__ : Dict = os.path.join(args.output_dir , lowerCAmelCase__ ) accelerator.save_state(lowerCAmelCase__ ) a__ : Union[str, Any] = evaluation_loop(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) a__ : Optional[int] = accuracy a__ : Dict = lr_scheduler.get_lr()[0] a__ : Optional[Any] = optimizer.param_groups[0]['''lr'''] a__ : int = epoch a__ : Any = overall_step accelerator.print(F'epoch {epoch}:' , lowerCAmelCase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , F'state_{epoch}.json' ) , '''w''' ) as f: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def __a ( ): a__ : str = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''' , type=lowerCAmelCase__ , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=lowerCAmelCase__ , ) parser.add_argument( '''--output_dir''' , type=lowerCAmelCase__ , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , ) parser.add_argument( '''--resume_from_checkpoint''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''If the training should continue from a checkpoint folder.''' , ) parser.add_argument( '''--partial_train_epoch''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''If passed, the training will stop after this number of epochs.''' , ) parser.add_argument( '''--num_epochs''' , type=lowerCAmelCase__ , default=2 , help='''Number of train epochs.''' , ) a__ : Any = parser.parse_args() a__ : Dict = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": main()
688
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : int = 0 def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[Any] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[Any] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[int] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict() config_dict.pop('''image_processor_type''' ) a__ : Union[str, Any] = CLIPImageProcessor(**A__ ) # save in new folder model_config.save_pretrained(A__ ) config.save_pretrained(A__ ) a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ ) # make sure private variable is not incorrectly saved a__ : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''clip-base is not a local folder and is not a valid model identifier''' ): a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' with self.assertRaises(A__ ): a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoImageProcessor.register(A__ , A__ ) with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[str] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = CustomImageProcessor.from_pretrained(A__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = True try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # If remote code is not set, the default is to use local a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. a__ : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub a__ : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(A__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
688
1
'''simple docstring''' import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'microsoft/unispeech-sat-base-100h-libri-ft': ( 'https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json' ), # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "unispeech-sat" def __init__( self : Optional[int] , A__ : str=3_2 , A__ : Union[str, Any]=7_6_8 , A__ : str=1_2 , A__ : Dict=1_2 , A__ : Dict=3_0_7_2 , A__ : Any="gelu" , A__ : Optional[int]=0.1 , A__ : List[Any]=0.1 , A__ : Tuple=0.1 , A__ : Union[str, Any]=0.0 , A__ : int=0.0 , A__ : Union[str, Any]=0.1 , A__ : Dict=0.1 , A__ : int=0.02 , A__ : str=1E-5 , A__ : List[Any]="group" , A__ : List[str]="gelu" , A__ : Union[str, Any]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2) , A__ : Tuple=(5, 2, 2, 2, 2, 2, 2) , A__ : Optional[int]=(1_0, 3, 3, 3, 3, 2, 2) , A__ : Tuple=False , A__ : Any=1_2_8 , A__ : str=1_6 , A__ : Optional[Any]=False , A__ : List[Any]=True , A__ : str=0.05 , A__ : Tuple=1_0 , A__ : str=2 , A__ : Dict=0.0 , A__ : int=1_0 , A__ : str=0 , A__ : List[Any]=3_2_0 , A__ : Dict=2 , A__ : Optional[Any]=0.1 , A__ : Dict=1_0_0 , A__ : Tuple=2_5_6 , A__ : Tuple=2_5_6 , A__ : Dict=0.1 , A__ : int="mean" , A__ : List[str]=False , A__ : Optional[Any]=False , A__ : Any=2_5_6 , A__ : Tuple=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 1_5_0_0) , A__ : Dict=(5, 3, 3, 1, 1) , A__ : int=(1, 2, 3, 1, 1) , A__ : Union[str, Any]=5_1_2 , A__ : str=0 , A__ : Any=1 , A__ : Dict=2 , A__ : Optional[Any]=5_0_4 , **A__ : Dict , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ , pad_token_id=A__ , bos_token_id=A__ , eos_token_id=A__ ) a__ : List[str] = hidden_size a__ : str = feat_extract_norm a__ : Dict = feat_extract_activation a__ : int = list(A__ ) a__ : Any = list(A__ ) a__ : Any = list(A__ ) a__ : Optional[Any] = conv_bias a__ : Tuple = num_conv_pos_embeddings a__ : Optional[Any] = num_conv_pos_embedding_groups a__ : int = len(self.conv_dim ) a__ : Optional[int] = num_hidden_layers a__ : Tuple = intermediate_size a__ : List[str] = hidden_act a__ : Dict = num_attention_heads a__ : Optional[Any] = hidden_dropout a__ : List[str] = attention_dropout a__ : Optional[int] = activation_dropout a__ : int = feat_proj_dropout a__ : Optional[Any] = final_dropout a__ : Dict = layerdrop a__ : List[str] = layer_norm_eps a__ : Dict = initializer_range a__ : Union[str, Any] = vocab_size a__ : Tuple = num_clusters a__ : Tuple = do_stable_layer_norm a__ : Tuple = 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 a__ : List[str] = apply_spec_augment a__ : Optional[int] = mask_time_prob a__ : List[Any] = mask_time_length a__ : Optional[Any] = mask_time_min_masks a__ : List[Any] = mask_feature_prob a__ : List[str] = mask_feature_length a__ : Optional[int] = mask_feature_min_masks # parameters for pretraining with codevector quantized representations a__ : Optional[Any] = num_codevectors_per_group a__ : List[str] = num_codevector_groups a__ : Union[str, Any] = contrastive_logits_temperature a__ : str = feat_quantizer_dropout a__ : Optional[int] = num_negatives a__ : Dict = codevector_dim a__ : Tuple = proj_codevector_dim a__ : Any = diversity_loss_weight # ctc loss a__ : List[Any] = ctc_loss_reduction a__ : Optional[Any] = ctc_zero_infinity # SequenceClassification-specific parameter. Feel free to ignore for other classes. a__ : Tuple = classifier_proj_size # XVector-specific parameters. Feel free to ignore for other classes. a__ : str = list(A__ ) a__ : str = list(A__ ) a__ : List[Any] = list(A__ ) a__ : Union[str, Any] = xvector_output_dim @property def __lowerCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' return functools.reduce(operator.mul , self.conv_stride , 1 )
688
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version __SCREAMING_SNAKE_CASE = get_logger(__name__) class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = "dummy_data" __UpperCamelCase = "datasets" __UpperCamelCase = False def __init__( self : Any , A__ : str , A__ : str , A__ : Union[Version, str] , A__ : Optional[str] = None , A__ : bool = False , A__ : bool = True , A__ : Optional[List[Callable]] = None , ) -> int: '''simple docstring''' a__ : Tuple = 0 a__ : Any = dataset_name a__ : int = cache_dir a__ : str = use_local_dummy_data a__ : List[str] = config # download_callbacks take a single url as input a__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root a__ : str = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general a__ : Optional[Any] = str(A__ ) # to be downloaded a__ : Tuple = None a__ : Tuple = None @property def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' if self._dummy_file is None: a__ : Dict = self.download_dummy_data() return self._dummy_file @property def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('''dummy''' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('''dummy''' , self.version_name ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : int = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) a__ : str = cached_path( A__ , cache_dir=self.cache_dir , extract_compressed_file=A__ , force_extract=A__ ) return os.path.join(A__ , self.dummy_file_name ) @property def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self._bucket_url is None: a__ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) ) return self._bucket_url @property def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , *A__ : int ) -> Union[str, Any]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested a__ : Tuple = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned a__ : Union[str, Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(A__ , A__ ): return self.create_dummy_data_dict(A__ , A__ ) elif isinstance(A__ , (list, tuple) ): return self.create_dummy_data_list(A__ , A__ ) else: return self.create_dummy_data_single(A__ , A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Any , *A__ : int ) -> Any: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Any , A__ : Optional[int] , A__ : Optional[Any] ) -> int: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , *A__ : List[Any] , **A__ : str ) -> Optional[Any]: '''simple docstring''' return path def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' return {} def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[str] ) -> Any: '''simple docstring''' a__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A__ , A__ ): for single_url in single_urls: download_callback(A__ ) else: a__ : Dict = single_urls download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A__ , A__ ): a__ : Optional[int] = [os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) for x in single_urls] else: a__ : Optional[Any] = single_urls a__ : Tuple = os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) a__ : List[str] = value # make sure that values are unique if all(isinstance(A__ , A__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique a__ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : str = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one a__ : Union[str, Any] = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , A__ ) ) for url in data_url ) a__ : Optional[Any] = all( url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): a__ : Dict = [data_url[0]] * len(A__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Optional[int] = os.path.join(A__ , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) ) dummy_data_list.append(A__ ) return dummy_data_list def __lowerCAmelCase ( self : Dict , A__ : Dict , A__ : str ) -> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Union[str, Any] = os.path.join(A__ , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) ) if os.path.exists(A__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' pass def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: '''simple docstring''' pass def __lowerCAmelCase ( self : Any , A__ : Tuple ) -> Any: '''simple docstring''' def _iter_archive_members(A__ : str ): # this preserves the order of the members inside the ZIP archive a__ : Dict = Path(self.dummy_file ).parent a__ : Tuple = path.relative_to(A__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: a__ : Optional[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A__ ) a__ : str = Path(A__ ) a__ : Optional[Any] = _iter_archive_members(A__ ) if self.use_local_dummy_data else path.rglob('''*''' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ): yield file_path.relative_to(A__ ).as_posix(), file_path.open('''rb''' ) def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> Tuple: '''simple docstring''' if not isinstance(A__ , A__ ): a__ : int = [paths] for path in paths: if os.path.isfile(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): return yield path else: for dirpath, dirnames, filenames in os.walk(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): continue dirnames.sort() for filename in sorted(A__ ): if filename.startswith(('''.''', '''__''') ): continue yield os.path.join(A__ , A__ )
688
1
'''simple docstring''' import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) __SCREAMING_SNAKE_CASE = logging.getLogger() def __a ( lowerCAmelCase__ : Path , lowerCAmelCase__ : list ): a__ : Optional[Any] = '''\n'''.join(lowerCAmelCase__ ) Path(lowerCAmelCase__ ).open('''w''' ).writelines(lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE = 'patrickvonplaten/t5-tiny-random' __SCREAMING_SNAKE_CASE = 'sshleifer/bart-tiny-random' __SCREAMING_SNAKE_CASE = 'sshleifer/tiny-mbart' __SCREAMING_SNAKE_CASE = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __lowerCAmelCase ( self : Dict , A__ : List[Any] ) -> Any: '''simple docstring''' a__ : Tuple = Path(self.get_auto_remove_tmp_dir() ) / '''utest_input.source''' a__ : str = input_file_name.parent / '''utest_output.txt''' assert not output_file_name.exists() a__ : int = [''' New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County.'''] _dump_articles(A__ , A__ ) a__ : int = str(Path(self.get_auto_remove_tmp_dir() ) / '''scores.json''' ) a__ : int = '''translation_en_to_de''' if model == T5_TINY else '''summarization''' a__ : Union[str, Any] = F'\n run_eval_search.py\n {model}\n {input_file_name}\n {output_file_name}\n --score_path {score_path}\n --task {task}\n --num_beams 2\n --length_penalty 2.0\n '.split() with patch.object(A__ , '''argv''' , A__ ): run_generate() assert Path(A__ ).exists() # os.remove(Path(output_file_name)) def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' self.run_eval_tester(A__ ) @parameterized.expand([BART_TINY, MBART_TINY] ) @slow def __lowerCAmelCase ( self : List[str] , A__ : List[Any] ) -> List[str]: '''simple docstring''' self.run_eval_tester(A__ ) @parameterized.expand([T5_TINY, MBART_TINY] ) @slow def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> int: '''simple docstring''' a__ : str = Path(self.get_auto_remove_tmp_dir() ) / '''utest_input.source''' a__ : Optional[int] = input_file_name.parent / '''utest_output.txt''' assert not output_file_name.exists() a__ : Optional[Any] = { '''en''': ['''Machine learning is great, isn\'t it?''', '''I like to eat bananas''', '''Tomorrow is another great day!'''], '''de''': [ '''Maschinelles Lernen ist großartig, oder?''', '''Ich esse gerne Bananen''', '''Morgen ist wieder ein toller Tag!''', ], } a__ : Dict = Path(self.get_auto_remove_tmp_dir() ) a__ : Dict = str(tmp_dir / '''scores.json''' ) a__ : List[Any] = str(tmp_dir / '''val.target''' ) _dump_articles(A__ , text['''en'''] ) _dump_articles(A__ , text['''de'''] ) a__ : List[str] = '''translation_en_to_de''' if model == T5_TINY else '''summarization''' a__ : int = F'\n run_eval_search.py\n {model}\n {str(A__ )}\n {str(A__ )}\n --score_path {score_path}\n --reference_path {reference_path}\n --task {task}\n '.split() testargs.extend(['''--search''', '''num_beams=1:2 length_penalty=0.9:1.0'''] ) with patch.object(A__ , '''argv''' , A__ ): with CaptureStdout() as cs: run_search() a__ : Any = [''' num_beams | length_penalty''', model, '''Best score args'''] a__ : Optional[Any] = ['''Info'''] if "translation" in task: expected_strings.append('''bleu''' ) else: expected_strings.extend(A__ ) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(A__ ).exists() os.remove(Path(A__ ) )
688
'''simple docstring''' import os import unittest from transformers import LxmertTokenizer, LxmertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class lowerCAmelCase__ ( lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = LxmertTokenizer __UpperCamelCase = LxmertTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def __lowerCAmelCase ( self : str ) -> str: '''simple docstring''' super().setUp() a__ : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] a__ : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def __lowerCAmelCase ( self : int , A__ : int ) -> int: '''simple docstring''' a__ : List[Any] = '''UNwant\u00E9d,running''' a__ : Optional[int] = '''unwanted, running''' return input_text, output_text def __lowerCAmelCase ( self : int ) -> Dict: '''simple docstring''' a__ : Optional[int] = self.tokenizer_class(self.vocab_file ) a__ : List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(A__ , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [7, 4, 5, 1_0, 8, 9] ) def __lowerCAmelCase ( self : Any ) -> Dict: '''simple docstring''' if not self.test_rust_tokenizer: return a__ : Union[str, Any] = self.get_tokenizer() a__ : Union[str, Any] = self.get_rust_tokenizer() a__ : str = '''I was born in 92000, and this is falsé.''' a__ : Tuple = tokenizer.tokenize(A__ ) a__ : Tuple = rust_tokenizer.tokenize(A__ ) self.assertListEqual(A__ , A__ ) a__ : Optional[int] = tokenizer.encode(A__ , add_special_tokens=A__ ) a__ : Optional[Any] = rust_tokenizer.encode(A__ , add_special_tokens=A__ ) self.assertListEqual(A__ , A__ ) a__ : List[str] = self.get_rust_tokenizer() a__ : str = tokenizer.encode(A__ ) a__ : int = rust_tokenizer.encode(A__ ) self.assertListEqual(A__ , A__ )
688
1
'''simple docstring''' def __a ( lowerCAmelCase__ : int = 1000 ): a__ : Dict = 2**power a__ : Optional[int] = 0 while n: a__ , a__ : Optional[Any] = r + n % 10, n // 10 return r if __name__ == "__main__": print(solution(int(str(input()).strip())))
688
'''simple docstring''' import argparse from transformers import ( TapasConfig, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasTokenizer, load_tf_weights_in_tapas, ) from transformers.utils import logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : str ): # Initialise PyTorch model. # If you want to convert a checkpoint that uses absolute position embeddings, make sure to set reset_position_index_per_cell of # TapasConfig to False. # initialize configuration from json file a__ : Dict = TapasConfig.from_json_file(lowerCAmelCase__ ) # set absolute/relative position embeddings parameter a__ : List[Any] = reset_position_index_per_cell # set remaining parameters of TapasConfig as well as the model based on the task if task == "SQA": a__ : Optional[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WTQ": # run_task_main.py hparams a__ : List[str] = 4 a__ : Optional[int] = True # hparam_utils.py hparams a__ : List[Any] = 0.664694 a__ : List[Any] = 0.207951 a__ : Union[str, Any] = 0.121194 a__ : Optional[Any] = True a__ : Optional[int] = True a__ : List[str] = False a__ : Union[str, Any] = 0.0352513 a__ : Any = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "WIKISQL_SUPERVISED": # run_task_main.py hparams a__ : Tuple = 4 a__ : Dict = False # hparam_utils.py hparams a__ : str = 36.4519 a__ : str = 0.903421 a__ : Optional[Any] = 222.088 a__ : Dict = True a__ : Dict = True a__ : Dict = True a__ : str = 0.763141 a__ : List[Any] = TapasForQuestionAnswering(config=lowerCAmelCase__ ) elif task == "TABFACT": a__ : List[str] = TapasForSequenceClassification(config=lowerCAmelCase__ ) elif task == "MLM": a__ : Tuple = TapasForMaskedLM(config=lowerCAmelCase__ ) elif task == "INTERMEDIATE_PRETRAINING": a__ : List[str] = TapasModel(config=lowerCAmelCase__ ) else: raise ValueError(F'Task {task} not supported.' ) print(F'Building PyTorch model from configuration: {config}' ) # Load weights from tf checkpoint load_tf_weights_in_tapas(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model (weights and configuration) print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowerCAmelCase__ ) # Save tokenizer files print(F'Save tokenizer files to {pytorch_dump_path}' ) a__ : Optional[Any] = TapasTokenizer(vocab_file=tf_checkpoint_path[:-10] + '''vocab.txt''' , model_max_length=512 ) tokenizer.save_pretrained(lowerCAmelCase__ ) print('''Used relative position embeddings:''' , model.config.reset_position_index_per_cell ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--task', default='SQA', type=str, help='Model task for which to convert a checkpoint. Defaults to SQA.' ) parser.add_argument( '--reset_position_index_per_cell', default=False, action='store_true', help='Whether to use relative position embeddings or not. Defaults to True.', ) parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--tapas_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained TAPAS model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_tf_checkpoint_to_pytorch( args.task, args.reset_position_index_per_cell, args.tf_checkpoint_path, args.tapas_config_file, args.pytorch_dump_path, )
688
1
'''simple docstring''' from __future__ import annotations from math import ceil, floor, sqrt def __a ( lowerCAmelCase__ : int = 2000000 ): a__ : list[int] = [0] a__ : int for idx in range(1 , ceil(sqrt(target * 2 ) * 1.1 ) ): triangle_numbers.append(triangle_numbers[-1] + idx ) # we want this to be as close as possible to target a__ : int = 0 # the area corresponding to the grid that gives the product closest to target a__ : int = 0 # an estimate of b, using the quadratic formula a__ : float # the largest integer less than b_estimate a__ : int # the largest integer less than b_estimate a__ : int # the triangle number corresponding to b_floor a__ : int # the triangle number corresponding to b_ceil a__ : int for idx_a, triangle_a in enumerate(triangle_numbers[1:] , 1 ): a__ : Any = (-1 + sqrt(1 + 8 * target / triangle_a )) / 2 a__ : Any = floor(lowerCAmelCase__ ) a__ : Optional[int] = ceil(lowerCAmelCase__ ) a__ : List[str] = triangle_numbers[b_floor] a__ : Dict = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a ) < abs( target - best_product ): a__ : Tuple = triangle_b_first_guess * triangle_a a__ : str = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a ) < abs( target - best_product ): a__ : Optional[int] = triangle_b_second_guess * triangle_a a__ : Dict = idx_a * b_ceil return area if __name__ == "__main__": print(f'{solution() = }')
688
'''simple docstring''' 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_fnet import FNetTokenizer else: __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model', }, 'tokenizer_file': { 'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json', 'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json', }, } __SCREAMING_SNAKE_CASE = { 'google/fnet-base': 5_1_2, 'google/fnet-large': 5_1_2, } __SCREAMING_SNAKE_CASE = '▁' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "token_type_ids"] __UpperCamelCase = FNetTokenizer def __init__( self : Any , A__ : Any=None , A__ : int=None , A__ : List[str]=False , A__ : int=True , A__ : str=True , A__ : List[Any]="<unk>" , A__ : Dict="[SEP]" , A__ : List[str]="<pad>" , A__ : Union[str, Any]="[CLS]" , A__ : Dict="[MASK]" , **A__ : Tuple , ) -> List[str]: '''simple docstring''' a__ : Optional[int] = ( AddedToken(A__ , lstrip=A__ , rstrip=A__ , normalized=A__ ) if isinstance(A__ , A__ ) else mask_token ) super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , remove_space=A__ , keep_accents=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , **A__ , ) a__ : Optional[Any] = do_lower_case a__ : Dict = remove_space a__ : List[Any] = keep_accents a__ : Optional[Any] = vocab_file a__ : Any = False if not self.vocab_file else True def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Optional[int] = [self.sep_token_id] a__ : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __lowerCAmelCase ( self : List[Any] , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Dict = [self.sep_token_id] a__ : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : Tuple , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(A__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return a__ : Union[str, Any] = os.path.join( A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A__ ): copyfile(self.vocab_file , A__ ) return (out_vocab_file,)
688
1
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import evaluate import numpy as np import torch from datasets import load_dataset from PIL import Image from torchvision.transforms import ( CenterCrop, Compose, Normalize, RandomHorizontalFlip, RandomResizedCrop, Resize, ToTensor, ) import transformers from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForImageClassification, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('4.31.0') require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/image-classification/requirements.txt') __SCREAMING_SNAKE_CASE = list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys()) __SCREAMING_SNAKE_CASE = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) def __a ( lowerCAmelCase__ : str ): with open(lowerCAmelCase__ , '''rb''' ) as f: a__ : Any = Image.open(lowerCAmelCase__ ) return im.convert('''RGB''' ) @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={ "help": "Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub)." } , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} ) __UpperCamelCase = field(default=lowerCAmelCase_ , metadata={"help": "A folder containing the training data."} ) __UpperCamelCase = field(default=lowerCAmelCase_ , metadata={"help": "A folder containing the validation data."} ) __UpperCamelCase = field( default=0.15 , metadata={"help": "Percent to split off of train for validation."} ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) } , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of evaluation examples to this " "value if set." ) } , ) def __lowerCAmelCase ( self : Union[str, Any] ) -> str: '''simple docstring''' if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None): raise ValueError( '''You must specify either a dataset name from the hub or a train and/or validation directory.''' ) @dataclass class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = field( default="google/vit-base-patch16-224-in21k" , metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={"help": "If training from scratch, pass a model type from the list: " + ", ".join(lowerCAmelCase_ )} , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={"help": "Pretrained config name or path if not the same as model_name"} ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} ) __UpperCamelCase = field( default="main" , metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} , ) __UpperCamelCase = field(default=lowerCAmelCase_ , metadata={"help": "Name or path of preprocessor config."} ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={ "help": ( "Will use the token generated when running `huggingface-cli login` (necessary to use this script " "with private models)." ) } , ) __UpperCamelCase = field( default=lowerCAmelCase_ , metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} , ) def __a ( lowerCAmelCase__ : List[str] ): a__ : Optional[Any] = torch.stack([example['''pixel_values'''] for example in examples] ) a__ : Any = torch.tensor([example['''labels'''] for example in examples] ) return {"pixel_values": pixel_values, "labels": labels} def __a ( ): # 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. a__ : Dict = 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. a__ , a__ , a__ : List[str] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: a__ , a__ , a__ : List[Any] = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry('''run_image_classification''' , lowerCAmelCase__ , lowerCAmelCase__ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() a__ : Optional[Any] = training_args.get_process_log_level() logger.setLevel(lowerCAmelCase__ ) transformers.utils.logging.set_verbosity(lowerCAmelCase__ ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) logger.info(F'Training/evaluation parameters {training_args}' ) # Detecting last checkpoint. a__ : int = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: a__ : List[Any] = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' '''Use --overwrite_output_dir to overcome.''' ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.''' ) # Set seed before initializing model. set_seed(training_args.seed ) # Initialize our dataset and prepare it for the 'image-classification' task. if data_args.dataset_name is not None: a__ : Union[str, Any] = load_dataset( data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir , task='''image-classification''' , use_auth_token=True if model_args.use_auth_token else None , ) else: a__ : Optional[Any] = {} if data_args.train_dir is not None: a__ : int = os.path.join(data_args.train_dir , '''**''' ) if data_args.validation_dir is not None: a__ : Tuple = os.path.join(data_args.validation_dir , '''**''' ) a__ : str = load_dataset( '''imagefolder''' , data_files=lowerCAmelCase__ , cache_dir=model_args.cache_dir , task='''image-classification''' , ) # If we don't have a validation split, split off a percentage of train as validation. a__ : Any = None if '''validation''' in dataset.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , lowerCAmelCase__ ) and data_args.train_val_split > 0.0: a__ : Dict = dataset['''train'''].train_test_split(data_args.train_val_split ) a__ : List[str] = split['''train'''] a__ : Union[str, Any] = split['''test'''] # Prepare label mappings. # We'll include these in the model's config to get human readable labels in the Inference API. a__ : Any = dataset['''train'''].features['''labels'''].names a__ , a__ : Optional[int] = {}, {} for i, label in enumerate(lowerCAmelCase__ ): a__ : Optional[Any] = str(lowerCAmelCase__ ) a__ : Optional[Any] = label # Load the accuracy metric from the datasets package a__ : Optional[int] = evaluate.load('''accuracy''' ) # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(lowerCAmelCase__ : Dict ): return metric.compute(predictions=np.argmax(p.predictions , axis=1 ) , references=p.label_ids ) a__ : Optional[int] = AutoConfig.from_pretrained( model_args.config_name or model_args.model_name_or_path , num_labels=len(lowerCAmelCase__ ) , labelaid=lowerCAmelCase__ , idalabel=lowerCAmelCase__ , finetuning_task='''image-classification''' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) a__ : Dict = AutoModelForImageClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('''.ckpt''' in model_args.model_name_or_path ) , config=lowerCAmelCase__ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , ) a__ : Tuple = AutoImageProcessor.from_pretrained( model_args.image_processor_name or model_args.model_name_or_path , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) # Define torchvision transforms to be applied to each image. if "shortest_edge" in image_processor.size: a__ : Optional[Any] = image_processor.size['''shortest_edge'''] else: a__ : Optional[int] = (image_processor.size['''height'''], image_processor.size['''width''']) a__ : Any = Normalize(mean=image_processor.image_mean , std=image_processor.image_std ) a__ : int = Compose( [ RandomResizedCrop(lowerCAmelCase__ ), RandomHorizontalFlip(), ToTensor(), normalize, ] ) a__ : Any = Compose( [ Resize(lowerCAmelCase__ ), CenterCrop(lowerCAmelCase__ ), ToTensor(), normalize, ] ) def train_transforms(lowerCAmelCase__ : str ): a__ : int = [ _train_transforms(pil_img.convert('''RGB''' ) ) for pil_img in example_batch['''image'''] ] return example_batch def val_transforms(lowerCAmelCase__ : int ): a__ : Tuple = [_val_transforms(pil_img.convert('''RGB''' ) ) for pil_img in example_batch['''image''']] return example_batch if training_args.do_train: if "train" not in dataset: raise ValueError('''--do_train requires a train dataset''' ) if data_args.max_train_samples is not None: a__ : Any = ( dataset['''train'''].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) ) # Set the training transforms dataset["train"].set_transform(lowerCAmelCase__ ) if training_args.do_eval: if "validation" not in dataset: raise ValueError('''--do_eval requires a validation dataset''' ) if data_args.max_eval_samples is not None: a__ : str = ( dataset['''validation'''].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms dataset["validation"].set_transform(lowerCAmelCase__ ) # Initalize our trainer a__ : Optional[Any] = Trainer( model=lowerCAmelCase__ , args=lowerCAmelCase__ , train_dataset=dataset['''train'''] if training_args.do_train else None , eval_dataset=dataset['''validation'''] if training_args.do_eval else None , compute_metrics=lowerCAmelCase__ , tokenizer=lowerCAmelCase__ , data_collator=lowerCAmelCase__ , ) # Training if training_args.do_train: a__ : str = None if training_args.resume_from_checkpoint is not None: a__ : int = training_args.resume_from_checkpoint elif last_checkpoint is not None: a__ : Dict = last_checkpoint a__ : List[str] = trainer.train(resume_from_checkpoint=lowerCAmelCase__ ) trainer.save_model() trainer.log_metrics('''train''' , train_result.metrics ) trainer.save_metrics('''train''' , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: a__ : List[str] = trainer.evaluate() trainer.log_metrics('''eval''' , lowerCAmelCase__ ) trainer.save_metrics('''eval''' , lowerCAmelCase__ ) # Write model card and (optionally) push to hub a__ : str = { '''finetuned_from''': model_args.model_name_or_path, '''tasks''': '''image-classification''', '''dataset''': data_args.dataset_name, '''tags''': ['''image-classification''', '''vision'''], } if training_args.push_to_hub: trainer.push_to_hub(**lowerCAmelCase__ ) else: trainer.create_model_card(**lowerCAmelCase__ ) if __name__ == "__main__": main()
688
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { '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' ), }, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': 5_1_2, 'distilbert-base-uncased-distilled-squad': 5_1_2, 'distilbert-base-cased': 5_1_2, 'distilbert-base-cased-distilled-squad': 5_1_2, 'distilbert-base-german-cased': 5_1_2, 'distilbert-base-multilingual-cased': 5_1_2, } __SCREAMING_SNAKE_CASE = { '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 lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = DistilBertTokenizer def __init__( self : str , A__ : Optional[Any]=None , A__ : Any=None , A__ : Tuple=True , A__ : List[Any]="[UNK]" , A__ : List[str]="[SEP]" , A__ : Tuple="[PAD]" , A__ : Optional[int]="[CLS]" , A__ : Union[str, Any]="[MASK]" , A__ : List[str]=True , A__ : Any=None , **A__ : int , ) -> str: '''simple docstring''' super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , tokenize_chinese_chars=A__ , strip_accents=A__ , **A__ , ) a__ : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , A__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , A__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , A__ ) != tokenize_chinese_chars ): a__ : int = getattr(A__ , normalizer_state.pop('''type''' ) ) a__ : List[Any] = do_lower_case a__ : str = strip_accents a__ : List[str] = tokenize_chinese_chars a__ : Dict = normalizer_class(**A__ ) a__ : List[Any] = do_lower_case def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Dict=None ) -> List[str]: '''simple docstring''' a__ : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : int , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : List[str] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : str , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' a__ : int = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
688
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} __SCREAMING_SNAKE_CASE = { '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' ), }, } __SCREAMING_SNAKE_CASE = { 'distilbert-base-uncased': 5_1_2, 'distilbert-base-uncased-distilled-squad': 5_1_2, 'distilbert-base-cased': 5_1_2, 'distilbert-base-cased-distilled-squad': 5_1_2, 'distilbert-base-german-cased': 5_1_2, 'distilbert-base-multilingual-cased': 5_1_2, } __SCREAMING_SNAKE_CASE = { '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 lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = PRETRAINED_INIT_CONFIGURATION __UpperCamelCase = ["input_ids", "attention_mask"] __UpperCamelCase = DistilBertTokenizer def __init__( self : str , A__ : Optional[Any]=None , A__ : Any=None , A__ : Tuple=True , A__ : List[Any]="[UNK]" , A__ : List[str]="[SEP]" , A__ : Tuple="[PAD]" , A__ : Optional[int]="[CLS]" , A__ : Union[str, Any]="[MASK]" , A__ : List[str]=True , A__ : Any=None , **A__ : int , ) -> str: '''simple docstring''' super().__init__( A__ , tokenizer_file=A__ , do_lower_case=A__ , unk_token=A__ , sep_token=A__ , pad_token=A__ , cls_token=A__ , mask_token=A__ , tokenize_chinese_chars=A__ , strip_accents=A__ , **A__ , ) a__ : Dict = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , A__ ) != do_lower_case or normalizer_state.get('''strip_accents''' , A__ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , A__ ) != tokenize_chinese_chars ): a__ : int = getattr(A__ , normalizer_state.pop('''type''' ) ) a__ : List[Any] = do_lower_case a__ : str = strip_accents a__ : List[str] = tokenize_chinese_chars a__ : Dict = normalizer_class(**A__ ) a__ : List[Any] = do_lower_case def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Dict=None ) -> List[str]: '''simple docstring''' a__ : List[str] = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __lowerCAmelCase ( self : int , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : List[str] = [self.sep_token_id] a__ : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __lowerCAmelCase ( self : str , A__ : str , A__ : Optional[str] = None ) -> Tuple[str]: '''simple docstring''' a__ : int = self._tokenizer.model.save(A__ , name=A__ ) return tuple(A__ )
688
'''simple docstring''' from __future__ import annotations import time from math import sqrt # 1 for manhattan, 0 for euclidean __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] __SCREAMING_SNAKE_CASE = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right __SCREAMING_SNAKE_CASE = tuple[int, int] class lowerCAmelCase__ : """simple docstring""" def __init__( self : str , A__ : int , A__ : int , A__ : int , A__ : int , A__ : int , A__ : Node | None , ) -> None: '''simple docstring''' a__ : Optional[int] = pos_x a__ : str = pos_y a__ : Optional[int] = (pos_y, pos_x) a__ : List[str] = goal_x a__ : Any = goal_y a__ : Any = g_cost a__ : Optional[int] = parent a__ : Union[str, Any] = self.calculate_heuristic() a__ : List[Any] = self.g_cost + self.h_cost def __lowerCAmelCase ( self : Union[str, Any] ) -> float: '''simple docstring''' a__ : List[str] = self.pos_x - self.goal_x a__ : List[str] = self.pos_y - self.goal_y if HEURISTIC == 1: return abs(A__ ) + abs(A__ ) else: return sqrt(dy**2 + dx**2 ) def __lt__( self : List[Any] , A__ : Node ) -> bool: '''simple docstring''' return self.f_cost < other.f_cost class lowerCAmelCase__ : """simple docstring""" def __init__( self : Optional[int] , A__ : TPosition , A__ : TPosition ) -> Optional[Any]: '''simple docstring''' a__ : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , A__ ) a__ : Dict = Node(goal[1] , goal[0] , goal[1] , goal[0] , 9_9_9_9_9 , A__ ) a__ : Dict = [self.start] a__ : list[Node] = [] a__ : str = False def __lowerCAmelCase ( self : List[str] ) -> list[TPosition]: '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() a__ : Dict = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: return self.retrace_path(A__ ) self.closed_nodes.append(A__ ) a__ : List[Any] = self.get_successors(A__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[int] = self.open_nodes.pop(self.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(A__ ) else: self.open_nodes.append(A__ ) return [self.start.pos] def __lowerCAmelCase ( self : Optional[Any] , A__ : Node ) -> list[Node]: '''simple docstring''' a__ : Optional[int] = [] for action in delta: a__ : List[Any] = parent.pos_x + action[1] a__ : Tuple = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(A__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( A__ , A__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , A__ , ) ) return successors def __lowerCAmelCase ( self : List[Any] , A__ : Node | None ) -> list[TPosition]: '''simple docstring''' a__ : Union[str, Any] = node a__ : Optional[Any] = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) a__ : Any = current_node.parent path.reverse() return path class lowerCAmelCase__ : """simple docstring""" def __init__( self : List[Any] , A__ : TPosition , A__ : TPosition ) -> None: '''simple docstring''' a__ : str = AStar(A__ , A__ ) a__ : Optional[int] = AStar(A__ , A__ ) a__ : List[str] = False def __lowerCAmelCase ( self : Tuple ) -> list[TPosition]: '''simple docstring''' while self.fwd_astar.open_nodes or self.bwd_astar.open_nodes: self.fwd_astar.open_nodes.sort() self.bwd_astar.open_nodes.sort() a__ : int = self.fwd_astar.open_nodes.pop(0 ) a__ : List[Any] = self.bwd_astar.open_nodes.pop(0 ) if current_bwd_node.pos == current_fwd_node.pos: return self.retrace_bidirectional_path( A__ , A__ ) self.fwd_astar.closed_nodes.append(A__ ) self.bwd_astar.closed_nodes.append(A__ ) a__ : Tuple = current_bwd_node a__ : Optional[int] = current_fwd_node a__ : Optional[int] = { self.fwd_astar: self.fwd_astar.get_successors(A__ ), self.bwd_astar: self.bwd_astar.get_successors(A__ ), } for astar in [self.fwd_astar, self.bwd_astar]: for child_node in successors[astar]: if child_node in astar.closed_nodes: continue if child_node not in astar.open_nodes: astar.open_nodes.append(A__ ) else: # retrieve the best current path a__ : Optional[Any] = astar.open_nodes.pop( astar.open_nodes.index(A__ ) ) if child_node.g_cost < better_node.g_cost: astar.open_nodes.append(A__ ) else: astar.open_nodes.append(A__ ) return [self.fwd_astar.start.pos] def __lowerCAmelCase ( self : List[str] , A__ : Node , A__ : Node ) -> list[TPosition]: '''simple docstring''' a__ : str = self.fwd_astar.retrace_path(A__ ) a__ : List[str] = self.bwd_astar.retrace_path(A__ ) bwd_path.pop() bwd_path.reverse() a__ : Optional[int] = fwd_path + bwd_path return path if __name__ == "__main__": # all coordinates are given in format [y,x] __SCREAMING_SNAKE_CASE = (0, 0) __SCREAMING_SNAKE_CASE = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = AStar(init, goal) __SCREAMING_SNAKE_CASE = a_star.search() __SCREAMING_SNAKE_CASE = time.time() - start_time print(f'AStar execution time = {end_time:f} seconds') __SCREAMING_SNAKE_CASE = time.time() __SCREAMING_SNAKE_CASE = BidirectionalAStar(init, goal) __SCREAMING_SNAKE_CASE = time.time() - bd_start_time print(f'BidirectionalAStar execution time = {bd_end_time:f} seconds')
688
1
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'junnyu/roformer_chinese_small': 'https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/config.json', 'junnyu/roformer_chinese_base': 'https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/config.json', 'junnyu/roformer_chinese_char_small': ( 'https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/config.json' ), 'junnyu/roformer_chinese_char_base': ( 'https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/config.json' ), 'junnyu/roformer_small_discriminator': ( 'https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/config.json' ), 'junnyu/roformer_small_generator': ( 'https://huggingface.co/junnyu/roformer_small_generator/resolve/main/config.json' ), # See all RoFormer models at https://huggingface.co/models?filter=roformer } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "roformer" def __init__( self : Dict , A__ : Any=5_0_0_0_0 , A__ : int=None , A__ : List[str]=7_6_8 , A__ : List[Any]=1_2 , A__ : Optional[Any]=1_2 , A__ : str=3_0_7_2 , A__ : List[Any]="gelu" , A__ : Union[str, Any]=0.1 , A__ : Union[str, Any]=0.1 , A__ : Tuple=1_5_3_6 , A__ : Tuple=2 , A__ : Optional[Any]=0.02 , A__ : int=1E-12 , A__ : str=0 , A__ : List[str]=False , A__ : List[Any]=True , **A__ : Dict , ) -> List[Any]: '''simple docstring''' super().__init__(pad_token_id=A__ , **A__ ) a__ : Union[str, Any] = vocab_size a__ : Tuple = hidden_size if embedding_size is None else embedding_size a__ : int = hidden_size a__ : Optional[Any] = num_hidden_layers a__ : Optional[int] = num_attention_heads a__ : Dict = hidden_act a__ : str = intermediate_size a__ : List[str] = hidden_dropout_prob a__ : Any = attention_probs_dropout_prob a__ : List[str] = max_position_embeddings a__ : str = type_vocab_size a__ : Union[str, Any] = initializer_range a__ : Tuple = layer_norm_eps a__ : Optional[int] = rotary_value a__ : List[str] = use_cache class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" @property def __lowerCAmelCase ( self : Tuple ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task == "multiple-choice": a__ : str = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: a__ : List[Any] = {0: '''batch''', 1: '''sequence'''} a__ : Any = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
688
'''simple docstring''' import argparse import torch from transformers import GPTaConfig, GPTaModel, load_tf_weights_in_gpta from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] ): # Construct model if gpta_config_file == "": a__ : Union[str, Any] = GPTaConfig() else: a__ : Dict = GPTaConfig.from_json_file(lowerCAmelCase__ ) a__ : Optional[int] = GPTaModel(lowerCAmelCase__ ) # Load weights from numpy load_tf_weights_in_gpta(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Save pytorch-model a__ : int = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME a__ : Union[str, Any] = pytorch_dump_folder_path + '''/''' + CONFIG_NAME print(F'Save PyTorch model to {pytorch_weights_dump_path}' ) torch.save(model.state_dict() , lowerCAmelCase__ ) print(F'Save configuration file to {pytorch_config_dump_path}' ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--gpt2_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--gpt2_config_file', default='', type=str, help=( 'An optional config json file corresponding to the pre-trained OpenAI model. \n' 'This specifies the model architecture.' ), ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_gpta_checkpoint_to_pytorch(args.gpta_checkpoint_path, args.gpta_config_file, args.pytorch_dump_folder_path)
688
1
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : int = 0 def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[Any] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[Any] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[int] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict() config_dict.pop('''image_processor_type''' ) a__ : Union[str, Any] = CLIPImageProcessor(**A__ ) # save in new folder model_config.save_pretrained(A__ ) config.save_pretrained(A__ ) a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ ) # make sure private variable is not incorrectly saved a__ : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''clip-base is not a local folder and is not a valid model identifier''' ): a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' with self.assertRaises(A__ ): a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoImageProcessor.register(A__ , A__ ) with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[str] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = CustomImageProcessor.from_pretrained(A__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = True try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # If remote code is not set, the default is to use local a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. a__ : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub a__ : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(A__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
688
'''simple docstring''' import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel __SCREAMING_SNAKE_CASE = False __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = False if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') __SCREAMING_SNAKE_CASE = parser.parse_args() __SCREAMING_SNAKE_CASE = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } __SCREAMING_SNAKE_CASE = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } __SCREAMING_SNAKE_CASE = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: __SCREAMING_SNAKE_CASE = reader.read() __SCREAMING_SNAKE_CASE = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): __SCREAMING_SNAKE_CASE = UNetaDModel(**config) else: __SCREAMING_SNAKE_CASE = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel __SCREAMING_SNAKE_CASE = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) __SCREAMING_SNAKE_CASE = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: __SCREAMING_SNAKE_CASE = config[key] del config[key] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['down_block_types']] __SCREAMING_SNAKE_CASE = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: __SCREAMING_SNAKE_CASE = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) __SCREAMING_SNAKE_CASE = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue __SCREAMING_SNAKE_CASE = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: __SCREAMING_SNAKE_CASE = param_value __SCREAMING_SNAKE_CASE = True if not has_changed: __SCREAMING_SNAKE_CASE = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
688
1
'''simple docstring''' from ..utils import DummyObject, requires_backends class lowerCAmelCase__ ( metaclass=lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = ["transformers", "torch", "note_seq"] def __init__( self : Optional[int] , *A__ : Any , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' requires_backends(self , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def __lowerCAmelCase ( cls : Any , *A__ : Dict , **A__ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] ) @classmethod def __lowerCAmelCase ( cls : Any , *A__ : List[Any] , **A__ : Dict ) -> int: '''simple docstring''' requires_backends(cls , ['''transformers''', '''torch''', '''note_seq'''] )
688
'''simple docstring''' import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = (KDPMaDiscreteScheduler,) __UpperCamelCase = 10 def __lowerCAmelCase ( self : Optional[Any] , **A__ : Optional[int] ) -> int: '''simple docstring''' a__ : Optional[int] = { '''num_train_timesteps''': 1_1_0_0, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**A__ ) return config def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=A__ ) def __lowerCAmelCase ( self : List[str] ) -> List[str]: '''simple docstring''' for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=A__ , beta_end=A__ ) def __lowerCAmelCase ( self : Tuple ) -> List[str]: '''simple docstring''' for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=A__ ) def __lowerCAmelCase ( self : str ) -> Optional[int]: '''simple docstring''' a__ : Any = self.scheduler_classes[0] a__ : str = self.get_scheduler_config(prediction_type='''v_prediction''' ) a__ : Dict = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : Tuple = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Dict = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : Optional[Any] = scheduler.scale_model_input(A__ , A__ ) a__ : Union[str, Any] = model(A__ , A__ ) a__ : List[str] = scheduler.step(A__ , A__ , A__ ) a__ : Optional[Any] = output.prev_sample a__ : Tuple = torch.sum(torch.abs(A__ ) ) a__ : Optional[int] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693_4286_5017_0972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' if torch_device == "mps": return a__ : List[Any] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : Tuple = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps ) a__ : List[Any] = self.dummy_model() a__ : Any = self.dummy_sample_deter * scheduler.init_noise_sigma a__ : Any = sample.to(A__ ) for i, t in enumerate(scheduler.timesteps ): a__ : str = scheduler.scale_model_input(A__ , A__ ) a__ : List[str] = model(A__ , A__ ) a__ : str = scheduler.step(A__ , A__ , A__ ) a__ : List[Any] = output.prev_sample a__ : Dict = torch.sum(torch.abs(A__ ) ) a__ : Optional[Any] = torch.mean(torch.abs(A__ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def __lowerCAmelCase ( self : str ) -> int: '''simple docstring''' if torch_device == "mps": return a__ : Optional[int] = self.scheduler_classes[0] a__ : Tuple = self.get_scheduler_config() a__ : List[Any] = scheduler_class(**A__ ) scheduler.set_timesteps(self.num_inference_steps , device=A__ ) a__ : Union[str, Any] = self.dummy_model() a__ : List[Any] = self.dummy_sample_deter.to(A__ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: a__ : Optional[int] = scheduler.scale_model_input(A__ , A__ ) a__ : List[Any] = model(A__ , A__ ) a__ : Any = scheduler.step(A__ , A__ , A__ ) a__ : List[str] = output.prev_sample a__ : Any = torch.sum(torch.abs(A__ ) ) a__ : Union[str, Any] = torch.mean(torch.abs(A__ ) ) if str(A__ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
688
1
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import KandinskyPipeline, KandinskyPriorPipeline else: from .pipeline_kandinsky import KandinskyPipeline from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput from .text_encoder import MultilingualCLIP
688
'''simple docstring''' import unittest from transformers.utils.backbone_utils import ( BackboneMixin, get_aligned_output_features_output_indices, verify_out_features_out_indices, ) class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' a__ : str = ['''a''', '''b''', '''c'''] # Defaults to last layer if both are None a__ , a__ : List[Any] = get_aligned_output_features_output_indices(A__ , A__ , A__ ) self.assertEqual(A__ , ['''c'''] ) self.assertEqual(A__ , [2] ) # Out indices set to match out features a__ , a__ : Optional[int] = get_aligned_output_features_output_indices(['''a''', '''c'''] , A__ , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features set to match out indices a__ , a__ : int = get_aligned_output_features_output_indices(A__ , [0, 2] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [0, 2] ) # Out features selected from negative indices a__ , a__ : List[str] = get_aligned_output_features_output_indices(A__ , [-3, -1] , A__ ) self.assertEqual(A__ , ['''a''', '''c'''] ) self.assertEqual(A__ , [-3, -1] ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , A__ ) # Out features must be a list with self.assertRaises(A__ ): verify_out_features_out_indices(('''a''', '''b''') , (0, 1) , ['''a''', '''b'''] ) # Out features must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 1) , ['''a'''] ) # Out indices must be a list or tuple with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , 0 , ['''a''', '''b'''] ) # Out indices must be a subset of stage names with self.assertRaises(A__ ): verify_out_features_out_indices(A__ , (0, 1) , ['''a'''] ) # Out features and out indices must be the same length with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0,) , ['''a''', '''b''', '''c'''] ) # Out features should match out indices with self.assertRaises(A__ ): verify_out_features_out_indices(['''a''', '''b'''] , (0, 2) , ['''a''', '''b''', '''c'''] ) # Out features and out indices should be in order with self.assertRaises(A__ ): verify_out_features_out_indices(['''b''', '''a'''] , (0, 1) , ['''a''', '''b'''] ) # Check passes with valid inputs verify_out_features_out_indices(['''a''', '''b''', '''d'''] , (0, 1, -1) , ['''a''', '''b''', '''c''', '''d'''] ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' a__ : Optional[Any] = BackboneMixin() a__ : int = ['''a''', '''b''', '''c'''] a__ : List[Any] = ['''a''', '''c'''] a__ : Tuple = [0, 2] # Check that the output features and indices are set correctly self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [0, 2] ) # Check out features and indices are updated correctly a__ : Dict = ['''a''', '''b'''] self.assertEqual(backbone.out_features , ['''a''', '''b'''] ) self.assertEqual(backbone.out_indices , [0, 1] ) a__ : int = [-3, -1] self.assertEqual(backbone.out_features , ['''a''', '''c'''] ) self.assertEqual(backbone.out_indices , [-3, -1] )
688
1
'''simple docstring''' import os __SCREAMING_SNAKE_CASE = {'I': 1, 'V': 5, 'X': 1_0, 'L': 5_0, 'C': 1_0_0, 'D': 5_0_0, 'M': 1_0_0_0} def __a ( lowerCAmelCase__ : str ): a__ : Optional[Any] = 0 a__ : Optional[Any] = 0 while index < len(lowerCAmelCase__ ) - 1: a__ : Any = SYMBOLS[numerals[index]] a__ : Optional[int] = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def __a ( lowerCAmelCase__ : int ): a__ : List[Any] = '''''' a__ : Optional[int] = num // 1000 numerals += m_count * "M" num %= 1000 a__ : Dict = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 a__ : List[str] = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def __a ( lowerCAmelCase__ : str = "/p089_roman.txt" ): a__ : Optional[int] = 0 with open(os.path.dirname(lowerCAmelCase__ ) + roman_numerals_filename ) as filea: a__ : Optional[Any] = filea.readlines() for line in lines: a__ : List[Any] = line.strip() a__ : Union[str, Any] = parse_roman_numerals(lowerCAmelCase__ ) a__ : List[str] = generate_roman_numerals(lowerCAmelCase__ ) savings += len(lowerCAmelCase__ ) - len(lowerCAmelCase__ ) return savings if __name__ == "__main__": print(f'{solution() = }')
688
'''simple docstring''' import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def __a ( lowerCAmelCase__ : List[Any] ): # encoder.embeddings are double copied in original FLAVA return sum(param.float().sum() if '''encoder.embeddings''' not in key else 0 for key, param in state_dict.items() ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ): a__ : Dict = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue a__ : Any = key.replace('''heads.cmd.mim_head.cls.predictions''' , '''mmm_image_head''' ) a__ : int = key.replace('''heads.cmd.mlm_head.cls.predictions''' , '''mmm_text_head''' ) a__ : Optional[Any] = key.replace('''heads.cmd.itm_head.cls''' , '''itm_head''' ) a__ : Dict = key.replace('''heads.cmd.itm_head.pooler''' , '''itm_head.pooler''' ) a__ : List[str] = key.replace('''heads.cmd.clip_head.logit_scale''' , '''flava.logit_scale''' ) a__ : List[Any] = key.replace('''heads.fairseq_mlm.cls.predictions''' , '''mlm_head''' ) a__ : str = key.replace('''heads.imagenet.mim_head.cls.predictions''' , '''mim_head''' ) a__ : List[Any] = key.replace('''mm_text_projection''' , '''flava.text_to_mm_projection''' ) a__ : List[Any] = key.replace('''mm_image_projection''' , '''flava.image_to_mm_projection''' ) a__ : str = key.replace('''image_encoder.module''' , '''flava.image_model''' ) a__ : Dict = key.replace('''text_encoder.module''' , '''flava.text_model''' ) a__ : List[Any] = key.replace('''mm_encoder.module.encoder.cls_token''' , '''flava.multimodal_model.cls_token''' ) a__ : List[str] = key.replace('''mm_encoder.module''' , '''flava.multimodal_model''' ) a__ : List[str] = key.replace('''text_projection''' , '''flava.text_projection''' ) a__ : Any = key.replace('''image_projection''' , '''flava.image_projection''' ) a__ : Any = value.float() for key, value in codebook_state_dict.items(): a__ : List[str] = value return upgrade @torch.no_grad() def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Dict=None ): if config_path is not None: a__ : Tuple = FlavaConfig.from_pretrained(lowerCAmelCase__ ) else: a__ : Optional[int] = FlavaConfig() a__ : List[Any] = FlavaForPreTraining(lowerCAmelCase__ ).eval() a__ : Optional[int] = convert_dalle_checkpoint(lowerCAmelCase__ , lowerCAmelCase__ , save_checkpoint=lowerCAmelCase__ ) if os.path.exists(lowerCAmelCase__ ): a__ : List[str] = torch.load(lowerCAmelCase__ , map_location='''cpu''' ) else: a__ : Dict = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' ) a__ : List[Any] = upgrade_state_dict(lowerCAmelCase__ , lowerCAmelCase__ ) hf_model.load_state_dict(lowerCAmelCase__ ) a__ : Any = hf_model.state_dict() a__ : Optional[Any] = count_parameters(lowerCAmelCase__ ) a__ : int = count_parameters(lowerCAmelCase__ ) + count_parameters(lowerCAmelCase__ ) assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) hf_model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
688
1
'''simple docstring''' import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('0.12.2'): raise Exception('requires fairseq >= 0.12.2') if version.parse(fairseq.__version__) > version.parse('2'): raise Exception('requires fairseq < v2') logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = 'Hello, World!' __SCREAMING_SNAKE_CASE = 'en_XX' def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : str , lowerCAmelCase__ : bool ): a__ : Union[str, Any] = Path('''data_bin''' ) a__ : int = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(lowerCAmelCase__ ).parent ) , checkpoint_file=Path(lowerCAmelCase__ ).name , _name='''xmod_base''' , arch='''xmod_base''' , task='''multilingual_masked_lm''' , data_name_or_path=str(lowerCAmelCase__ ) , bpe='''sentencepiece''' , sentencepiece_model=str(Path(lowerCAmelCase__ ).parent / '''sentencepiece.bpe.model''' ) , src_dict=str(data_dir / '''dict.txt''' ) , ) xmod.eval() # disable dropout print(lowerCAmelCase__ ) a__ : Dict = xmod.model.encoder.sentence_encoder a__ : Tuple = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1E-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , '''bottleneck''' , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: a__ : Optional[Any] = xmod.model.classification_heads['''mnli'''].out_proj.weight.shape[0] print('''Our X-MOD config:''' , lowerCAmelCase__ ) a__ : str = XmodForSequenceClassification(lowerCAmelCase__ ) if classification_head else XmodForMaskedLM(lowerCAmelCase__ ) model.eval() # Now let's copy all the weights. # Embeddings a__ : str = xmod_sent_encoder.embed_tokens.weight a__ : Any = xmod_sent_encoder.embed_positions.weight a__ : Any = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. a__ : Union[str, Any] = xmod_sent_encoder.layernorm_embedding.weight a__ : Any = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer a__ : List[str] = model.roberta.encoder.layer[i] a__ : Optional[int] = xmod_sent_encoder.layers[i] # self attention a__ : Tuple = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError('''Dimensions of self-attention weights do not match.''' ) a__ : str = xmod_layer.self_attn.q_proj.weight a__ : Any = xmod_layer.self_attn.q_proj.bias a__ : List[str] = xmod_layer.self_attn.k_proj.weight a__ : Dict = xmod_layer.self_attn.k_proj.bias a__ : Union[str, Any] = xmod_layer.self_attn.v_proj.weight a__ : List[str] = xmod_layer.self_attn.v_proj.bias # self-attention output a__ : int = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError('''Dimensions of self-attention output weights do not match.''' ) a__ : Union[str, Any] = xmod_layer.self_attn.out_proj.weight a__ : Optional[int] = xmod_layer.self_attn.out_proj.bias a__ : Optional[int] = xmod_layer.self_attn_layer_norm.weight a__ : str = xmod_layer.self_attn_layer_norm.bias # intermediate a__ : Dict = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('''Dimensions of intermediate weights do not match.''' ) a__ : List[str] = xmod_layer.fca.weight a__ : Union[str, Any] = xmod_layer.fca.bias # output a__ : Optional[Any] = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('''Dimensions of feed-forward weights do not match.''' ) a__ : Dict = xmod_layer.fca.weight a__ : Union[str, Any] = xmod_layer.fca.bias a__ : Optional[int] = xmod_layer.final_layer_norm.weight a__ : Optional[int] = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: a__ : Optional[int] = xmod_layer.adapter_layer_norm.weight a__ : str = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError('''Lists of language adapters do not match.''' ) for lang_code, adapter in xmod_layer.adapter_modules.items(): a__ : Optional[Any] = bert_output.adapter_modules[lang_code] a__ : Optional[Any] = xmod_layer.adapter_modules[lang_code] a__ : Optional[Any] = from_adapter.fca.weight a__ : Any = from_adapter.fca.bias a__ : Dict = from_adapter.fca.weight a__ : int = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: a__ : Optional[int] = xmod_sent_encoder.layer_norm.weight a__ : Dict = xmod_sent_encoder.layer_norm.bias if classification_head: a__ : int = xmod.model.classification_heads['''mnli'''].dense.weight a__ : Tuple = xmod.model.classification_heads['''mnli'''].dense.bias a__ : Union[str, Any] = xmod.model.classification_heads['''mnli'''].out_proj.weight a__ : Dict = xmod.model.classification_heads['''mnli'''].out_proj.bias else: # LM Head a__ : Union[str, Any] = xmod.model.encoder.lm_head.dense.weight a__ : Dict = xmod.model.encoder.lm_head.dense.bias a__ : Union[str, Any] = xmod.model.encoder.lm_head.layer_norm.weight a__ : Union[str, Any] = xmod.model.encoder.lm_head.layer_norm.bias a__ : Optional[Any] = xmod.model.encoder.lm_head.weight a__ : List[Any] = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. a__ : Optional[Any] = xmod.encode(lowerCAmelCase__ ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(lowerCAmelCase__ ) a__ : Optional[int] = model(lowerCAmelCase__ )[0] if classification_head: a__ : Union[str, Any] = xmod.model.classification_heads['''mnli'''](xmod.extract_features(lowerCAmelCase__ ) ) else: a__ : Dict = xmod.model(lowerCAmelCase__ , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) a__ : Union[str, Any] = torch.max(torch.abs(our_output - their_output ) ).item() print(F'max_absolute_diff = {max_absolute_diff}' ) # ~ 1e-7 a__ : str = torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ) print('''Do both models output the same tensors?''' , '''🔥''' if success else '''💩''' ) if not success: raise Exception('''Something went wRoNg''' ) Path(lowerCAmelCase__ ).mkdir(parents=lowerCAmelCase__ , exist_ok=lowerCAmelCase__ ) print(F'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xmod_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.' ) parser.add_argument( '--classification_head', action='store_true', help='Whether to convert a final classification head.' ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
688
'''simple docstring''' import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node __SCREAMING_SNAKE_CASE = 4 __SCREAMING_SNAKE_CASE = 3 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" pass def __a ( lowerCAmelCase__ : List[str] ): for shard in shards: for i in range(lowerCAmelCase__ ): yield {"i": i, "shard": shard} def __a ( ): a__ : str = int(os.environ['''RANK'''] ) a__ : int = int(os.environ['''WORLD_SIZE'''] ) a__ : str = ArgumentParser() parser.add_argument('''--streaming''' , type=lowerCAmelCase__ ) parser.add_argument('''--local_rank''' , type=lowerCAmelCase__ ) parser.add_argument('''--num_workers''' , type=lowerCAmelCase__ , default=0 ) a__ : int = parser.parse_args() a__ : List[str] = args.streaming a__ : Dict = args.num_workers a__ : Dict = {'''shards''': [F'shard_{shard_idx}' for shard_idx in range(lowerCAmelCase__ )]} a__ : Tuple = IterableDataset.from_generator(lowerCAmelCase__ , gen_kwargs=lowerCAmelCase__ ) if not streaming: a__ : str = Dataset.from_list(list(lowerCAmelCase__ ) ) a__ : Optional[int] = split_dataset_by_node(lowerCAmelCase__ , rank=lowerCAmelCase__ , world_size=lowerCAmelCase__ ) a__ : Dict = torch.utils.data.DataLoader(lowerCAmelCase__ , num_workers=lowerCAmelCase__ ) a__ : str = NUM_SHARDS * NUM_ITEMS_PER_SHARD a__ : Dict = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) a__ : str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'local_size {local_size} != expected_local_size {expected_local_size}' ) if __name__ == "__main__": main()
688
1
'''simple docstring''' from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_tf_available(): import tensorflow as tf from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) @add_end_docstrings(lowerCAmelCase_ ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : List[str] , *A__ : Any , **A__ : Optional[int] ) -> List[str]: '''simple docstring''' super().__init__(*A__ , **A__ ) requires_backends(self , '''vision''' ) self.check_model_type( TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING if self.framework == '''tf''' else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING ) def __lowerCAmelCase ( self : int , A__ : Optional[Any]=None ) -> List[str]: '''simple docstring''' a__ : Optional[int] = {} if top_k is not None: a__ : Any = top_k return {}, {}, postprocess_params def __call__( self : List[str] , A__ : Union[str, List[str], "Image.Image", List["Image.Image"]] , **A__ : Optional[int] ) -> int: '''simple docstring''' return super().__call__(A__ , **A__ ) def __lowerCAmelCase ( self : List[Any] , A__ : int ) -> Optional[Any]: '''simple docstring''' a__ : List[Any] = load_image(A__ ) a__ : Optional[int] = self.image_processor(images=A__ , return_tensors=self.framework ) return model_inputs def __lowerCAmelCase ( self : List[str] , A__ : Optional[Any] ) -> Tuple: '''simple docstring''' a__ : List[Any] = self.model(**A__ ) return model_outputs def __lowerCAmelCase ( self : Union[str, Any] , A__ : List[str] , A__ : Optional[int]=5 ) -> Union[str, Any]: '''simple docstring''' if top_k > self.model.config.num_labels: a__ : Any = self.model.config.num_labels if self.framework == "pt": a__ : Dict = model_outputs.logits.softmax(-1 )[0] a__ , a__ : Optional[Any] = probs.topk(A__ ) elif self.framework == "tf": a__ : Optional[Any] = stable_softmax(model_outputs.logits , axis=-1 )[0] a__ : Any = tf.math.top_k(A__ , k=A__ ) a__ , a__ : Union[str, Any] = topk.values.numpy(), topk.indices.numpy() else: raise ValueError(F'Unsupported framework: {self.framework}' ) a__ : str = scores.tolist() a__ : Any = ids.tolist() return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(A__ , A__ )]
688
'''simple docstring''' # This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests __SCREAMING_SNAKE_CASE = open # noqa: we just need to have a builtin inside this module to test it properly
688
1
'''simple docstring''' import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'b0': efficientnet.EfficientNetBa, 'b1': efficientnet.EfficientNetBa, 'b2': efficientnet.EfficientNetBa, 'b3': efficientnet.EfficientNetBa, 'b4': efficientnet.EfficientNetBa, 'b5': efficientnet.EfficientNetBa, 'b6': efficientnet.EfficientNetBa, 'b7': efficientnet.EfficientNetBa, } __SCREAMING_SNAKE_CASE = { 'b0': { 'hidden_dim': 1_2_8_0, 'width_coef': 1.0, 'depth_coef': 1.0, 'image_size': 2_2_4, 'dropout_rate': 0.2, 'dw_padding': [], }, 'b1': { 'hidden_dim': 1_2_8_0, 'width_coef': 1.0, 'depth_coef': 1.1, 'image_size': 2_4_0, 'dropout_rate': 0.2, 'dw_padding': [1_6], }, 'b2': { 'hidden_dim': 1_4_0_8, 'width_coef': 1.1, 'depth_coef': 1.2, 'image_size': 2_6_0, 'dropout_rate': 0.3, 'dw_padding': [5, 8, 1_6], }, 'b3': { 'hidden_dim': 1_5_3_6, 'width_coef': 1.2, 'depth_coef': 1.4, 'image_size': 3_0_0, 'dropout_rate': 0.3, 'dw_padding': [5, 1_8], }, 'b4': { 'hidden_dim': 1_7_9_2, 'width_coef': 1.4, 'depth_coef': 1.8, 'image_size': 3_8_0, 'dropout_rate': 0.4, 'dw_padding': [6], }, 'b5': { 'hidden_dim': 2_0_4_8, 'width_coef': 1.6, 'depth_coef': 2.2, 'image_size': 4_5_6, 'dropout_rate': 0.4, 'dw_padding': [1_3, 2_7], }, 'b6': { 'hidden_dim': 2_3_0_4, 'width_coef': 1.8, 'depth_coef': 2.6, 'image_size': 5_2_8, 'dropout_rate': 0.5, 'dw_padding': [3_1], }, 'b7': { 'hidden_dim': 2_5_6_0, 'width_coef': 2.0, 'depth_coef': 3.1, 'image_size': 6_0_0, 'dropout_rate': 0.5, 'dw_padding': [1_8], }, } def __a ( lowerCAmelCase__ : Any ): a__ : List[Any] = EfficientNetConfig() a__ : List[Any] = CONFIG_MAP[model_name]['''hidden_dim'''] a__ : List[str] = CONFIG_MAP[model_name]['''width_coef'''] a__ : Optional[Any] = CONFIG_MAP[model_name]['''depth_coef'''] a__ : Optional[int] = CONFIG_MAP[model_name]['''image_size'''] a__ : Tuple = CONFIG_MAP[model_name]['''dropout_rate'''] a__ : str = CONFIG_MAP[model_name]['''dw_padding'''] a__ : Dict = '''huggingface/label-files''' a__ : List[Any] = '''imagenet-1k-id2label.json''' a__ : Optional[int] = 1000 a__ : Optional[Any] = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type='''dataset''' ) , '''r''' ) ) a__ : Dict = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} a__ : str = idalabel a__ : List[Any] = {v: k for k, v in idalabel.items()} return config def __a ( ): a__ : Tuple = '''http://images.cocodataset.org/val2017/000000039769.jpg''' a__ : str = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) return im def __a ( lowerCAmelCase__ : List[str] ): a__ : str = CONFIG_MAP[model_name]['''image_size'''] a__ : List[Any] = EfficientNetImageProcessor( size={'''height''': size, '''width''': size} , image_mean=[0.485, 0.456, 0.406] , image_std=[0.47853944, 0.4732864, 0.47434163] , do_center_crop=lowerCAmelCase__ , ) return preprocessor def __a ( lowerCAmelCase__ : int ): a__ : Optional[Any] = [v.split('''_''' )[0].split('''block''' )[1] for v in original_param_names if v.startswith('''block''' )] a__ : Dict = sorted(set(lowerCAmelCase__ ) ) a__ : int = len(lowerCAmelCase__ ) a__ : Union[str, Any] = {b: str(lowerCAmelCase__ ) for b, i in zip(lowerCAmelCase__ , range(lowerCAmelCase__ ) )} a__ : str = [] rename_keys.append(('''stem_conv/kernel:0''', '''embeddings.convolution.weight''') ) rename_keys.append(('''stem_bn/gamma:0''', '''embeddings.batchnorm.weight''') ) rename_keys.append(('''stem_bn/beta:0''', '''embeddings.batchnorm.bias''') ) rename_keys.append(('''stem_bn/moving_mean:0''', '''embeddings.batchnorm.running_mean''') ) rename_keys.append(('''stem_bn/moving_variance:0''', '''embeddings.batchnorm.running_var''') ) for b in block_names: a__ : Union[str, Any] = block_name_mapping[b] rename_keys.append((F'block{b}_expand_conv/kernel:0', F'encoder.blocks.{hf_b}.expansion.expand_conv.weight') ) rename_keys.append((F'block{b}_expand_bn/gamma:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.weight') ) rename_keys.append((F'block{b}_expand_bn/beta:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.bias') ) rename_keys.append( (F'block{b}_expand_bn/moving_mean:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.running_mean') ) rename_keys.append( (F'block{b}_expand_bn/moving_variance:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.running_var') ) rename_keys.append( (F'block{b}_dwconv/depthwise_kernel:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight') ) rename_keys.append((F'block{b}_bn/gamma:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight') ) rename_keys.append((F'block{b}_bn/beta:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias') ) rename_keys.append( (F'block{b}_bn/moving_mean:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean') ) rename_keys.append( (F'block{b}_bn/moving_variance:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var') ) rename_keys.append((F'block{b}_se_reduce/kernel:0', F'encoder.blocks.{hf_b}.squeeze_excite.reduce.weight') ) rename_keys.append((F'block{b}_se_reduce/bias:0', F'encoder.blocks.{hf_b}.squeeze_excite.reduce.bias') ) rename_keys.append((F'block{b}_se_expand/kernel:0', F'encoder.blocks.{hf_b}.squeeze_excite.expand.weight') ) rename_keys.append((F'block{b}_se_expand/bias:0', F'encoder.blocks.{hf_b}.squeeze_excite.expand.bias') ) rename_keys.append( (F'block{b}_project_conv/kernel:0', F'encoder.blocks.{hf_b}.projection.project_conv.weight') ) rename_keys.append((F'block{b}_project_bn/gamma:0', F'encoder.blocks.{hf_b}.projection.project_bn.weight') ) rename_keys.append((F'block{b}_project_bn/beta:0', F'encoder.blocks.{hf_b}.projection.project_bn.bias') ) rename_keys.append( (F'block{b}_project_bn/moving_mean:0', F'encoder.blocks.{hf_b}.projection.project_bn.running_mean') ) rename_keys.append( (F'block{b}_project_bn/moving_variance:0', F'encoder.blocks.{hf_b}.projection.project_bn.running_var') ) rename_keys.append(('''top_conv/kernel:0''', '''encoder.top_conv.weight''') ) rename_keys.append(('''top_bn/gamma:0''', '''encoder.top_bn.weight''') ) rename_keys.append(('''top_bn/beta:0''', '''encoder.top_bn.bias''') ) rename_keys.append(('''top_bn/moving_mean:0''', '''encoder.top_bn.running_mean''') ) rename_keys.append(('''top_bn/moving_variance:0''', '''encoder.top_bn.running_var''') ) a__ : Optional[int] = {} for item in rename_keys: if item[0] in original_param_names: a__ : List[Any] = '''efficientnet.''' + item[1] a__ : Optional[Any] = '''classifier.weight''' a__ : Union[str, Any] = '''classifier.bias''' return key_mapping def __a ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Optional[int] ): for key, value in tf_params.items(): if "normalization" in key: continue a__ : Tuple = key_mapping[key] if "_conv" in key and "kernel" in key: a__ : List[Any] = torch.from_numpy(lowerCAmelCase__ ).permute(3 , 2 , 0 , 1 ) elif "depthwise_kernel" in key: a__ : Optional[Any] = torch.from_numpy(lowerCAmelCase__ ).permute(2 , 3 , 0 , 1 ) elif "kernel" in key: a__ : Any = torch.from_numpy(np.transpose(lowerCAmelCase__ ) ) else: a__ : str = torch.from_numpy(lowerCAmelCase__ ) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(lowerCAmelCase__ ) @torch.no_grad() def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Union[str, Any] ): a__ : List[str] = model_classes[model_name]( include_top=lowerCAmelCase__ , weights='''imagenet''' , input_tensor=lowerCAmelCase__ , input_shape=lowerCAmelCase__ , pooling=lowerCAmelCase__ , classes=1000 , classifier_activation='''softmax''' , ) a__ : Optional[Any] = original_model.trainable_variables a__ : str = original_model.non_trainable_variables a__ : List[Any] = {param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: a__ : List[Any] = param.numpy() a__ : int = list(tf_params.keys() ) # Load HuggingFace model a__ : str = get_efficientnet_config(lowerCAmelCase__ ) a__ : Optional[int] = EfficientNetForImageClassification(lowerCAmelCase__ ).eval() a__ : Optional[int] = hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print('''Converting parameters...''' ) a__ : Any = rename_keys(lowerCAmelCase__ ) replace_params(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Initialize preprocessor and preprocess input image a__ : Optional[Any] = convert_image_processor(lowerCAmelCase__ ) a__ : Optional[Any] = preprocessor(images=prepare_img() , return_tensors='''pt''' ) # HF model inference hf_model.eval() with torch.no_grad(): a__ : Optional[int] = hf_model(**lowerCAmelCase__ ) a__ : Optional[int] = outputs.logits.detach().numpy() # Original model inference a__ : Optional[int] = False a__ : Dict = CONFIG_MAP[model_name]['''image_size'''] a__ : Tuple = prepare_img().resize((image_size, image_size) , resample=PIL.Image.NEAREST ) a__ : Union[str, Any] = image.img_to_array(lowerCAmelCase__ ) a__ : Union[str, Any] = np.expand_dims(lowerCAmelCase__ , axis=0 ) a__ : Tuple = original_model.predict(lowerCAmelCase__ ) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(lowerCAmelCase__ , lowerCAmelCase__ , atol=1E-3 ), "The predicted logits are not the same." print('''Model outputs match!''' ) if save_model: # Create folder to save model if not os.path.isdir(lowerCAmelCase__ ): os.mkdir(lowerCAmelCase__ ) # Save converted model and image processor hf_model.save_pretrained(lowerCAmelCase__ ) preprocessor.save_pretrained(lowerCAmelCase__ ) if push_to_hub: # Push model and image processor to hub print(F'Pushing converted {model_name} to the hub...' ) a__ : int = F'efficientnet-{model_name}' preprocessor.push_to_hub(lowerCAmelCase__ ) hf_model.push_to_hub(lowerCAmelCase__ ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='b0', type=str, help='Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].', ) parser.add_argument( '--pytorch_dump_folder_path', default='hf_model', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--save_model', action='store_true', help='Save model to local') parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') __SCREAMING_SNAKE_CASE = parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
688
'''simple docstring''' import enum import shutil import sys __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = shutil.get_terminal_size() __SCREAMING_SNAKE_CASE = {'UP': 'A', 'DOWN': 'B', 'RIGHT': 'C', 'LEFT': 'D'} class lowerCAmelCase__ ( enum.Enum ): """simple docstring""" __UpperCamelCase = 0 __UpperCamelCase = 1 def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict="" ): sys.stdout.write(str(lowerCAmelCase__ ) + end ) sys.stdout.flush() def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int , lowerCAmelCase__ : int="" ): forceWrite(F'\u001b[{color}m{content}\u001b[0m' , lowerCAmelCase__ ) def __a ( ): forceWrite('''\r''' ) def __a ( lowerCAmelCase__ : int , lowerCAmelCase__ : str ): forceWrite(F'\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}' ) def __a ( ): forceWrite(''' ''' * TERMINAL_WIDTH ) reset_cursor() def __a ( ): reset_cursor() forceWrite('''-''' * TERMINAL_WIDTH )
688
1
'''simple docstring''' import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : List[str] , A__ : Optional[Any] , A__ : List[str]=1_3 , A__ : Union[str, Any]=7 , A__ : Dict=True , A__ : Optional[int]=True , A__ : List[Any]=False , A__ : List[str]=True , A__ : List[Any]=9_9 , A__ : List[str]=3_2 , A__ : Union[str, Any]=5 , A__ : str=4 , A__ : Any=6_4 , A__ : Tuple="gelu" , A__ : Optional[Any]=0.1 , A__ : Dict=0.1 , A__ : Dict=5_1_2 , A__ : Dict=1_6 , A__ : Optional[Any]=2 , A__ : List[str]=0.02 , A__ : Optional[int]=3 , A__ : int=4 , A__ : Optional[Any]=None , A__ : List[Any]=2 , A__ : Union[str, Any]=2 , A__ : str=2 , A__ : str=2 , A__ : Tuple=4 , A__ : List[str]=1 , ) -> Any: '''simple docstring''' a__ : str = parent a__ : Optional[Any] = batch_size a__ : List[str] = seq_length a__ : int = is_training a__ : List[Any] = use_input_mask a__ : Optional[Any] = use_token_type_ids a__ : Any = use_labels a__ : int = vocab_size a__ : Optional[int] = hidden_size a__ : Any = num_hidden_layers a__ : Union[str, Any] = num_attention_heads a__ : List[str] = intermediate_size a__ : str = hidden_act a__ : int = hidden_dropout_prob a__ : str = attention_probs_dropout_prob a__ : str = max_position_embeddings a__ : Any = type_vocab_size a__ : List[Any] = type_sequence_label_size a__ : Dict = initializer_range a__ : List[Any] = num_labels a__ : Tuple = num_choices a__ : List[str] = scope a__ : int = q_groups a__ : str = k_groups a__ : str = v_groups a__ : Any = post_attention_groups a__ : List[str] = intermediate_groups a__ : Any = output_groups def __lowerCAmelCase ( self : Union[str, Any] ) -> List[Any]: '''simple docstring''' a__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : str = None if self.use_input_mask: a__ : Dict = random_attention_mask([self.batch_size, self.seq_length] ) a__ : Any = None a__ : str = None a__ : List[str] = None if self.use_labels: a__ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a__ : Dict = ids_tensor([self.batch_size] , self.num_choices ) a__ : str = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowerCAmelCase ( self : List[Any] ) -> int: '''simple docstring''' return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Union[str, Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] , A__ : Optional[Any] ) -> int: '''simple docstring''' a__ : List[Any] = SqueezeBertModel(config=A__ ) model.to(A__ ) model.eval() a__ : Tuple = model(A__ , A__ ) a__ : Optional[Any] = model(A__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowerCAmelCase ( self : Tuple , A__ : List[str] , A__ : Optional[Any] , A__ : Dict , A__ : Optional[Any] , A__ : str , A__ : str ) -> Union[str, Any]: '''simple docstring''' a__ : str = SqueezeBertForMaskedLM(config=A__ ) model.to(A__ ) model.eval() a__ : Tuple = model(A__ , attention_mask=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowerCAmelCase ( self : List[str] , A__ : Any , A__ : Optional[Any] , A__ : Any , A__ : int , A__ : Tuple , A__ : Any ) -> Tuple: '''simple docstring''' a__ : List[str] = SqueezeBertForQuestionAnswering(config=A__ ) model.to(A__ ) model.eval() a__ : int = model( A__ , attention_mask=A__ , start_positions=A__ , end_positions=A__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , A__ : Dict , A__ : Optional[int] , A__ : Optional[int] , A__ : str , A__ : int ) -> Union[str, Any]: '''simple docstring''' a__ : str = self.num_labels a__ : int = SqueezeBertForSequenceClassification(A__ ) model.to(A__ ) model.eval() a__ : str = model(A__ , attention_mask=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowerCAmelCase ( self : List[Any] , A__ : Optional[Any] , A__ : Tuple , A__ : Any , A__ : Optional[int] , A__ : int , A__ : List[str] ) -> Tuple: '''simple docstring''' a__ : Tuple = self.num_labels a__ : List[str] = SqueezeBertForTokenClassification(config=A__ ) model.to(A__ ) model.eval() a__ : int = model(A__ , attention_mask=A__ , labels=A__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , A__ : Dict , A__ : Any , A__ : Dict , A__ : Any , A__ : Dict ) -> Optional[int]: '''simple docstring''' a__ : Union[str, Any] = self.num_choices a__ : List[Any] = SqueezeBertForMultipleChoice(config=A__ ) model.to(A__ ) model.eval() a__ : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : List[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a__ : Union[str, Any] = model( A__ , attention_mask=A__ , labels=A__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowerCAmelCase ( self : Tuple ) -> str: '''simple docstring''' a__ : List[Any] = self.prepare_config_and_inputs() ((a__) , (a__) , (a__) , (a__) , (a__) , (a__)) : List[Any] = config_and_inputs a__ : Optional[Any] = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCamelCase = ( { "feature-extraction": SqueezeBertModel, "fill-mask": SqueezeBertForMaskedLM, "question-answering": SqueezeBertForQuestionAnswering, "text-classification": SqueezeBertForSequenceClassification, "token-classification": SqueezeBertForTokenClassification, "zero-shot": SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = False def __lowerCAmelCase ( self : str ) -> Tuple: '''simple docstring''' a__ : int = SqueezeBertModelTester(self ) a__ : Tuple = ConfigTester(self , config_class=A__ , dim=3_7 ) def __lowerCAmelCase ( self : Dict ) -> Tuple: '''simple docstring''' self.config_tester.run_common_tests() def __lowerCAmelCase ( self : Tuple ) -> Any: '''simple docstring''' a__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*A__ ) def __lowerCAmelCase ( self : Any ) -> Union[str, Any]: '''simple docstring''' a__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*A__ ) def __lowerCAmelCase ( self : Any ) -> Union[str, Any]: '''simple docstring''' a__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*A__ ) def __lowerCAmelCase ( self : Any ) -> str: '''simple docstring''' a__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*A__ ) def __lowerCAmelCase ( self : int ) -> Any: '''simple docstring''' a__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*A__ ) @slow def __lowerCAmelCase ( self : Union[str, Any] ) -> Optional[int]: '''simple docstring''' for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : List[str] = SqueezeBertModel.from_pretrained(A__ ) self.assertIsNotNone(A__ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" @slow def __lowerCAmelCase ( self : Optional[int] ) -> Any: '''simple docstring''' a__ : str = SqueezeBertForSequenceClassification.from_pretrained('''squeezebert/squeezebert-mnli''' ) a__ : Dict = torch.tensor([[1, 2_9_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 1_3, 1_5_8_8, 2]] ) a__ : int = model(A__ )[0] a__ : Optional[int] = torch.Size((1, 3) ) self.assertEqual(output.shape , A__ ) a__ : Optional[int] = torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(A__ , A__ , atol=1E-4 ) )
688
'''simple docstring''' import inspect import unittest class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Dict ) -> Dict: '''simple docstring''' try: import diffusers # noqa: F401 except ImportError: assert False def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' import diffusers from diffusers.dependency_versions_table import deps a__ : Optional[int] = inspect.getmembers(A__ , inspect.isclass ) for cls_name, cls_module in all_classes: if "dummy_" in cls_module.__module__: for backend in cls_module._backends: if backend == "k_diffusion": a__ : int = '''k-diffusion''' elif backend == "invisible_watermark": a__ : int = '''invisible-watermark''' assert backend in deps, F'{backend} is not in the deps table!'
688
1
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : List[Any] ): assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] ): a__ : Tuple = tmp_path / '''cache''' a__ : str = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a__ : List[Any] = JsonDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read() _check_json_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) @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 __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[int] ): a__ : str = tmp_path / '''cache''' a__ : Optional[int] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} a__ : Tuple = features.copy() if features else default_expected_features a__ : Union[str, Any] = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) a__ : Any = JsonDatasetReader(lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_json_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize( '''features''' , [ None, {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''}, ] , ) def __a ( lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : str , lowerCAmelCase__ : int ): a__ : Dict = tmp_path / '''cache''' a__ : str = {'''col_3''': '''float64''', '''col_1''': '''string''', '''col_2''': '''int64'''} a__ : str = features.copy() if features else default_expected_features a__ : Tuple = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) a__ : int = JsonDatasetReader(lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def __a ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[str] ): # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} a__ : Dict = {'''col_2''': '''int64''', '''col_3''': '''float64''', '''col_1''': '''string'''} a__ : Optional[Any] = features.copy() a__ : str = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) a__ : int = tmp_path / '''cache''' a__ : Union[str, Any] = JsonDatasetReader(lowerCAmelCase__ , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[int] ): a__ : Optional[Any] = tmp_path / '''cache''' a__ : int = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} a__ : Optional[int] = JsonDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , split=lowerCAmelCase__ ).read() _check_json_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('''path_type''' , [str, list] ) def __a ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Dict ): if issubclass(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Optional[int] = jsonl_path elif issubclass(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Tuple = [jsonl_path] a__ : Optional[Any] = tmp_path / '''cache''' a__ : Optional[Any] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} a__ : Optional[int] = JsonDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_json_dataset(lowerCAmelCase__ , lowerCAmelCase__ ) def __a ( lowerCAmelCase__ : Any , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : int=("train",) ): assert isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) for split in splits: a__ : Dict = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('''keep_in_memory''' , [False, True] ) def __a ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Any , lowerCAmelCase__ : List[Any] ): a__ : Optional[int] = tmp_path / '''cache''' a__ : List[str] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a__ : int = JsonDatasetReader({'''train''': jsonl_path} , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ ).read() _check_json_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ ) @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 __a ( lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Union[str, Any] ): a__ : int = tmp_path / '''cache''' a__ : Dict = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} a__ : Optional[Any] = features.copy() if features else default_expected_features a__ : Optional[int] = ( Features({feature: Value(lowerCAmelCase__ ) for feature, dtype in features.items()} ) if features is not None else None ) a__ : str = JsonDatasetReader({'''train''': jsonl_path} , features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_json_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ ) @pytest.mark.parametrize('''split''' , [None, NamedSplit('''train''' ), '''train''', '''test'''] ) def __a ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : List[str] ): if split: a__ : int = {split: jsonl_path} else: a__ : Optional[int] = '''train''' a__ : List[Any] = {'''train''': jsonl_path, '''test''': jsonl_path} a__ : Optional[Any] = tmp_path / '''cache''' a__ : List[str] = {'''col_1''': '''string''', '''col_2''': '''int64''', '''col_3''': '''float64'''} a__ : Any = JsonDatasetReader(lowerCAmelCase__ , cache_dir=lowerCAmelCase__ ).read() _check_json_datasetdict(lowerCAmelCase__ , lowerCAmelCase__ , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def __a ( lowerCAmelCase__ : Optional[Any] ): return json.load(lowerCAmelCase__ ) def __a ( lowerCAmelCase__ : Tuple ): return [json.loads(lowerCAmelCase__ ) for line in buffer] class lowerCAmelCase__ : """simple docstring""" @pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] ) def __lowerCAmelCase ( self : str , A__ : Optional[Any] , A__ : Optional[int] , A__ : Tuple ) -> List[Any]: '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(A__ , A__ , lines=A__ ).write() buffer.seek(0 ) a__ : int = load_json_function(A__ ) assert isinstance(A__ , A__ ) assert isinstance(exported_content[0] , A__ ) assert len(A__ ) == 1_0 @pytest.mark.parametrize( '''orient, container, keys, len_at''' , [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ] , ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Dict , A__ : Union[str, Any] , A__ : List[str] , A__ : int , A__ : Dict ) -> str: '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(A__ , A__ , lines=A__ , orient=A__ ).write() buffer.seek(0 ) a__ : Union[str, Any] = load_json(A__ ) assert isinstance(A__ , A__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(A__ , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 1_0 else: assert len(A__ ) == 1_0 @pytest.mark.parametrize('''lines, load_json_function''' , [(True, load_json_lines), (False, load_json)] ) def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Any , A__ : List[str] ) -> Optional[Any]: '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(A__ , A__ , lines=A__ , num_proc=2 ).write() buffer.seek(0 ) a__ : Dict = load_json_function(A__ ) assert isinstance(A__ , A__ ) assert isinstance(exported_content[0] , A__ ) assert len(A__ ) == 1_0 @pytest.mark.parametrize( '''orient, container, keys, len_at''' , [ ('''records''', list, {'''tokens''', '''labels''', '''answers''', '''id'''}, None), ('''split''', dict, {'''columns''', '''data'''}, '''data'''), ('''index''', dict, set('''0123456789''' ), None), ('''columns''', dict, {'''tokens''', '''labels''', '''answers''', '''id'''}, '''tokens'''), ('''values''', list, None, None), ('''table''', dict, {'''schema''', '''data'''}, '''data'''), ] , ) def __lowerCAmelCase ( self : Optional[Any] , A__ : Tuple , A__ : Optional[Any] , A__ : Optional[int] , A__ : Optional[int] , A__ : List[str] ) -> Any: '''simple docstring''' with io.BytesIO() as buffer: JsonDatasetWriter(A__ , A__ , lines=A__ , orient=A__ , num_proc=2 ).write() buffer.seek(0 ) a__ : Union[str, Any] = load_json(A__ ) assert isinstance(A__ , A__ ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(A__ , '''keys''' ) and not hasattr(exported_content[0] , '''keys''' ) if len_at: assert len(exported_content[len_at] ) == 1_0 else: assert len(A__ ) == 1_0 def __lowerCAmelCase ( self : Dict , A__ : int ) -> List[str]: '''simple docstring''' with pytest.raises(A__ ): with io.BytesIO() as buffer: JsonDatasetWriter(A__ , A__ , num_proc=0 ) @pytest.mark.parametrize('''compression, extension''' , [('''gzip''', '''gz'''), ('''bz2''', '''bz2'''), ('''xz''', '''xz''')] ) def __lowerCAmelCase ( self : Optional[Any] , A__ : int , A__ : List[str] , A__ : str , A__ : int , A__ : Tuple ) -> Tuple: '''simple docstring''' a__ : Optional[int] = tmp_path_factory.mktemp('''data''' ) / F'test.json.{extension}' a__ : List[str] = str(shared_datadir / F'test_file.json.{extension}' ) JsonDatasetWriter(A__ , A__ , compression=A__ ).write() with fsspec.open(A__ , '''rb''' , compression='''infer''' ) as f: a__ : List[Any] = f.read() with fsspec.open(A__ , '''rb''' , compression='''infer''' ) as f: a__ : List[Any] = f.read() assert exported_content == original_content
688
'''simple docstring''' import inspect from typing import List, Optional, Tuple, Union import numpy as np import PIL import torch import torch.utils.checkpoint from ...models import UNetaDModel, VQModel from ...schedulers import ( DDIMScheduler, DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, ) from ...utils import PIL_INTERPOLATION, randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput def __a ( lowerCAmelCase__ : Dict ): a__ , a__ : int = image.size a__ , a__ : List[str] = (x - x % 32 for x in (w, h)) # resize to integer multiple of 32 a__ : Tuple = image.resize((w, h) , resample=PIL_INTERPOLATION['''lanczos'''] ) a__ : List[Any] = np.array(lowerCAmelCase__ ).astype(np.floataa ) / 255.0 a__ : Any = image[None].transpose(0 , 3 , 1 , 2 ) a__ : Dict = torch.from_numpy(lowerCAmelCase__ ) return 2.0 * image - 1.0 class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[Any] , A__ : VQModel , A__ : UNetaDModel , A__ : Union[ DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler, ] , ) -> str: '''simple docstring''' super().__init__() self.register_modules(vqvae=A__ , unet=A__ , scheduler=A__ ) @torch.no_grad() def __call__( self : List[str] , A__ : Union[torch.Tensor, PIL.Image.Image] = None , A__ : Optional[int] = 1 , A__ : Optional[int] = 1_0_0 , A__ : Optional[float] = 0.0 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> Union[Tuple, ImagePipelineOutput]: '''simple docstring''' if isinstance(A__ , PIL.Image.Image ): a__ : List[Any] = 1 elif isinstance(A__ , torch.Tensor ): a__ : List[str] = image.shape[0] else: raise ValueError(F'`image` has to be of type `PIL.Image.Image` or `torch.Tensor` but is {type(A__ )}' ) if isinstance(A__ , PIL.Image.Image ): a__ : Union[str, Any] = preprocess(A__ ) a__ , a__ : Dict = image.shape[-2:] # in_channels should be 6: 3 for latents, 3 for low resolution image a__ : Optional[int] = (batch_size, self.unet.config.in_channels // 2, height, width) a__ : Optional[int] = next(self.unet.parameters() ).dtype a__ : List[str] = randn_tensor(A__ , generator=A__ , device=self.device , dtype=A__ ) a__ : Any = image.to(device=self.device , dtype=A__ ) # set timesteps and move to the correct device self.scheduler.set_timesteps(A__ , device=self.device ) a__ : int = self.scheduler.timesteps # scale the initial noise by the standard deviation required by the scheduler a__ : str = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature. # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a__ : Union[str, Any] = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a__ : str = {} if accepts_eta: a__ : Dict = eta for t in self.progress_bar(A__ ): # concat latents and low resolution image in the channel dimension. a__ : str = torch.cat([latents, image] , dim=1 ) a__ : Optional[Any] = self.scheduler.scale_model_input(A__ , A__ ) # predict the noise residual a__ : Union[str, Any] = self.unet(A__ , A__ ).sample # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step(A__ , A__ , A__ , **A__ ).prev_sample # decode the image latents with the VQVAE a__ : List[Any] = self.vqvae.decode(A__ ).sample a__ : List[Any] = torch.clamp(A__ , -1.0 , 1.0 ) a__ : Optional[Any] = image / 2 + 0.5 a__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a__ : Union[str, Any] = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' from __future__ import annotations import math def __a ( lowerCAmelCase__ : int ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowerCAmelCase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True __SCREAMING_SNAKE_CASE = [num for num in range(3, 1_0_0_0_0_1, 2) if not is_prime(num)] def __a ( lowerCAmelCase__ : int ): if not isinstance(lowerCAmelCase__ , lowerCAmelCase__ ): raise ValueError('''n must be an integer''' ) if n <= 0: raise ValueError('''n must be >= 0''' ) a__ : Dict = [] for num in range(len(lowerCAmelCase__ ) ): a__ : Any = 0 while 2 * i * i <= odd_composites[num]: a__ : Optional[Any] = odd_composites[num] - 2 * i * i if is_prime(lowerCAmelCase__ ): break i += 1 else: list_nums.append(odd_composites[num] ) if len(lowerCAmelCase__ ) == n: return list_nums return [] def __a ( ): return compute_nums(1 )[0] if __name__ == "__main__": print(f'{solution() = }')
688
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) # pylint: disable=invalid-name __SCREAMING_SNAKE_CASE = '\n Examples:\n ```py\n >>> import torch\n >>> import numpy as np\n\n >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n >>> from transformers import pipeline\n >>> from diffusers.utils import load_image\n\n\n >>> def make_hint(image, depth_estimator):\n ... image = depth_estimator(image)["depth"]\n ... image = np.array(image)\n ... image = image[:, :, None]\n ... image = np.concatenate([image, image, image], axis=2)\n ... detected_map = torch.from_numpy(image).float() / 255.0\n ... hint = detected_map.permute(2, 0, 1)\n ... return hint\n\n\n >>> depth_estimator = pipeline("depth-estimation")\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n ... )\n >>> pipe_prior = pipe_prior.to("cuda")\n\n >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n ... "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16\n ... )\n >>> pipe = pipe.to("cuda")\n\n\n >>> img = load_image(\n ... "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n ... "/kandinsky/cat.png"\n ... ).resize((768, 768))\n\n >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")\n\n >>> prompt = "A robot, 4k photo"\n >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"\n\n >>> generator = torch.Generator(device="cuda").manual_seed(43)\n\n >>> image_emb, zero_image_emb = pipe_prior(\n ... prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n ... ).to_tuple()\n\n >>> images = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... hint=hint,\n ... num_inference_steps=50,\n ... generator=generator,\n ... height=768,\n ... width=768,\n ... ).images\n\n >>> images[0].save("robot_cat.png")\n ```\n' def __a ( lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Any , lowerCAmelCase__ : str=8 ): a__ : Tuple = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a__ : Union[str, Any] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Dict , A__ : UNetaDConditionModel , A__ : DDPMScheduler , A__ : VQModel , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules( unet=A__ , scheduler=A__ , movq=A__ , ) a__ : Union[str, Any] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def __lowerCAmelCase ( self : Optional[Any] , A__ : List[Any] , A__ : List[str] , A__ : Optional[Any] , A__ : Dict , A__ : Dict , A__ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' if latents is None: a__ : List[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__ : int = latents.to(A__ ) a__ : Tuple = latents * scheduler.init_noise_sigma return latents def __lowerCAmelCase ( self : Union[str, Any] , A__ : int=0 ) -> str: '''simple docstring''' if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('''Please install accelerate via `pip install accelerate`''' ) a__ : Union[str, Any] = torch.device(F'cuda:{gpu_id}' ) a__ : Union[str, Any] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(A__ , A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple=0 ) -> Dict: '''simple docstring''' if is_accelerate_available() and is_accelerate_version('''>=''' , '''0.17.0.dev0''' ): from accelerate import cpu_offload_with_hook else: raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.''' ) a__ : int = torch.device(F'cuda:{gpu_id}' ) if self.device.type != "cpu": self.to('''cpu''' , silence_dtype_warnings=A__ ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a__ : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: a__ , a__ : List[str] = cpu_offload_with_hook(A__ , A__ , prev_module_hook=A__ ) # We'll offload the last model manually. a__ : Dict = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def __lowerCAmelCase ( self : Union[str, Any] ) -> Any: '''simple docstring''' if not hasattr(self.unet , '''_hf_hook''' ): return self.device for module in self.unet.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 @torch.no_grad() @replace_example_docstring(A__ ) def __call__( self : Any , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : Union[torch.FloatTensor, List[torch.FloatTensor]] , A__ : torch.FloatTensor , A__ : int = 5_1_2 , A__ : int = 5_1_2 , A__ : int = 1_0_0 , A__ : float = 4.0 , A__ : int = 1 , A__ : Optional[Union[torch.Generator, List[torch.Generator]]] = None , A__ : Optional[torch.FloatTensor] = None , A__ : Optional[str] = "pil" , A__ : bool = True , ) -> str: '''simple docstring''' a__ : Optional[Any] = self._execution_device a__ : List[str] = guidance_scale > 1.0 if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : Optional[int] = torch.cat(A__ , dim=0 ) if isinstance(A__ , A__ ): a__ : int = torch.cat(A__ , dim=0 ) a__ : Union[str, Any] = image_embeds.shape[0] * num_images_per_prompt if do_classifier_free_guidance: a__ : Tuple = image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = negative_image_embeds.repeat_interleave(A__ , dim=0 ) a__ : Optional[int] = hint.repeat_interleave(A__ , dim=0 ) a__ : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) a__ : Tuple = torch.cat([hint, hint] , dim=0 ).to(dtype=self.unet.dtype , device=A__ ) self.scheduler.set_timesteps(A__ , device=A__ ) a__ : int = self.scheduler.timesteps a__ : str = self.movq.config.latent_channels a__ , a__ : Optional[int] = downscale_height_and_width(A__ , A__ , self.movq_scale_factor ) # create initial latent a__ : List[Any] = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , A__ , A__ , A__ , self.scheduler , ) for i, t in enumerate(self.progress_bar(A__ ) ): # expand the latents if we are doing classifier free guidance a__ : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a__ : List[str] = {'''image_embeds''': image_embeds, '''hint''': hint} a__ : Union[str, Any] = self.unet( sample=A__ , timestep=A__ , encoder_hidden_states=A__ , added_cond_kwargs=A__ , return_dict=A__ , )[0] if do_classifier_free_guidance: a__ , a__ : Dict = noise_pred.split(latents.shape[1] , dim=1 ) a__ , a__ : Dict = noise_pred.chunk(2 ) a__ , a__ : Optional[Any] = variance_pred.chunk(2 ) a__ : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a__ : Union[str, Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , '''variance_type''' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a__ , a__ : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a__ : Union[str, Any] = self.scheduler.step( A__ , A__ , A__ , generator=A__ , )[0] # post-processing a__ : Tuple = self.movq.decode(A__ , force_not_quantize=A__ )['''sample'''] if output_type not in ["pt", "np", "pil"]: raise ValueError(F'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}' ) if output_type in ["np", "pil"]: a__ : Union[str, Any] = image * 0.5 + 0.5 a__ : str = image.clamp(0 , 1 ) a__ : Optional[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a__ : int = self.numpy_to_pil(A__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=A__ )
688
1
'''simple docstring''' import warnings from ...utils import logging from .image_processing_poolformer import PoolFormerImageProcessor __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : Optional[int] , *A__ : List[Any] , **A__ : Optional[Any] ) -> None: '''simple docstring''' warnings.warn( '''The class PoolFormerFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use PoolFormerImageProcessor instead.''' , A__ , ) super().__init__(*A__ , **A__ )
688
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = {'vocab_file': 'vocab.txt'} __SCREAMING_SNAKE_CASE = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } __SCREAMING_SNAKE_CASE = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def __a ( lowerCAmelCase__ : Union[str, Any] ): with open(lowerCAmelCase__ , '''r''' ) as f: a__ : Optional[int] = f.read().splitlines() return [l.strip() for l in lines] class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ["input_ids", "attention_mask"] def __init__( self : List[str] , A__ : int , A__ : Union[str, Any]="<unk>" , A__ : Tuple="<cls>" , A__ : List[Any]="<pad>" , A__ : Optional[int]="<mask>" , A__ : List[Any]="<eos>" , **A__ : Optional[Any] , ) -> Optional[int]: '''simple docstring''' super().__init__(**A__ ) a__ : Union[str, Any] = load_vocab_file(A__ ) a__ : int = dict(enumerate(self.all_tokens ) ) a__ : str = {tok: ind for ind, tok in enumerate(self.all_tokens )} a__ : List[Any] = unk_token a__ : Any = cls_token a__ : Any = pad_token a__ : Any = mask_token a__ : Any = eos_token a__ : int = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def __lowerCAmelCase ( self : Any , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : Optional[Any] , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Tuple , **A__ : str ) -> List[Any]: '''simple docstring''' return text.split() def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int]=False ) -> Tuple: '''simple docstring''' return len(self._id_to_token ) def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' return {token: i for i, token in enumerate(self.all_tokens )} def __lowerCAmelCase ( self : Any , A__ : str ) -> int: '''simple docstring''' return self._token_to_id.get(A__ , self._token_to_id.get(self.unk_token ) ) def __lowerCAmelCase ( self : List[Any] , A__ : int ) -> str: '''simple docstring''' return self._id_to_token.get(A__ , self.unk_token ) def __lowerCAmelCase ( self : str , A__ : List[int] , A__ : Optional[List[int]] = None ) -> List[int]: '''simple docstring''' a__ : Tuple = [self.cls_token_id] a__ : Union[str, Any] = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('''Cannot tokenize multiple sequences when EOS token is not set!''' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def __lowerCAmelCase ( self : Tuple , A__ : List , A__ : Optional[List] = None , A__ : bool = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] a__ : Any = [1] + ([0] * len(A__ )) + [1] if token_ids_a is not None: mask += [0] * len(A__ ) + [1] return mask def __lowerCAmelCase ( self : Any , A__ : Dict , A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Union[str, Any] = os.path.join(A__ , (filename_prefix + '''-''' if filename_prefix else '''''') + '''vocab.txt''' ) with open(A__ , '''w''' ) as f: f.write('''\n'''.join(self.all_tokens ) ) return (vocab_file,) @property def __lowerCAmelCase ( self : Any ) -> int: '''simple docstring''' return self.get_vocab_size(with_added_tokens=A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Union[List[str], List[AddedToken]] , A__ : bool = False ) -> int: '''simple docstring''' return super()._add_tokens(A__ , special_tokens=A__ )
688
1
'''simple docstring''' from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def __a ( lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : bool = False ): if radian_mode: return [magnitude * cos(lowerCAmelCase__ ), magnitude * sin(lowerCAmelCase__ )] return [magnitude * cos(radians(lowerCAmelCase__ ) ), magnitude * sin(radians(lowerCAmelCase__ ) )] def __a ( lowerCAmelCase__ : NDArray[floataa] , lowerCAmelCase__ : NDArray[floataa] , lowerCAmelCase__ : float = 10**-1 ): a__ : NDArray[floataa] = cross(lowerCAmelCase__ , lowerCAmelCase__ ) a__ : float = sum(lowerCAmelCase__ ) return abs(lowerCAmelCase__ ) < eps if __name__ == "__main__": # Test to check if it works __SCREAMING_SNAKE_CASE = array( [ polar_force(718.4, 1_8_0 - 3_0), polar_force(879.54, 4_5), polar_force(1_0_0, -9_0), ] ) __SCREAMING_SNAKE_CASE = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg __SCREAMING_SNAKE_CASE = array( [ polar_force(3_0 * 9.81, 1_5), polar_force(2_1_5, 1_8_0 - 4_5), polar_force(2_6_4, 9_0 - 3_0), ] ) __SCREAMING_SNAKE_CASE = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg __SCREAMING_SNAKE_CASE = array([[0, -2_0_0_0], [0, -1_2_0_0], [0, 1_5_6_0_0], [0, -1_2_4_0_0]]) __SCREAMING_SNAKE_CASE = array([[0, 0], [6, 0], [1_0, 0], [1_2, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
688
'''simple docstring''' import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex __SCREAMING_SNAKE_CASE = logging.getLogger(__name__) class lowerCAmelCase__ : """simple docstring""" def __init__( self : str ) -> Dict: '''simple docstring''' a__ : List[str] = False def __lowerCAmelCase ( self : Tuple , A__ : Optional[int] , A__ : Optional[Any] , A__ : List[str] , A__ : Tuple ) -> Optional[int]: '''simple docstring''' if not self.initialized: a__ : Optional[Any] = RagRetriever( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : Union[str, Any] = True def __lowerCAmelCase ( self : Tuple ) -> Tuple: '''simple docstring''' self.retriever.index.init_index() def __lowerCAmelCase ( self : List[Any] , A__ : List[Any] , A__ : Optional[int] ) -> List[Any]: '''simple docstring''' a__ , a__ : Optional[Any] = self.retriever._main_retrieve(A__ , A__ ) return doc_ids, retrieved_doc_embeds class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" def __init__( self : str , A__ : Optional[int] , A__ : List[Any] , A__ : List[Any] , A__ : str , A__ : Any=None ) -> Optional[Any]: '''simple docstring''' if index is not None and index.is_initialized() and len(A__ ) > 0: raise ValueError( '''When using Ray for distributed fine-tuning, ''' '''you\'ll need to provide the paths instead, ''' '''as the dataset and the index are loaded ''' '''separately. More info in examples/rag/use_own_knowledge_dataset.py ''' ) super().__init__( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , index=A__ , init_retrieval=A__ , ) a__ : List[str] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(A__ , A__ , A__ , A__ ) for worker in self.retrieval_workers ] ) def __lowerCAmelCase ( self : Tuple ) -> Optional[int]: '''simple docstring''' logger.info('''initializing retrieval''' ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __lowerCAmelCase ( self : Optional[int] , A__ : Optional[int] , A__ : int ) -> Dict: '''simple docstring''' if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. a__ : List[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] a__ , a__ : Tuple = ray.get(random_worker.retrieve.remote(A__ , A__ ) ) else: a__ , a__ : int = self._main_retrieve(A__ , A__ ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[Any] , A__ : Any=None , **A__ : Optional[Any] ) -> Optional[int]: '''simple docstring''' return super(A__ , cls ).get_tokenizers(A__ , A__ , **A__ ) @classmethod def __lowerCAmelCase ( cls : int , A__ : Optional[int] , A__ : Union[str, Any] , A__ : Union[str, Any]=None , **A__ : Dict ) -> List[Any]: '''simple docstring''' a__ : Dict = kwargs.pop('''config''' , A__ ) or RagConfig.from_pretrained(A__ , **A__ ) a__ : Dict = RagTokenizer.from_pretrained(A__ , config=A__ ) a__ : str = rag_tokenizer.question_encoder a__ : List[str] = rag_tokenizer.generator if indexed_dataset is not None: a__ : List[Any] = '''custom''' a__ : List[Any] = CustomHFIndex(config.retrieval_vector_size , A__ ) else: a__ : Optional[Any] = cls._build_index(A__ ) return cls( A__ , question_encoder_tokenizer=A__ , generator_tokenizer=A__ , retrieval_workers=A__ , index=A__ , )
688
1
'''simple docstring''' import pprint import requests __SCREAMING_SNAKE_CASE = 'https://zenquotes.io/api' def __a ( ): return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def __a ( ): return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": __SCREAMING_SNAKE_CASE = random_quotes() pprint.pprint(response)
688
'''simple docstring''' def __a ( lowerCAmelCase__ : list , lowerCAmelCase__ : list , lowerCAmelCase__ : int ): a__ : List[str] = len(lowerCAmelCase__ ) a__ : int = [[0] * n for i in range(lowerCAmelCase__ )] for i in range(lowerCAmelCase__ ): a__ : Dict = y_points[i] for i in range(2 , lowerCAmelCase__ ): for j in range(lowerCAmelCase__ , lowerCAmelCase__ ): a__ : Any = ( (xa - x_points[j - i + 1]) * q[j][i - 1] - (xa - x_points[j]) * q[j - 1][i - 1] ) / (x_points[j] - x_points[j - i + 1]) return [q[n - 1][n - 1], q] if __name__ == "__main__": import doctest doctest.testmod()
688
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) __SCREAMING_SNAKE_CASE = {'configuration_unispeech': ['UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP', 'UniSpeechConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE = [ 'UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST', 'UniSpeechForCTC', 'UniSpeechForPreTraining', 'UniSpeechForSequenceClassification', 'UniSpeechModel', 'UniSpeechPreTrainedModel', ] if TYPE_CHECKING: from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_unispeech import ( UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST, UniSpeechForCTC, UniSpeechForPreTraining, UniSpeechForSequenceClassification, UniSpeechModel, UniSpeechPreTrainedModel, ) else: import sys __SCREAMING_SNAKE_CASE = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
688
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __SCREAMING_SNAKE_CASE = logging.get_logger(__name__) __SCREAMING_SNAKE_CASE = { 'caidas/swin2sr-classicalsr-x2-64': ( 'https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json' ), } class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = "swin2sr" __UpperCamelCase = { "hidden_size": "embed_dim", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Union[str, Any] , A__ : int=6_4 , A__ : List[Any]=1 , A__ : List[Any]=3 , A__ : Any=1_8_0 , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Optional[int]=[6, 6, 6, 6, 6, 6] , A__ : Dict=8 , A__ : Any=2.0 , A__ : Optional[int]=True , A__ : Union[str, Any]=0.0 , A__ : Union[str, Any]=0.0 , A__ : List[str]=0.1 , A__ : Any="gelu" , A__ : Tuple=False , A__ : Optional[int]=0.02 , A__ : List[Any]=1E-5 , A__ : Any=2 , A__ : Union[str, Any]=1.0 , A__ : Dict="1conv" , A__ : Optional[Any]="pixelshuffle" , **A__ : Optional[Any] , ) -> Optional[Any]: '''simple docstring''' super().__init__(**A__ ) a__ : List[str] = image_size a__ : Optional[Any] = patch_size a__ : Dict = num_channels a__ : Optional[int] = embed_dim a__ : int = depths a__ : Optional[int] = len(A__ ) a__ : Dict = num_heads a__ : List[Any] = window_size a__ : Optional[int] = mlp_ratio a__ : Optional[int] = qkv_bias a__ : Union[str, Any] = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Union[str, Any] = drop_path_rate a__ : int = hidden_act a__ : int = use_absolute_embeddings a__ : Dict = layer_norm_eps a__ : List[str] = initializer_range a__ : List[Any] = upscale a__ : List[Any] = img_range a__ : Optional[int] = resi_connection a__ : int = upsampler
688
1
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = ["image_processor", "tokenizer"] __UpperCamelCase = "CLIPImageProcessor" __UpperCamelCase = ("CLIPTokenizer", "CLIPTokenizerFast") def __init__( self : Optional[Any] , A__ : List[str]=None , A__ : Tuple=None , **A__ : Optional[int] ) -> Optional[Any]: '''simple docstring''' a__ : Union[str, Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , A__ , ) a__ : Optional[int] = kwargs.pop('''feature_extractor''' ) a__ : int = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(A__ , A__ ) def __call__( self : List[str] , A__ : Tuple=None , A__ : Dict=None , A__ : Optional[int]=None , **A__ : int ) -> str: '''simple docstring''' if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: a__ : Optional[Any] = self.tokenizer(A__ , return_tensors=A__ , **A__ ) if images is not None: a__ : List[str] = self.image_processor(A__ , return_tensors=A__ , **A__ ) if text is not None and images is not None: a__ : Dict = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**A__ ) , tensor_type=A__ ) def __lowerCAmelCase ( self : Dict , *A__ : Optional[int] , **A__ : Dict ) -> Union[str, Any]: '''simple docstring''' return self.tokenizer.batch_decode(*A__ , **A__ ) def __lowerCAmelCase ( self : Tuple , *A__ : int , **A__ : str ) -> List[str]: '''simple docstring''' return self.tokenizer.decode(*A__ , **A__ ) @property def __lowerCAmelCase ( self : Any ) -> Union[str, Any]: '''simple docstring''' a__ : int = self.tokenizer.model_input_names a__ : Optional[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , A__ , ) return self.image_processor_class @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , A__ , ) return self.image_processor
688
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCAmelCase__ ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : Optional[int] ) -> int: '''simple docstring''' a__ : int = 0 def __lowerCAmelCase ( self : Union[str, Any] ) -> Tuple: '''simple docstring''' a__ : Optional[int] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : Dict ) -> int: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : List[Any] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[Any] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[Any] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : List[Any] ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type a__ : int = Path(A__ ) / '''preprocessor_config.json''' a__ : Optional[int] = Path(A__ ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally a__ : List[Any] = AutoImageProcessor.from_pretrained(A__ ).to_dict() config_dict.pop('''image_processor_type''' ) a__ : Union[str, Any] = CLIPImageProcessor(**A__ ) # save in new folder model_config.save_pretrained(A__ ) config.save_pretrained(A__ ) a__ : Union[str, Any] = AutoImageProcessor.from_pretrained(A__ ) # make sure private variable is not incorrectly saved a__ : Optional[Any] = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) a__ : Any = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) def __lowerCAmelCase ( self : str ) -> Optional[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''clip-base is not a local folder and is not a valid model identifier''' ): a__ : str = AutoImageProcessor.from_pretrained('''clip-base''' ) def __lowerCAmelCase ( self : Optional[Any] ) -> int: '''simple docstring''' with self.assertRaisesRegex( A__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): a__ : Tuple = AutoImageProcessor.from_pretrained(A__ , revision='''aaaaaa''' ) def __lowerCAmelCase ( self : str ) -> List[Any]: '''simple docstring''' with self.assertRaisesRegex( A__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): a__ : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def __lowerCAmelCase ( self : List[Any] ) -> Tuple: '''simple docstring''' with self.assertRaises(A__ ): a__ : str = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(A__ ): a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : str = AutoImageProcessor.from_pretrained(A__ , trust_remote_code=A__ ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(A__ ): AutoImageProcessor.register(A__ , A__ ) with tempfile.TemporaryDirectory() as tmpdirname: a__ : Optional[int] = Path(A__ ) / '''preprocessor_config.json''' a__ : List[str] = Path(A__ ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(A__ , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(A__ , '''w''' ) ) a__ : Tuple = CustomImageProcessor.from_pretrained(A__ ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(A__ ) a__ : Tuple = AutoImageProcessor.from_pretrained(A__ ) self.assertIsInstance(A__ , A__ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def __lowerCAmelCase ( self : List[Any] ) -> List[str]: '''simple docstring''' class lowerCAmelCase__ ( lowerCAmelCase_ ): """simple docstring""" __UpperCamelCase = True try: AutoConfig.register('''custom''' , A__ ) AutoImageProcessor.register(A__ , A__ ) # If remote code is not set, the default is to use local a__ : Dict = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. a__ : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub a__ : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=A__ ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(A__ , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
688
1
'''simple docstring''' import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def __a ( lowerCAmelCase__ : int ): a__ : int = [2, 2, 6, 2] if '''tiny''' in model_name else [2, 2, 18, 2] a__ : Any = True if '''large''' in model_name or '''huge''' in model_name else False a__ : List[str] = True if '''large''' in model_name or '''huge''' in model_name else False a__ : Optional[int] = True if '''large''' in model_name or '''huge''' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: a__ : List[Any] = [3, 3, 3, 3] a__ : List[Any] = [5, 5, 5, 5] elif "fl4" in model_name: a__ : str = [4, 4, 4, 4] a__ : Optional[Any] = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: a__ : List[str] = [3, 3, 3, 3] if "lrf" in model_name: a__ : Any = [3, 3, 3, 3] else: a__ : int = [2, 2, 2, 2] if "tiny" in model_name: a__ : int = 96 elif "small" in model_name: a__ : int = 96 elif "base" in model_name: a__ : Union[str, Any] = 128 elif "large" in model_name: a__ : List[str] = 192 elif "xlarge" in model_name: a__ : Dict = 256 elif "huge" in model_name: a__ : int = 352 # set label information a__ : Tuple = '''huggingface/label-files''' if "large" in model_name or "huge" in model_name: a__ : List[Any] = '''imagenet-22k-id2label.json''' else: a__ : List[str] = '''imagenet-1k-id2label.json''' a__ : List[Any] = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type='''dataset''' ) , '''r''' ) ) a__ : str = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} a__ : Optional[int] = {v: k for k, v in idalabel.items()} a__ : Any = FocalNetConfig( embed_dim=lowerCAmelCase__ , depths=lowerCAmelCase__ , focal_levels=lowerCAmelCase__ , focal_windows=lowerCAmelCase__ , use_conv_embed=lowerCAmelCase__ , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__ , use_post_layernorm=lowerCAmelCase__ , use_layerscale=lowerCAmelCase__ , ) return config def __a ( lowerCAmelCase__ : Tuple ): if "patch_embed.proj" in name: a__ : Union[str, Any] = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' ) if "patch_embed.norm" in name: a__ : Tuple = name.replace('''patch_embed.norm''' , '''embeddings.norm''' ) if "layers" in name: a__ : Dict = '''encoder.''' + name if "encoder.layers" in name: a__ : str = name.replace('''encoder.layers''' , '''encoder.stages''' ) if "downsample.proj" in name: a__ : List[str] = name.replace('''downsample.proj''' , '''downsample.projection''' ) if "blocks" in name: a__ : Tuple = name.replace('''blocks''' , '''layers''' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: a__ : Optional[Any] = name.replace('''modulation.f''' , '''modulation.projection_in''' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: a__ : Union[str, Any] = name.replace('''modulation.h''' , '''modulation.projection_context''' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: a__ : Dict = name.replace('''modulation.proj''' , '''modulation.projection_out''' ) if name == "norm.weight": a__ : Dict = '''layernorm.weight''' if name == "norm.bias": a__ : List[str] = '''layernorm.bias''' if "head" in name: a__ : str = name.replace('''head''' , '''classifier''' ) else: a__ : Dict = '''focalnet.''' + name return name def __a ( lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str]=False ): # fmt: off a__ : Optional[Any] = { '''focalnet-tiny''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth''', '''focalnet-tiny-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth''', '''focalnet-small''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth''', '''focalnet-small-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth''', '''focalnet-base''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth''', '''focalnet-base-lrf''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth''', '''focalnet-large-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth''', '''focalnet-large-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth''', '''focalnet-xlarge-lrf-fl3''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth''', '''focalnet-xlarge-lrf-fl4''': '''https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth''', } # fmt: on a__ : Union[str, Any] = model_name_to_url[model_name] print('''Checkpoint URL: ''' , lowerCAmelCase__ ) a__ : List[str] = torch.hub.load_state_dict_from_url(lowerCAmelCase__ , map_location='''cpu''' )['''model'''] # rename keys for key in state_dict.copy().keys(): a__ : Union[str, Any] = state_dict.pop(lowerCAmelCase__ ) a__ : int = val a__ : List[str] = get_focalnet_config(lowerCAmelCase__ ) a__ : Optional[int] = FocalNetForImageClassification(lowerCAmelCase__ ) model.eval() # load state dict model.load_state_dict(lowerCAmelCase__ ) # verify conversion a__ : List[str] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' a__ : Any = BitImageProcessor( do_resize=lowerCAmelCase__ , size={'''shortest_edge''': 256} , resample=PILImageResampling.BILINEAR , do_center_crop=lowerCAmelCase__ , crop_size=224 , do_normalize=lowerCAmelCase__ , image_mean=lowerCAmelCase__ , image_std=lowerCAmelCase__ , ) a__ : Tuple = Image.open(requests.get(lowerCAmelCase__ , stream=lowerCAmelCase__ ).raw ) a__ : str = processor(images=lowerCAmelCase__ , return_tensors='''pt''' ) a__ : int = transforms.Compose( [ transforms.Resize(256 ), transforms.CenterCrop(224 ), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) a__ : Union[str, Any] = image_transforms(lowerCAmelCase__ ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values , lowerCAmelCase__ , atol=1E-4 ) a__ : Optional[Any] = model(**lowerCAmelCase__ ) a__ : List[str] = outputs.logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) print('''First values of logits:''' , outputs.logits[0, :3] ) if model_name == "focalnet-tiny": a__ : Tuple = torch.tensor([0.2166, -0.4368, 0.2191] ) elif model_name == "focalnet-tiny-lrf": a__ : List[Any] = torch.tensor([1.1669, 0.0125, -0.1695] ) elif model_name == "focalnet-small": a__ : List[Any] = torch.tensor([0.4917, -0.0430, 0.1341] ) elif model_name == "focalnet-small-lrf": a__ : int = torch.tensor([-0.2588, -0.5342, -0.2331] ) elif model_name == "focalnet-base": a__ : List[str] = torch.tensor([-0.1655, -0.4090, -0.1730] ) elif model_name == "focalnet-base-lrf": a__ : Dict = torch.tensor([0.5306, -0.0483, -0.3928] ) assert torch.allclose(outputs.logits[0, :3] , lowerCAmelCase__ , atol=1E-4 ) print('''Looks ok!''' ) if pytorch_dump_folder_path is not None: print(F'Saving model and processor of {model_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(lowerCAmelCase__ ) processor.save_pretrained(lowerCAmelCase__ ) if push_to_hub: print(F'Pushing model and processor of {model_name} to the hub...' ) model.push_to_hub(F'{model_name}' ) processor.push_to_hub(F'{model_name}' ) if __name__ == "__main__": __SCREAMING_SNAKE_CASE = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='focalnet-tiny', type=str, help='Name of the FocalNet 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 and processor to the hub.', ) __SCREAMING_SNAKE_CASE = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
688
'''simple docstring''' # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version __SCREAMING_SNAKE_CASE = get_logger(__name__) class lowerCAmelCase__ : """simple docstring""" __UpperCamelCase = "dummy_data" __UpperCamelCase = "datasets" __UpperCamelCase = False def __init__( self : Any , A__ : str , A__ : str , A__ : Union[Version, str] , A__ : Optional[str] = None , A__ : bool = False , A__ : bool = True , A__ : Optional[List[Callable]] = None , ) -> int: '''simple docstring''' a__ : Tuple = 0 a__ : Any = dataset_name a__ : int = cache_dir a__ : str = use_local_dummy_data a__ : List[str] = config # download_callbacks take a single url as input a__ : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root a__ : str = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general a__ : Optional[Any] = str(A__ ) # to be downloaded a__ : Tuple = None a__ : Tuple = None @property def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]: '''simple docstring''' if self._dummy_file is None: a__ : Dict = self.download_dummy_data() return self._dummy_file @property def __lowerCAmelCase ( self : Any ) -> Optional[int]: '''simple docstring''' if self.config is not None: # structure is dummy / config_name / version_name return os.path.join('''dummy''' , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join('''dummy''' , self.version_name ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Dict: '''simple docstring''' return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' ) def __lowerCAmelCase ( self : str ) -> Union[str, Any]: '''simple docstring''' a__ : int = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) a__ : str = cached_path( A__ , cache_dir=self.cache_dir , extract_compressed_file=A__ , force_extract=A__ ) return os.path.join(A__ , self.dummy_file_name ) @property def __lowerCAmelCase ( self : int ) -> Optional[int]: '''simple docstring''' return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: '''simple docstring''' if self._bucket_url is None: a__ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) ) return self._bucket_url @property def __lowerCAmelCase ( self : List[Any] ) -> Dict: '''simple docstring''' if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , *A__ : int ) -> Union[str, Any]: '''simple docstring''' if self.load_existing_dummy_data: # dummy data is downloaded and tested a__ : Tuple = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned a__ : Union[str, Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(A__ , A__ ): return self.create_dummy_data_dict(A__ , A__ ) elif isinstance(A__ , (list, tuple) ): return self.create_dummy_data_list(A__ , A__ ) else: return self.create_dummy_data_single(A__ , A__ ) def __lowerCAmelCase ( self : List[str] , A__ : Any , *A__ : int ) -> Any: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Any , A__ : Optional[int] , A__ : Optional[Any] ) -> int: '''simple docstring''' return self.download_and_extract(A__ ) def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , *A__ : List[Any] , **A__ : str ) -> Optional[Any]: '''simple docstring''' return path def __lowerCAmelCase ( self : List[Any] ) -> str: '''simple docstring''' return {} def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[str] ) -> Any: '''simple docstring''' a__ : int = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A__ , A__ ): for single_url in single_urls: download_callback(A__ ) else: a__ : Dict = single_urls download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A__ , A__ ): a__ : Optional[int] = [os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) for x in single_urls] else: a__ : Optional[Any] = single_urls a__ : Tuple = os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) a__ : List[str] = value # make sure that values are unique if all(isinstance(A__ , A__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique a__ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Optional[int] ) -> Optional[int]: '''simple docstring''' a__ : str = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one a__ : Union[str, Any] = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , A__ ) ) for url in data_url ) a__ : Optional[Any] = all( url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): a__ : Dict = [data_url[0]] * len(A__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Optional[int] = os.path.join(A__ , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) ) dummy_data_list.append(A__ ) return dummy_data_list def __lowerCAmelCase ( self : Dict , A__ : Dict , A__ : str ) -> Optional[int]: '''simple docstring''' for download_callback in self.download_callbacks: download_callback(A__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus a__ : Union[str, Any] = os.path.join(A__ , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) ) if os.path.exists(A__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def __lowerCAmelCase ( self : int ) -> str: '''simple docstring''' pass def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple: '''simple docstring''' pass def __lowerCAmelCase ( self : Any , A__ : Tuple ) -> Any: '''simple docstring''' def _iter_archive_members(A__ : str ): # this preserves the order of the members inside the ZIP archive a__ : Dict = Path(self.dummy_file ).parent a__ : Tuple = path.relative_to(A__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: a__ : Optional[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A__ ) a__ : str = Path(A__ ) a__ : Optional[Any] = _iter_archive_members(A__ ) if self.use_local_dummy_data else path.rglob('''*''' ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ): yield file_path.relative_to(A__ ).as_posix(), file_path.open('''rb''' ) def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> Tuple: '''simple docstring''' if not isinstance(A__ , A__ ): a__ : int = [paths] for path in paths: if os.path.isfile(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): return yield path else: for dirpath, dirnames, filenames in os.walk(A__ ): if os.path.basename(A__ ).startswith(('''.''', '''__''') ): continue dirnames.sort() for filename in sorted(A__ ): if filename.startswith(('''.''', '''__''') ): continue yield os.path.join(A__ , A__ )
688
1