code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
from heapq import heappop, heappush import numpy as np def __magic_name__ ( __lowerCAmelCase : np.ndarray , __lowerCAmelCase : tuple[int, int] , __lowerCAmelCase : tuple[int, int] , __lowerCAmelCase : bool , ) -> tuple[float | int, list[tuple[int, int]]]: __lowerCamelCase , __lowerCamelCase = grid.shape __lowerCamelCase = [-1, 1, 0, 0] __lowerCamelCase = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] __lowerCamelCase , __lowerCamelCase = [(0, source)], set() __lowerCamelCase = np.full((rows, cols) , np.inf ) __lowerCamelCase = 0 __lowerCamelCase = np.empty((rows, cols) , dtype=__lowerCAmelCase ) __lowerCamelCase = None while queue: ((__lowerCamelCase) , (__lowerCamelCase)) = heappop(__lowerCAmelCase ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: __lowerCamelCase = [] while (x, y) != source: path.append((x, y) ) __lowerCamelCase , __lowerCamelCase = predecessors[x, y] path.append(__lowerCAmelCase ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(__lowerCAmelCase ) ): __lowerCamelCase , __lowerCamelCase = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: __lowerCamelCase = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(__lowerCAmelCase , (dist + 1, (nx, ny)) ) __lowerCamelCase = dist + 1 __lowerCamelCase = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
270
from __future__ import annotations from statistics import mean def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> list[int]: __lowerCamelCase = [0] * no_of_processes __lowerCamelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] __lowerCamelCase = [] __lowerCamelCase = 0 __lowerCamelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCamelCase = [] __lowerCamelCase = -1 for i in range(__lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: __lowerCamelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCamelCase = i total_time += burst_time[target_process] completed += 1 __lowerCamelCase = 0 __lowerCamelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : int , __lowerCAmelCase : list[int] ) -> list[int]: __lowerCamelCase = [0] * no_of_processes for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") SCREAMING_SNAKE_CASE__ : Tuple = 4 SCREAMING_SNAKE_CASE__ : Optional[int] = [2, 5, 3, 7] SCREAMING_SNAKE_CASE__ : List[str] = [0, 0, 0, 0] SCREAMING_SNAKE_CASE__ : str = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( F'{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t' F'{waiting_time[i]}\t\t\t\t{turn_around_time[i]}' ) print(F'\nAverage waiting time = {mean(waiting_time):.5f}') print(F'Average turnaround time = {mean(turn_around_time):.5f}')
270
1
from string import ascii_uppercase SCREAMING_SNAKE_CASE__ : Union[str, Any] = {str(ord(c) - 55): c for c in ascii_uppercase} def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> str: if isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise TypeError('''int() can\'t convert non-string with explicit base''' ) if num < 0: raise ValueError('''parameter must be positive int''' ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise TypeError('''\'str\' object cannot be interpreted as an integer''' ) if isinstance(__lowerCAmelCase , __lowerCAmelCase ): raise TypeError('''\'float\' object cannot be interpreted as an integer''' ) if base in (0, 1): raise ValueError('''base must be >= 2''' ) if base > 36: raise ValueError('''base must be <= 36''' ) __lowerCamelCase = '''''' __lowerCamelCase = 0 __lowerCamelCase = 0 while div != 1: __lowerCamelCase , __lowerCamelCase = divmod(__lowerCAmelCase , __lowerCAmelCase ) if base >= 11 and 9 < mod < 36: __lowerCamelCase = ALPHABET_VALUES[str(__lowerCAmelCase )] else: __lowerCamelCase = str(__lowerCAmelCase ) new_value += actual_value __lowerCamelCase = num // base __lowerCamelCase = div if div == 0: return str(new_value[::-1] ) elif div == 1: new_value += str(__lowerCAmelCase ) return str(new_value[::-1] ) return new_value[::-1] if __name__ == "__main__": import doctest doctest.testmod() for base in range(2, 37): for num in range(1_000): assert int(decimal_to_any(num, base), base) == num, ( num, base, decimal_to_any(num, base), int(decimal_to_any(num, base), base), )
270
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( __lowercase ): @staticmethod @abstractmethod def __A ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> str: raise NotImplementedError() @abstractmethod def __A ( self : Optional[int] ) -> Union[str, Any]: raise NotImplementedError()
270
1
# Algorithm for the pigeonhole sorting def __magic_name__ ( __lowerCAmelCase : Union[str, Any] ) -> Tuple: __lowerCamelCase = min(__lowerCAmelCase ) # min() finds the minimum value __lowerCamelCase = max(__lowerCAmelCase ) # max() finds the maximum value __lowerCamelCase = max_val - min_val + 1 # size is difference of max and min values plus one # list of pigeonholes of size equal to the variable size __lowerCamelCase = [0] * size # Populate the pigeonholes. for x in a: assert isinstance(__lowerCAmelCase , __lowerCAmelCase ), "integers only please" holes[x - min_val] += 1 # Putting the elements back into the array in an order. __lowerCamelCase = 0 for count in range(__lowerCAmelCase ): while holes[count] > 0: holes[count] -= 1 __lowerCamelCase = count + min_val i += 1 def __magic_name__ ( ) -> int: __lowerCamelCase = [8, 3, 2, 7, 4, 6, 8] pigeonhole_sort(__lowerCAmelCase ) print('''Sorted order is:''' , ''' '''.join(__lowerCAmelCase ) ) if __name__ == "__main__": main()
270
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue_model_parallelism.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> List[Any]: if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=SCREAMING_SNAKE_CASE__ , ) assert hasattr(self , '''env''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: # configuration for running training on smdistributed Model Parallel __lowerCamelCase = { '''enabled''': True, '''processes_per_host''': 8, } __lowerCamelCase = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __lowerCamelCase = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __lowerCamelCase = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=SCREAMING_SNAKE_CASE__ , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE__ , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 5_00, } , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE__ , py_version='''py36''' , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: TrainingJobAnalytics(SCREAMING_SNAKE_CASE__ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: # create estimator __lowerCamelCase = self.create_estimator(SCREAMING_SNAKE_CASE__ ) # run training estimator.fit() # result dataframe __lowerCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # 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} , SCREAMING_SNAKE_CASE__ )
270
1
import numpy as np def __magic_name__ ( __lowerCAmelCase : np.array ) -> np.array: return 1 / (1 + np.exp(-vector )) def __magic_name__ ( __lowerCAmelCase : np.array ) -> np.array: return vector * sigmoid(1.702 * vector ) if __name__ == "__main__": import doctest doctest.testmod()
270
from __future__ import annotations from fractions import Fraction def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def __magic_name__ ( __lowerCAmelCase : int ) -> list[str]: __lowerCamelCase = [] __lowerCamelCase = 11 __lowerCamelCase = int('''1''' + '''0''' * digit_len ) for num in range(__lowerCAmelCase , __lowerCAmelCase ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(__lowerCAmelCase , __lowerCAmelCase ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 __lowerCamelCase = 10 return solutions def __magic_name__ ( __lowerCAmelCase : int = 2 ) -> int: __lowerCamelCase = 1.0 for fraction in fraction_list(__lowerCAmelCase ): __lowerCamelCase = Fraction(__lowerCAmelCase ) result *= frac.denominator / frac.numerator return int(__lowerCAmelCase ) if __name__ == "__main__": print(solution())
270
1
import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger SCREAMING_SNAKE_CASE__ : Dict = get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[str] = r"\n Args:\n input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n search or log softmax for each vocabulary token when using beam search\n kwargs (`Dict[str, Any]`, *optional*):\n Additional logits processor specific kwargs.\n\n Return:\n `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n" class lowerCAmelCase__ : @add_start_docstrings(SCREAMING_SNAKE_CASE__ ) def __call__( self : int , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray ) -> jnp.ndarray: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class lowerCAmelCase__ : @add_start_docstrings(SCREAMING_SNAKE_CASE__ ) def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray ) -> jnp.ndarray: raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class lowerCAmelCase__ ( __lowercase ): @add_start_docstrings(SCREAMING_SNAKE_CASE__ ) def __call__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> jnp.ndarray: for processor in self: __lowerCamelCase = inspect.signature(processor.__call__ ).parameters if len(SCREAMING_SNAKE_CASE__ ) > 3: if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ): raise ValueError( f'''Make sure that all the required parameters: {list(function_args.keys() )} for ''' f'''{processor.__class__} are passed to the logits processor.''' ) __lowerCamelCase = processor(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: __lowerCamelCase = processor(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return scores class lowerCAmelCase__ ( __lowercase ): def __init__( self : int , SCREAMING_SNAKE_CASE__ : float ) -> Any: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or not (temperature > 0): raise ValueError(f'''`temperature` has to be a strictly positive float, but is {temperature}''' ) __lowerCamelCase = temperature def __call__( self : List[str] , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : int ) -> jnp.ndarray: __lowerCamelCase = scores / self.temperature return scores class lowerCAmelCase__ ( __lowercase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : float , SCREAMING_SNAKE_CASE__ : float = -float('''Inf''' ) , SCREAMING_SNAKE_CASE__ : int = 1 ) -> int: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or (top_p < 0 or top_p > 1.0): raise ValueError(f'''`top_p` has to be a float > 0 and < 1, but is {top_p}''' ) if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or (min_tokens_to_keep < 1): raise ValueError(f'''`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}''' ) __lowerCamelCase = top_p __lowerCamelCase = filter_value __lowerCamelCase = min_tokens_to_keep def __call__( self : Tuple , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : int ) -> jnp.ndarray: __lowerCamelCase , __lowerCamelCase = lax.top_k(SCREAMING_SNAKE_CASE__ , scores.shape[-1] ) __lowerCamelCase = jnp.full_like(SCREAMING_SNAKE_CASE__ , self.filter_value ) __lowerCamelCase = jax.nn.softmax(SCREAMING_SNAKE_CASE__ , axis=-1 ).cumsum(axis=-1 ) __lowerCamelCase = cumulative_probs < self.top_p # include the token that is higher than top_p as well __lowerCamelCase = jnp.roll(SCREAMING_SNAKE_CASE__ , 1 ) score_mask |= score_mask.at[:, 0].set(SCREAMING_SNAKE_CASE__ ) # min tokens to keep __lowerCamelCase = score_mask.at[:, : self.min_tokens_to_keep].set(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.where(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jax.lax.sort_key_val(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )[-1] return next_scores class lowerCAmelCase__ ( __lowercase ): def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = -float('''Inf''' ) , SCREAMING_SNAKE_CASE__ : int = 1 ) -> Any: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or top_k <= 0: raise ValueError(f'''`top_k` has to be a strictly positive integer, but is {top_k}''' ) __lowerCamelCase = max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = filter_value def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : int ) -> jnp.ndarray: __lowerCamelCase , __lowerCamelCase = scores.shape __lowerCamelCase = jnp.full(batch_size * vocab_size , self.filter_value ) __lowerCamelCase = min(self.top_k , scores.shape[-1] ) # Safety check __lowerCamelCase , __lowerCamelCase = lax.top_k(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.broadcast_to((jnp.arange(SCREAMING_SNAKE_CASE__ ) * vocab_size)[:, None] , (batch_size, topk) ).flatten() __lowerCamelCase = topk_scores.flatten() __lowerCamelCase = topk_indices.flatten() + shift __lowerCamelCase = next_scores_flat.at[topk_indices_flat].set(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = next_scores_flat.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return next_scores class lowerCAmelCase__ ( __lowercase ): def __init__( self : Any , SCREAMING_SNAKE_CASE__ : int ) -> Any: __lowerCamelCase = bos_token_id def __call__( self : Dict , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : int ) -> jnp.ndarray: __lowerCamelCase = jnp.full(scores.shape , -float('''inf''' ) ) __lowerCamelCase = 1 - jnp.bool_(cur_len - 1 ) __lowerCamelCase = jnp.where(SCREAMING_SNAKE_CASE__ , new_scores.at[:, self.bos_token_id].set(0 ) , SCREAMING_SNAKE_CASE__ ) return scores class lowerCAmelCase__ ( __lowercase ): def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: __lowerCamelCase = max_length __lowerCamelCase = eos_token_id def __call__( self : List[str] , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : int ) -> jnp.ndarray: __lowerCamelCase = jnp.full(scores.shape , -float('''inf''' ) ) __lowerCamelCase = 1 - jnp.bool_(cur_len - self.max_length + 1 ) __lowerCamelCase = jnp.where(SCREAMING_SNAKE_CASE__ , new_scores.at[:, self.eos_token_id].set(0 ) , SCREAMING_SNAKE_CASE__ ) return scores class lowerCAmelCase__ ( __lowercase ): def __init__( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or min_length < 0: raise ValueError(f'''`min_length` has to be a positive integer, but is {min_length}''' ) if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or eos_token_id < 0: raise ValueError(f'''`eos_token_id` has to be a positive integer, but is {eos_token_id}''' ) __lowerCamelCase = min_length __lowerCamelCase = eos_token_id def __call__( self : int , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : int ) -> jnp.ndarray: # create boolean flag to decide if min length penalty should be applied __lowerCamelCase = 1 - jnp.clip(cur_len - self.min_length , 0 , 1 ) __lowerCamelCase = jnp.where(SCREAMING_SNAKE_CASE__ , scores.at[:, self.eos_token_id].set(-float('''inf''' ) ) , SCREAMING_SNAKE_CASE__ ) return scores class lowerCAmelCase__ ( __lowercase ): def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] ) -> str: __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = begin_index def __call__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Any: __lowerCamelCase = 1 - jnp.bool_(cur_len - self.begin_index ) __lowerCamelCase = jnp.where(SCREAMING_SNAKE_CASE__ , scores.at[:, self.begin_suppress_tokens].set(-float('''inf''' ) ) , SCREAMING_SNAKE_CASE__ ) return scores class lowerCAmelCase__ ( __lowercase ): def __init__( self : Any , SCREAMING_SNAKE_CASE__ : list ) -> Tuple: __lowerCamelCase = list(SCREAMING_SNAKE_CASE__ ) def __call__( self : Dict , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : int ) -> jnp.ndarray: __lowerCamelCase = scores.at[..., self.suppress_tokens].set(-float('''inf''' ) ) return scores class lowerCAmelCase__ ( __lowercase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Tuple ) -> Tuple: __lowerCamelCase = dict(SCREAMING_SNAKE_CASE__ ) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. __lowerCamelCase = jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1 for index, token in force_token_map.items(): if token is not None: __lowerCamelCase = force_token_array.at[index].set(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.intaa(SCREAMING_SNAKE_CASE__ ) def __call__( self : int , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : jnp.ndarray , SCREAMING_SNAKE_CASE__ : int ) -> jnp.ndarray: def _force_token(SCREAMING_SNAKE_CASE__ : Optional[int] ): __lowerCamelCase = scores.shape[0] __lowerCamelCase = self.force_token_array[generation_idx] __lowerCamelCase = jnp.ones_like(SCREAMING_SNAKE_CASE__ , dtype=scores.dtype ) * -float('''inf''' ) __lowerCamelCase = jnp.zeros((batch_size, 1) , dtype=scores.dtype ) __lowerCamelCase = lax.dynamic_update_slice(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , (0, current_token) ) return new_scores __lowerCamelCase = lax.cond( cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond( self.force_token_array[cur_len] >= 0 , lambda: _force_token(SCREAMING_SNAKE_CASE__ ) , lambda: scores , ) , ) return scores class lowerCAmelCase__ ( __lowercase ): def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Union[str, Any]: __lowerCamelCase = generate_config.eos_token_id __lowerCamelCase = generate_config.no_timestamps_token_id __lowerCamelCase = generate_config.no_timestamps_token_id + 1 __lowerCamelCase = decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(SCREAMING_SNAKE_CASE__ , '''max_initial_timestamp_index''' ): __lowerCamelCase = generate_config.max_initial_timestamp_index else: __lowerCamelCase = model_config.vocab_size if self.max_initial_timestamp_index is None: __lowerCamelCase = model_config.vocab_size def __call__( self : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: # suppress <|notimestamps|> which is handled by without_timestamps __lowerCamelCase = scores.at[:, self.no_timestamps_token_id].set(-float('''inf''' ) ) def handle_pairs(SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ): __lowerCamelCase = jnp.where((cur_len - self.begin_index) >= 1 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = jnp.where((cur_len - self.begin_index) < 2 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) return jnp.where( SCREAMING_SNAKE_CASE__ , jnp.where( penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float('''inf''' ) ) , scores_k.at[: self.eos_token_id].set(-float('''inf''' ) ) , ) , SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = jax.vmap(SCREAMING_SNAKE_CASE__ )(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.where(cur_len == self.begin_index , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.where( self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = self.timestamp_begin + self.max_initial_timestamp_index __lowerCamelCase = jnp.where( SCREAMING_SNAKE_CASE__ , scores.at[:, last_allowed + 1 :].set(-float('''inf''' ) ) , SCREAMING_SNAKE_CASE__ , ) # if sum of probability over timestamps is above any other token, sample timestamp __lowerCamelCase = jax.nn.log_softmax(SCREAMING_SNAKE_CASE__ , axis=-1 ) def handle_cumulative_probs(SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str ): __lowerCamelCase = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 ) __lowerCamelCase = jnp.max(logprobs_k[: self.timestamp_begin] ) return jnp.where( timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float('''inf''' ) ) , SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = jax.vmap(SCREAMING_SNAKE_CASE__ )(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return scores
270
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipTextConfig", "BlipVisionConfig", ], "processing_blip": ["BlipProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = ["BlipImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipModel", "BlipPreTrainedModel", "BlipForConditionalGeneration", "BlipForQuestionAnswering", "BlipVisionModel", "BlipTextModel", "BlipForImageTextRetrieval", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBlipModel", "TFBlipPreTrainedModel", "TFBlipForConditionalGeneration", "TFBlipForQuestionAnswering", "TFBlipVisionModel", "TFBlipTextModel", "TFBlipForImageTextRetrieval", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
1
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Dict = { "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json", "allenai/longformer-large-4096": "https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json", "allenai/longformer-large-4096-finetuned-triviaqa": ( "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json" ), "allenai/longformer-base-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json" ), "allenai/longformer-large-4096-extra.pos.embd.only": ( "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json" ), } class lowerCAmelCase__ ( __lowercase ): a__ : List[str] = """longformer""" def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[List[int], int] = 5_12 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 1 , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 3_05_22 , SCREAMING_SNAKE_CASE__ : int = 7_68 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 12 , SCREAMING_SNAKE_CASE__ : int = 30_72 , SCREAMING_SNAKE_CASE__ : str = "gelu" , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : int = 5_12 , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1e-12 , SCREAMING_SNAKE_CASE__ : bool = False , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Tuple: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = attention_window __lowerCamelCase = sep_token_id __lowerCamelCase = bos_token_id __lowerCamelCase = eos_token_id __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = hidden_act __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = onnx_export class lowerCAmelCase__ ( __lowercase ): def __init__( self : int , SCREAMING_SNAKE_CASE__ : "PretrainedConfig" , SCREAMING_SNAKE_CASE__ : str = "default" , SCREAMING_SNAKE_CASE__ : "List[PatchingSpec]" = None ) -> List[str]: super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = True @property def __A ( self : List[str] ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __lowerCamelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: __lowerCamelCase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''global_attention_mask''', dynamic_axis), ] ) @property def __A ( self : Dict ) -> Mapping[str, Mapping[int, str]]: __lowerCamelCase = super().outputs if self.task == "default": __lowerCamelCase = {0: '''batch'''} return outputs @property def __A ( self : int ) -> float: return 1e-4 @property def __A ( self : Optional[Any] ) -> int: # needs to be >= 14 to support tril operator return max(super().default_onnx_opset , 14 ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : "PreTrainedTokenizerBase" , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : int = -1 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[TensorType] = None , ) -> Mapping[str, Any]: __lowerCamelCase = super().generate_dummy_inputs( preprocessor=SCREAMING_SNAKE_CASE__ , batch_size=SCREAMING_SNAKE_CASE__ , seq_length=SCREAMING_SNAKE_CASE__ , is_pair=SCREAMING_SNAKE_CASE__ , framework=SCREAMING_SNAKE_CASE__ ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly __lowerCamelCase = torch.zeros_like(inputs['''input_ids'''] ) # make every second token global __lowerCamelCase = 1 return inputs
270
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
270
import pprint import requests SCREAMING_SNAKE_CASE__ : str = "https://zenquotes.io/api" def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = random_quotes() pprint.pprint(response)
270
1
import os import time import numpy as np import onnxruntime as ort SCREAMING_SNAKE_CASE__ : Optional[Any] = "1" SCREAMING_SNAKE_CASE__ : Union[str, Any] = "0" SCREAMING_SNAKE_CASE__ : int = "1" SCREAMING_SNAKE_CASE__ : Dict = ort.SessionOptions() SCREAMING_SNAKE_CASE__ : Any = ort.GraphOptimizationLevel.ORT_DISABLE_ALL print("Create inference session...") SCREAMING_SNAKE_CASE__ : List[str] = ["TensorrtExecutionProvider", "CUDAExecutionProvider"] SCREAMING_SNAKE_CASE__ : Optional[int] = ort.InferenceSession("model.onnx", sess_options=sess_opt, providers=execution_provider) SCREAMING_SNAKE_CASE__ : str = ort.RunOptions() SCREAMING_SNAKE_CASE__ : Optional[Any] = 128 SCREAMING_SNAKE_CASE__ : List[str] = 1 SCREAMING_SNAKE_CASE__ : List[Any] = np.ones((batch, sequence), dtype=np.intaa) SCREAMING_SNAKE_CASE__ : Any = np.ones((batch, sequence), dtype=np.intaa) SCREAMING_SNAKE_CASE__ : List[str] = np.ones((batch, sequence), dtype=np.intaa) print("Warm up phase...") sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print("Start inference...") SCREAMING_SNAKE_CASE__ : Union[str, Any] = time.time() SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_000 SCREAMING_SNAKE_CASE__ : int = {} for iter in range(max_iters): SCREAMING_SNAKE_CASE__ : Union[str, Any] = sess.run( None, { sess.get_inputs()[0].name: input_ids, sess.get_inputs()[1].name: attention_mask, sess.get_inputs()[2].name: token_type_ids, }, run_options=run_opt, ) print("Average Inference Time = {:.3f} ms".format((time.time() - start_time) * 1_000 / max_iters))
270
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __magic_name__ ( __lowerCAmelCase : int ) -> int: __lowerCamelCase = prime_factors(__lowerCAmelCase ) if is_square_free(__lowerCAmelCase ): return -1 if len(__lowerCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
270
1
import math from enum import Enum from typing import Optional, Union from torch.optim import Optimizer from torch.optim.lr_scheduler import LambdaLR from .utils import logging SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowercase ): a__ : Union[str, Any] = """linear""" a__ : Optional[Any] = """cosine""" a__ : Dict = """cosine_with_restarts""" a__ : List[str] = """polynomial""" a__ : str = """constant""" a__ : Any = """constant_with_warmup""" a__ : Tuple = """piecewise_constant""" def __magic_name__ ( __lowerCAmelCase : Optimizer , __lowerCAmelCase : int = -1 ) -> Union[str, Any]: return LambdaLR(__lowerCAmelCase , lambda __lowerCAmelCase : 1 , last_epoch=__lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : Optimizer , __lowerCAmelCase : int , __lowerCAmelCase : int = -1 ) -> Optional[Any]: def lr_lambda(__lowerCAmelCase : int ): if current_step < num_warmup_steps: return float(__lowerCAmelCase ) / float(max(1.0 , __lowerCAmelCase ) ) return 1.0 return LambdaLR(__lowerCAmelCase , __lowerCAmelCase , last_epoch=__lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : Optimizer , __lowerCAmelCase : str , __lowerCAmelCase : int = -1 ) -> Optional[int]: __lowerCamelCase = {} __lowerCamelCase = step_rules.split(''',''' ) for rule_str in rule_list[:-1]: __lowerCamelCase , __lowerCamelCase = rule_str.split(''':''' ) __lowerCamelCase = int(__lowerCAmelCase ) __lowerCamelCase = float(__lowerCAmelCase ) __lowerCamelCase = value __lowerCamelCase = float(rule_list[-1] ) def create_rules_function(__lowerCAmelCase : int , __lowerCAmelCase : List[str] ): def rule_func(__lowerCAmelCase : int ) -> float: __lowerCamelCase = sorted(rules_dict.keys() ) for i, sorted_step in enumerate(__lowerCAmelCase ): if steps < sorted_step: return rules_dict[sorted_steps[i]] return last_lr_multiple return rule_func __lowerCamelCase = create_rules_function(__lowerCAmelCase , __lowerCAmelCase ) return LambdaLR(__lowerCAmelCase , __lowerCAmelCase , last_epoch=__lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : str , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[int]=-1 ) -> str: def lr_lambda(__lowerCAmelCase : int ): if current_step < num_warmup_steps: return float(__lowerCAmelCase ) / float(max(1 , __lowerCAmelCase ) ) return max( 0.0 , float(num_training_steps - current_step ) / float(max(1 , num_training_steps - num_warmup_steps ) ) ) return LambdaLR(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : Optimizer , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : float = 0.5 , __lowerCAmelCase : int = -1 ) -> Tuple: def lr_lambda(__lowerCAmelCase : List[Any] ): if current_step < num_warmup_steps: return float(__lowerCAmelCase ) / float(max(1 , __lowerCAmelCase ) ) __lowerCamelCase = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * float(__lowerCAmelCase ) * 2.0 * progress )) ) return LambdaLR(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : Optimizer , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : int = 1 , __lowerCAmelCase : int = -1 ) -> Any: def lr_lambda(__lowerCAmelCase : Dict ): if current_step < num_warmup_steps: return float(__lowerCAmelCase ) / float(max(1 , __lowerCAmelCase ) ) __lowerCamelCase = float(current_step - num_warmup_steps ) / float(max(1 , num_training_steps - num_warmup_steps ) ) if progress >= 1.0: return 0.0 return max(0.0 , 0.5 * (1.0 + math.cos(math.pi * ((float(__lowerCAmelCase ) * progress) % 1.0) )) ) return LambdaLR(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : int=1E-7 , __lowerCAmelCase : Dict=1.0 , __lowerCAmelCase : Union[str, Any]=-1 ) -> Any: __lowerCamelCase = optimizer.defaults['''lr'''] if not (lr_init > lr_end): raise ValueError(f'''lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})''' ) def lr_lambda(__lowerCAmelCase : int ): if current_step < num_warmup_steps: return float(__lowerCAmelCase ) / float(max(1 , __lowerCAmelCase ) ) elif current_step > num_training_steps: return lr_end / lr_init # as LambdaLR multiplies by lr_init else: __lowerCamelCase = lr_init - lr_end __lowerCamelCase = num_training_steps - num_warmup_steps __lowerCamelCase = 1 - (current_step - num_warmup_steps) / decay_steps __lowerCamelCase = lr_range * pct_remaining**power + lr_end return decay / lr_init # as LambdaLR multiplies by lr_init return LambdaLR(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : int = { SchedulerType.LINEAR: get_linear_schedule_with_warmup, SchedulerType.COSINE: get_cosine_schedule_with_warmup, SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup, SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup, SchedulerType.CONSTANT: get_constant_schedule, SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup, SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule, } def __magic_name__ ( __lowerCAmelCase : Union[str, SchedulerType] , __lowerCAmelCase : Optimizer , __lowerCAmelCase : Optional[str] = None , __lowerCAmelCase : Optional[int] = None , __lowerCAmelCase : Optional[int] = None , __lowerCAmelCase : int = 1 , __lowerCAmelCase : float = 1.0 , __lowerCAmelCase : int = -1 , ) -> Dict: __lowerCamelCase = SchedulerType(__lowerCAmelCase ) __lowerCamelCase = TYPE_TO_SCHEDULER_FUNCTION[name] if name == SchedulerType.CONSTANT: return schedule_func(__lowerCAmelCase , last_epoch=__lowerCAmelCase ) if name == SchedulerType.PIECEWISE_CONSTANT: return schedule_func(__lowerCAmelCase , step_rules=__lowerCAmelCase , last_epoch=__lowerCAmelCase ) # All other schedulers require `num_warmup_steps` if num_warmup_steps is None: raise ValueError(f'''{name} requires `num_warmup_steps`, please provide that argument.''' ) if name == SchedulerType.CONSTANT_WITH_WARMUP: return schedule_func(__lowerCAmelCase , num_warmup_steps=__lowerCAmelCase , last_epoch=__lowerCAmelCase ) # All other schedulers require `num_training_steps` if num_training_steps is None: raise ValueError(f'''{name} requires `num_training_steps`, please provide that argument.''' ) if name == SchedulerType.COSINE_WITH_RESTARTS: return schedule_func( __lowerCAmelCase , num_warmup_steps=__lowerCAmelCase , num_training_steps=__lowerCAmelCase , num_cycles=__lowerCAmelCase , last_epoch=__lowerCAmelCase , ) if name == SchedulerType.POLYNOMIAL: return schedule_func( __lowerCAmelCase , num_warmup_steps=__lowerCAmelCase , num_training_steps=__lowerCAmelCase , power=__lowerCAmelCase , last_epoch=__lowerCAmelCase , ) return schedule_func( __lowerCAmelCase , num_warmup_steps=__lowerCAmelCase , num_training_steps=__lowerCAmelCase , last_epoch=__lowerCAmelCase )
270
import argparse import collections import json import os import re import string import sys import numpy as np SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"\b(a|an|the)\b", re.UNICODE) SCREAMING_SNAKE_CASE__ : int = None def __magic_name__ ( ) -> str: __lowerCamelCase = argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.''' ) parser.add_argument('''data_file''' , metavar='''data.json''' , help='''Input data JSON file.''' ) parser.add_argument('''pred_file''' , metavar='''pred.json''' , help='''Model predictions.''' ) parser.add_argument( '''--out-file''' , '''-o''' , metavar='''eval.json''' , help='''Write accuracy metrics to file (default is stdout).''' ) parser.add_argument( '''--na-prob-file''' , '''-n''' , metavar='''na_prob.json''' , help='''Model estimates of probability of no answer.''' ) parser.add_argument( '''--na-prob-thresh''' , '''-t''' , type=__lowerCAmelCase , default=1.0 , help='''Predict "" if no-answer probability exceeds this (default = 1.0).''' , ) parser.add_argument( '''--out-image-dir''' , '''-p''' , metavar='''out_images''' , default=__lowerCAmelCase , help='''Save precision-recall curves to directory.''' ) parser.add_argument('''--verbose''' , '''-v''' , action='''store_true''' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = bool(qa['''answers''']['''text'''] ) return qid_to_has_ans def __magic_name__ ( __lowerCAmelCase : Dict ) -> Optional[Any]: def remove_articles(__lowerCAmelCase : Optional[int] ): return ARTICLES_REGEX.sub(''' ''' , __lowerCAmelCase ) def white_space_fix(__lowerCAmelCase : Optional[int] ): return " ".join(text.split() ) def remove_punc(__lowerCAmelCase : Union[str, Any] ): __lowerCamelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__lowerCAmelCase : Dict ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__lowerCAmelCase ) ) ) ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Optional[int]: if not s: return [] return normalize_answer(__lowerCAmelCase ).split() def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple ) -> int: return int(normalize_answer(__lowerCAmelCase ) == normalize_answer(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple ) -> str: __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = collections.Counter(__lowerCAmelCase ) & collections.Counter(__lowerCAmelCase ) __lowerCamelCase = sum(common.values() ) if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = (2 * precision * recall) / (precision + recall) return fa def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] ) -> Optional[Any]: __lowerCamelCase = {} __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = qa['''id'''] __lowerCamelCase = [t for t in qa['''answers''']['''text'''] if normalize_answer(__lowerCAmelCase )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __lowerCamelCase = [''''''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue __lowerCamelCase = preds[qid] # Take max over all gold answers __lowerCamelCase = max(compute_exact(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) __lowerCamelCase = max(compute_fa(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) return exact_scores, fa_scores def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ) -> List[str]: __lowerCamelCase = {} for qid, s in scores.items(): __lowerCamelCase = na_probs[qid] > na_prob_thresh if pred_na: __lowerCamelCase = float(not qid_to_has_ans[qid] ) else: __lowerCamelCase = s return new_scores def __magic_name__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=None ) -> Union[str, Any]: if not qid_list: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores.values() ) / total), ('''f1''', 100.0 * sum(fa_scores.values() ) / total), ('''total''', total), ] ) else: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('''f1''', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('''total''', total), ] ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ) -> int: for k in new_eval: __lowerCamelCase = new_eval[k] def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ) -> Optional[Any]: plt.step(__lowerCAmelCase , __lowerCAmelCase , color='''b''' , alpha=0.2 , where='''post''' ) plt.fill_between(__lowerCAmelCase , __lowerCAmelCase , step='''post''' , alpha=0.2 , color='''b''' ) plt.xlabel('''Recall''' ) plt.ylabel('''Precision''' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__lowerCAmelCase ) plt.savefig(__lowerCAmelCase ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Tuple=None ) -> int: __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) __lowerCamelCase = 0.0 __lowerCamelCase = 1.0 __lowerCamelCase = 0.0 __lowerCamelCase = [1.0] __lowerCamelCase = [0.0] __lowerCamelCase = 0.0 for i, qid in enumerate(__lowerCAmelCase ): if qid_to_has_ans[qid]: true_pos += scores[qid] __lowerCamelCase = true_pos / float(i + 1 ) __lowerCamelCase = true_pos / float(__lowerCAmelCase ) if i == len(__lowerCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__lowerCAmelCase ) recalls.append(__lowerCAmelCase ) if out_image: plot_pr_curve(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return {"ap": 100.0 * avg_prec} def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] ) -> List[Any]: if out_image_dir and not os.path.exists(__lowerCAmelCase ): os.makedirs(__lowerCAmelCase ) __lowerCamelCase = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_exact.png''' ) , title='''Precision-Recall curve for Exact Match score''' , ) __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_f1.png''' ) , title='''Precision-Recall curve for F1 score''' , ) __lowerCamelCase = {k: float(__lowerCAmelCase ) for k, v in qid_to_has_ans.items()} __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_oracle.png''' ) , title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)''' , ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_exact''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_f1''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_oracle''' ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> Optional[Any]: if not qid_list: return __lowerCamelCase = [na_probs[k] for k in qid_list] __lowerCamelCase = np.ones_like(__lowerCAmelCase ) / float(len(__lowerCAmelCase ) ) plt.hist(__lowerCAmelCase , weights=__lowerCAmelCase , bins=20 , range=(0.0, 1.0) ) plt.xlabel('''Model probability of no-answer''' ) plt.ylabel('''Proportion of dataset''' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__lowerCAmelCase , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ) -> Optional[int]: __lowerCamelCase = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __lowerCamelCase = num_no_ans __lowerCamelCase = cur_score __lowerCamelCase = 0.0 __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) for i, qid in enumerate(__lowerCAmelCase ): if qid not in scores: continue if qid_to_has_ans[qid]: __lowerCamelCase = scores[qid] else: if preds[qid]: __lowerCamelCase = -1 else: __lowerCamelCase = 0 cur_score += diff if cur_score > best_score: __lowerCamelCase = cur_score __lowerCamelCase = na_probs[qid] return 100.0 * best_score / len(__lowerCAmelCase ), best_thresh def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] ) -> int: __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = best_exact __lowerCamelCase = exact_thresh __lowerCamelCase = best_fa __lowerCamelCase = fa_thresh def __magic_name__ ( ) -> Optional[int]: with open(OPTS.data_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) __lowerCamelCase = dataset_json['''data'''] with open(OPTS.pred_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) else: __lowerCamelCase = {k: 0.0 for k in preds} __lowerCamelCase = make_qid_to_has_ans(__lowerCAmelCase ) # maps qid to True/False __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if v] __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if not v] __lowerCamelCase , __lowerCamelCase = get_raw_scores(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase ) if has_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''HasAns''' ) if no_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''NoAns''' ) if OPTS.na_prob_file: find_all_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''hasAns''' ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''noAns''' ) if OPTS.out_file: with open(OPTS.out_file , '''w''' ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) else: print(json.dumps(__lowerCAmelCase , indent=2 ) ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
270
1
def __magic_name__ ( __lowerCAmelCase : list[list[int | float]] ) -> int: __lowerCamelCase = len(__lowerCAmelCase ) __lowerCamelCase = len(matrix[0] ) __lowerCamelCase = min(__lowerCAmelCase , __lowerCAmelCase ) for row in range(__lowerCAmelCase ): # Check if diagonal element is not zero if matrix[row][row] != 0: # Eliminate all the elements below the diagonal for col in range(row + 1 , __lowerCAmelCase ): __lowerCamelCase = matrix[col][row] / matrix[row][row] for i in range(__lowerCAmelCase , __lowerCAmelCase ): matrix[col][i] -= multiplier * matrix[row][i] else: # Find a non-zero diagonal element to swap rows __lowerCamelCase = True for i in range(row + 1 , __lowerCAmelCase ): if matrix[i][row] != 0: __lowerCamelCase , __lowerCamelCase = matrix[i], matrix[row] __lowerCamelCase = False break if reduce: rank -= 1 for i in range(__lowerCAmelCase ): __lowerCamelCase = matrix[i][rank] # Reduce the row pointer by one to stay on the same row row -= 1 return rank if __name__ == "__main__": import doctest doctest.testmod()
270
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F'{bindir}/../../examples/pytorch/translation'): from run_translation import main # noqa set_seed(42) SCREAMING_SNAKE_CASE__ : Any = "sshleifer/student_marian_en_ro_6_1" SCREAMING_SNAKE_CASE__ : Tuple = "sshleifer/tiny-mbart" @require_torch class lowerCAmelCase__ ( __lowercase ): def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , ) -> Optional[int]: __lowerCamelCase = self.run_trainer( eval_steps=1 , max_len=12 , model_name=SCREAMING_SNAKE_CASE__ , num_train_epochs=1 , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , predict_with_generate=SCREAMING_SNAKE_CASE__ , do_train=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history if not do_eval: return __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats __lowerCamelCase = eval_metrics[-1] assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) assert not math.isnan(float(last_step_stats['''eval_loss'''] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def __A ( self : Optional[int] ) -> int: self.run_seqaseq_quick() @require_torch_multi_gpu def __A ( self : int ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @require_torch_multi_gpu def __A ( self : Optional[Any] ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Optional[int] ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple --fp16''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Tuple ) -> Any: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick( distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2 --fp16''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @require_apex @require_torch_gpu def __A ( self : Union[str, Any] ) -> List[str]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) @parameterized.expand(['''base''', '''low''', '''high''', '''mixed'''] ) @require_torch_multi_gpu def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout __lowerCamelCase = { # test with the default log_level - should be info and thus log info once '''base''': {'''extra_args_str''': '''''', '''n_matches''': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes '''low''': {'''extra_args_str''': '''--log_level debug --log_level_replica debug''', '''n_matches''': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica '''high''': {'''extra_args_str''': '''--log_level error --log_level_replica debug''', '''n_matches''': 1}, # test with high log_level and log_level_replica - should be quiet on all processes '''mixed''': {'''extra_args_str''': '''--log_level error --log_level_replica error''', '''n_matches''': 0}, } __lowerCamelCase = experiments[experiment_id] __lowerCamelCase = {'''distributed''': True, '''predict_with_generate''': False, '''do_eval''': False, '''do_predict''': False} __lowerCamelCase = '''Running training''' with CaptureStderr() as cl: self.run_seqaseq_quick(**SCREAMING_SNAKE_CASE__ , extra_args_str=data['''extra_args_str'''] ) __lowerCamelCase = len(re.findall(SCREAMING_SNAKE_CASE__ , cl.err ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ , data['''n_matches'''] ) @slow def __A ( self : Any ) -> Optional[Any]: __lowerCamelCase = self.run_trainer( eval_steps=2 , max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=10 , distributed=SCREAMING_SNAKE_CASE__ , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] __lowerCamelCase = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) # test if do_predict saves generations and metrics __lowerCamelCase = os.listdir(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {os.path.basename(SCREAMING_SNAKE_CASE__ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def __A ( self : Optional[int] ) -> str: from transformers.training_args import OptimizerNames def train_and_return_metrics(SCREAMING_SNAKE_CASE__ : str ) -> Tuple[int, float]: __lowerCamelCase = '''--skip_memory_metrics 0''' __lowerCamelCase = self.run_trainer( max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=1 , optim=SCREAMING_SNAKE_CASE__ , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , n_gpus_to_use=1 , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(Path(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = int(logs[0]['''train_mem_gpu_peaked_delta'''] / 2**20 ) __lowerCamelCase = int(logs[0]['''train_mem_gpu_alloc_delta'''] / 2**20 ) __lowerCamelCase = logs[0]['''train_loss'''] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) __lowerCamelCase = gpu_alloc_mem_orig - gpu_alloc_mem_bnb __lowerCamelCase = gpu_peak_mem_orig + gpu_alloc_mem_orig __lowerCamelCase = gpu_peak_mem_bnb + gpu_alloc_mem_bnb __lowerCamelCase = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings __lowerCamelCase = 1_20 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and''' f''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , ) self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less total gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and''' f''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , ) self.assertEqual( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , f'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = 3e-3 , SCREAMING_SNAKE_CASE__ : str = "adafactor" , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : int = None , ) -> List[Any]: __lowerCamelCase = self.test_file_dir / '''../fixtures/tests_samples/wmt_en_ro''' __lowerCamelCase = self.get_auto_remove_tmp_dir() __lowerCamelCase = f''' --model_name_or_path {model_name} --train_file {data_dir}/train.json --validation_file {data_dir}/val.json --test_file {data_dir}/test.json --output_dir {output_dir} --overwrite_output_dir --max_train_samples 8 --max_source_length {max_len} --max_target_length {max_len} --do_train --num_train_epochs {str(SCREAMING_SNAKE_CASE__ )} --per_device_train_batch_size 4 --learning_rate {learning_rate} --warmup_steps 8 --logging_steps 0 --logging_strategy no --save_steps {str(SCREAMING_SNAKE_CASE__ )} --group_by_length --label_smoothing_factor 0.1 --target_lang ro_RO --source_lang en_XX '''.split() __lowerCamelCase = f''' --do_eval --per_device_eval_batch_size 4 --max_eval_samples 8 --val_max_target_length {max_len} --evaluation_strategy steps --eval_steps {str(SCREAMING_SNAKE_CASE__ )} '''.split() __lowerCamelCase = ''' --do_predict '''.split() __lowerCamelCase = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f'''--optim {optim}'''.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: __lowerCamelCase = get_gpu_count() __lowerCamelCase = get_torch_dist_unique_port() __lowerCamelCase = f''' -m torch.distributed.run --nproc_per_node={n_gpus_to_use} --master_port={master_port} {self.examples_dir_str}/pytorch/translation/run_translation.py '''.split() __lowerCamelCase = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) else: __lowerCamelCase = ['''run_translation.py'''] + args with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): main() return output_dir
270
1
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowerCAmelCase__ : def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) __lowerCamelCase = img __lowerCamelCase = img.shape[1] __lowerCamelCase = img.shape[0] __lowerCamelCase = dst_width __lowerCamelCase = dst_height __lowerCamelCase = self.src_w / self.dst_w __lowerCamelCase = self.src_h / self.dst_h __lowerCamelCase = __lowerCamelCase = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def __A ( self : List[Any] ) -> str: for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase = self.img[self.get_y(SCREAMING_SNAKE_CASE__ )][self.get_x(SCREAMING_SNAKE_CASE__ )] def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_x * x ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_y * y ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = 800, 600 SCREAMING_SNAKE_CASE__ : int = imread("image_data/lena.jpg", 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
270
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__ : Dict = { "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__ : int = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowercase ): a__ : Any = """mask2former""" a__ : Dict = ["""swin"""] a__ : Any = {"""hidden_size""": """hidden_dim"""} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 20_48 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_55 , SCREAMING_SNAKE_CASE__ : int = 1_00 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_25_44 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 16, 32] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> str: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.''' ) __lowerCamelCase = CONFIG_MAPPING['''swin''']( image_size=2_24 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = backbone_config.pop('''model_type''' ) __lowerCamelCase = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # 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 )}''' ) __lowerCamelCase = backbone_config __lowerCamelCase = feature_size __lowerCamelCase = mask_feature_size __lowerCamelCase = hidden_dim __lowerCamelCase = encoder_feedforward_dim __lowerCamelCase = activation_function __lowerCamelCase = encoder_layers __lowerCamelCase = decoder_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = dropout __lowerCamelCase = dim_feedforward __lowerCamelCase = pre_norm __lowerCamelCase = enforce_input_projection __lowerCamelCase = common_stride __lowerCamelCase = ignore_value __lowerCamelCase = num_queries __lowerCamelCase = no_object_weight __lowerCamelCase = class_weight __lowerCamelCase = mask_weight __lowerCamelCase = dice_weight __lowerCamelCase = train_num_points __lowerCamelCase = oversample_ratio __lowerCamelCase = importance_sample_ratio __lowerCamelCase = init_std __lowerCamelCase = init_xavier_std __lowerCamelCase = use_auxiliary_loss __lowerCamelCase = feature_strides __lowerCamelCase = output_auxiliary_logits __lowerCamelCase = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def __A ( cls : Any , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Any ) -> Dict[str, any]: __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.backbone_config.to_dict() __lowerCamelCase = self.__class__.model_type return output
270
1
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__ : int = { "configuration_roformer": ["ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "RoFormerConfig", "RoFormerOnnxConfig"], "tokenization_roformer": ["RoFormerTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ["RoFormerTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "RoFormerForCausalLM", "RoFormerForMaskedLM", "RoFormerForMultipleChoice", "RoFormerForQuestionAnswering", "RoFormerForSequenceClassification", "RoFormerForTokenClassification", "RoFormerLayer", "RoFormerModel", "RoFormerPreTrainedModel", "load_tf_weights_in_roformer", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFRoFormerForCausalLM", "TFRoFormerForMaskedLM", "TFRoFormerForMultipleChoice", "TFRoFormerForQuestionAnswering", "TFRoFormerForSequenceClassification", "TFRoFormerForTokenClassification", "TFRoFormerLayer", "TFRoFormerModel", "TFRoFormerPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "FlaxRoFormerForMaskedLM", "FlaxRoFormerForMultipleChoice", "FlaxRoFormerForQuestionAnswering", "FlaxRoFormerForSequenceClassification", "FlaxRoFormerForTokenClassification", "FlaxRoFormerModel", "FlaxRoFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
import os def __magic_name__ ( ) -> str: __lowerCamelCase = os.path.join(os.path.dirname(__lowerCAmelCase ) , '''num.txt''' ) with open(__lowerCAmelCase ) as file_hand: return str(sum(int(__lowerCAmelCase ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
270
1
import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=32 , SCREAMING_SNAKE_CASE__ : int=3 , SCREAMING_SNAKE_CASE__ : Tuple=10 , SCREAMING_SNAKE_CASE__ : Optional[Any]=[10, 20, 30, 40] , SCREAMING_SNAKE_CASE__ : Dict=[1, 1, 2, 1] , SCREAMING_SNAKE_CASE__ : int=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : List[Any]="relu" , SCREAMING_SNAKE_CASE__ : List[Any]=3 , SCREAMING_SNAKE_CASE__ : List[str]=None , ) -> Tuple: __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = image_size __lowerCamelCase = num_channels __lowerCamelCase = embeddings_size __lowerCamelCase = hidden_sizes __lowerCamelCase = depths __lowerCamelCase = is_training __lowerCamelCase = use_labels __lowerCamelCase = hidden_act __lowerCamelCase = num_labels __lowerCamelCase = scope __lowerCamelCase = len(SCREAMING_SNAKE_CASE__ ) def __A ( self : List[str] ) -> Dict: __lowerCamelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowerCamelCase = self.get_config() return config, pixel_values def __A ( self : List[Any] ) -> Union[str, Any]: return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> int: __lowerCamelCase = FlaxRegNetModel(config=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple ) -> Union[str, Any]: __lowerCamelCase = self.num_labels __lowerCamelCase = FlaxRegNetForImageClassification(config=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self : Dict ) -> Any: __lowerCamelCase = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase = config_and_inputs __lowerCamelCase = {'''pixel_values''': pixel_values} return config, inputs_dict @require_flax class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : str = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () a__ : Tuple = False a__ : List[str] = False a__ : List[str] = False def __A ( self : Dict ) -> None: __lowerCamelCase = FlaxRegNetModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> int: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __A ( self : Dict ) -> Optional[Any]: return def __A ( self : Any ) -> Any: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict ) -> List[Any]: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason='''RegNet does not use inputs_embeds''' ) def __A ( self : Tuple ) -> List[str]: pass @unittest.skip(reason='''RegNet does not support input and output embeddings''' ) def __A ( self : List[Any] ) -> int: pass def __A ( self : List[str] ) -> int: __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase = model_class(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowerCamelCase = [*signature.parameters.keys()] __lowerCamelCase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[Any] ) -> Dict: def check_hidden_states_output(SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ): __lowerCamelCase = model_class(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __lowerCamelCase = self.model_tester.num_stages self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , expected_num_stages + 1 ) __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowerCamelCase = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __lowerCamelCase = True check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : str ) -> Optional[Any]: __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): __lowerCamelCase = self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model_class(SCREAMING_SNAKE_CASE__ ) @jax.jit def model_jitted(SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : Tuple ): return model(pixel_values=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with self.subTest('''JIT Enabled''' ): __lowerCamelCase = model_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): __lowerCamelCase = model_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(jitted_output.shape , output.shape ) def __magic_name__ ( ) -> Union[str, Any]: __lowerCamelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_flax class lowerCAmelCase__ ( unittest.TestCase ): @cached_property def __A ( self : str ) -> Dict: return AutoImageProcessor.from_pretrained('''facebook/regnet-y-040''' ) if is_vision_available() else None @slow def __A ( self : Tuple ) -> Optional[int]: __lowerCamelCase = FlaxRegNetForImageClassification.from_pretrained('''facebook/regnet-y-040''' ) __lowerCamelCase = self.default_image_processor __lowerCamelCase = prepare_img() __lowerCamelCase = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='''np''' ) __lowerCamelCase = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits __lowerCamelCase = (1, 10_00) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) )
270
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str a__ : List[str] a__ : Optional[List[str]] @dataclass class lowerCAmelCase__ : a__ : List[int] a__ : List[int] a__ : Optional[List[int]] = None a__ : Optional[List[int]] = None class lowerCAmelCase__ ( __lowercase ): a__ : Optional[Any] = """train""" a__ : Optional[int] = """dev""" a__ : Dict = """test""" class lowerCAmelCase__ : @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[Split, str] ) -> List[InputExample]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : str ) -> List[str]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : List[InputExample] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]="[CLS]" , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str="[SEP]" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : str=-1_00 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[Any]=True , ) -> List[InputFeatures]: __lowerCamelCase = {label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} __lowerCamelCase = [] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE__ ): if ex_index % 1_00_00 == 0: logger.info('''Writing example %d of %d''' , SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [] __lowerCamelCase = [] for word, label in zip(example.words , example.labels ): __lowerCamelCase = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE__ ) > 0: tokens.extend(SCREAMING_SNAKE_CASE__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __lowerCamelCase = tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE__ ) > max_seq_length - special_tokens_count: __lowerCamelCase = tokens[: (max_seq_length - special_tokens_count)] __lowerCamelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __lowerCamelCase = [sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __lowerCamelCase = [cls_token] + tokens __lowerCamelCase = [pad_token_label_id] + label_ids __lowerCamelCase = [cls_token_segment_id] + segment_ids __lowerCamelCase = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __lowerCamelCase = [1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE__ ) # Zero-pad up to the sequence length. __lowerCamelCase = max_seq_length - len(SCREAMING_SNAKE_CASE__ ) if pad_on_left: __lowerCamelCase = ([pad_token] * padding_length) + input_ids __lowerCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __lowerCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids __lowerCamelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , label_ids=SCREAMING_SNAKE_CASE__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowerCAmelCase__ ( __lowercase ): a__ : List[InputFeatures] a__ : int = nn.CrossEntropyLoss().ignore_index def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> Union[str, Any]: # Load data features from cache or dataset file __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __lowerCamelCase = cached_features_file + '''.lock''' with FileLock(SCREAMING_SNAKE_CASE__ ): if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) __lowerCamelCase = torch.load(SCREAMING_SNAKE_CASE__ ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , SCREAMING_SNAKE_CASE__ ) def __len__( self : Dict ) -> str: return len(self.features ) def __getitem__( self : Any , SCREAMING_SNAKE_CASE__ : Dict ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowerCAmelCase__ : a__ : List[InputFeatures] a__ : int = -100 def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> List[Any]: __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : List[Any] ) -> Any: return len(self.features ) def __getitem__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> InputFeatures: return self.features[i]
270
1
SCREAMING_SNAKE_CASE__ : List[Any] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def __magic_name__ ( __lowerCAmelCase : bytes ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): __lowerCamelCase = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(__lowerCAmelCase ) __lowerCamelCase = ''''''.join(bin(__lowerCAmelCase )[2:].zfill(8 ) for byte in data ) __lowerCamelCase = len(__lowerCAmelCase ) % 6 != 0 if padding_needed: # The padding that will be added later __lowerCamelCase = B'''=''' * ((6 - len(__lowerCAmelCase ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(__lowerCAmelCase ) % 6) else: __lowerCamelCase = B'''''' # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(__lowerCAmelCase ) , 6 ) ).encode() + padding ) def __magic_name__ ( __lowerCAmelCase : str ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) and not isinstance(__lowerCAmelCase , __lowerCAmelCase ): __lowerCamelCase = ( '''argument should be a bytes-like object or ASCII string, ''' f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(__lowerCAmelCase ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(__lowerCAmelCase , __lowerCAmelCase ): try: __lowerCamelCase = encoded_data.decode('''utf-8''' ) except UnicodeDecodeError: raise ValueError('''base64 encoded data should only contain ASCII characters''' ) __lowerCamelCase = encoded_data.count('''=''' ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(__lowerCAmelCase ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one __lowerCamelCase = encoded_data[:-padding] __lowerCamelCase = ''''''.join( bin(B64_CHARSET.index(__lowerCAmelCase ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: __lowerCamelCase = ''''''.join( bin(B64_CHARSET.index(__lowerCAmelCase ) )[2:].zfill(6 ) for char in encoded_data ) __lowerCamelCase = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(__lowerCAmelCase ) , 8 ) ] return bytes(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
270
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase__ ( __lowercase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : NestedDataStructureLike[PathLike] , SCREAMING_SNAKE_CASE__ : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE__ : Optional[Features] = None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : str , ) -> Union[str, Any]: super().__init__( SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ , streaming=SCREAMING_SNAKE_CASE__ , num_proc=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = path_or_paths if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else {self.split: path_or_paths} __lowerCamelCase = Text( cache_dir=SCREAMING_SNAKE_CASE__ , data_files=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : int ) -> Dict: # Build iterable dataset if self.streaming: __lowerCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE__ , download_mode=SCREAMING_SNAKE_CASE__ , verification_mode=SCREAMING_SNAKE_CASE__ , base_path=SCREAMING_SNAKE_CASE__ , num_proc=self.num_proc , ) __lowerCamelCase = self.builder.as_dataset( split=self.split , verification_mode=SCREAMING_SNAKE_CASE__ , in_memory=self.keep_in_memory ) return dataset
270
1
import requests def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str ) -> None: __lowerCamelCase = {'''Content-Type''': '''application/json'''} __lowerCamelCase = requests.post(__lowerCAmelCase , json={'''text''': message_body} , headers=__lowerCAmelCase ) if response.status_code != 200: __lowerCamelCase = ( '''Request to slack returned an error ''' f'''{response.status_code}, the response is:\n{response.text}''' ) raise ValueError(__lowerCAmelCase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
270
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
270
1
import argparse import json from collections import OrderedDict from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( SegformerConfig, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=False ) -> Any: __lowerCamelCase = OrderedDict() for key, value in state_dict.items(): if encoder_only and not key.startswith('''head''' ): __lowerCamelCase = '''segformer.encoder.''' + key if key.startswith('''backbone''' ): __lowerCamelCase = key.replace('''backbone''' , '''segformer.encoder''' ) if "patch_embed" in key: # replace for example patch_embed1 by patch_embeddings.0 __lowerCamelCase = key[key.find('''patch_embed''' ) + len('''patch_embed''' )] __lowerCamelCase = key.replace(f'''patch_embed{idx}''' , f'''patch_embeddings.{int(__lowerCAmelCase )-1}''' ) if "norm" in key: __lowerCamelCase = key.replace('''norm''' , '''layer_norm''' ) if "segformer.encoder.layer_norm" in key: # replace for example layer_norm1 by layer_norm.0 __lowerCamelCase = key[key.find('''segformer.encoder.layer_norm''' ) + len('''segformer.encoder.layer_norm''' )] __lowerCamelCase = key.replace(f'''layer_norm{idx}''' , f'''layer_norm.{int(__lowerCAmelCase )-1}''' ) if "layer_norm1" in key: __lowerCamelCase = key.replace('''layer_norm1''' , '''layer_norm_1''' ) if "layer_norm2" in key: __lowerCamelCase = key.replace('''layer_norm2''' , '''layer_norm_2''' ) if "block" in key: # replace for example block1 by block.0 __lowerCamelCase = key[key.find('''block''' ) + len('''block''' )] __lowerCamelCase = key.replace(f'''block{idx}''' , f'''block.{int(__lowerCAmelCase )-1}''' ) if "attn.q" in key: __lowerCamelCase = key.replace('''attn.q''' , '''attention.self.query''' ) if "attn.proj" in key: __lowerCamelCase = key.replace('''attn.proj''' , '''attention.output.dense''' ) if "attn" in key: __lowerCamelCase = key.replace('''attn''' , '''attention.self''' ) if "fc1" in key: __lowerCamelCase = key.replace('''fc1''' , '''dense1''' ) if "fc2" in key: __lowerCamelCase = key.replace('''fc2''' , '''dense2''' ) if "linear_pred" in key: __lowerCamelCase = key.replace('''linear_pred''' , '''classifier''' ) if "linear_fuse" in key: __lowerCamelCase = key.replace('''linear_fuse.conv''' , '''linear_fuse''' ) __lowerCamelCase = key.replace('''linear_fuse.bn''' , '''batch_norm''' ) if "linear_c" in key: # replace for example linear_c4 by linear_c.3 __lowerCamelCase = key[key.find('''linear_c''' ) + len('''linear_c''' )] __lowerCamelCase = key.replace(f'''linear_c{idx}''' , f'''linear_c.{int(__lowerCAmelCase )-1}''' ) if key.startswith('''head''' ): __lowerCamelCase = key.replace('''head''' , '''classifier''' ) __lowerCamelCase = value return new_state_dict def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ) -> int: # for each of the encoder blocks: for i in range(config.num_encoder_blocks ): for j in range(config.depths[i] ): # read in weights + bias of keys and values (which is a single matrix in the original implementation) __lowerCamelCase = state_dict.pop(f'''segformer.encoder.block.{i}.{j}.attention.self.kv.weight''' ) __lowerCamelCase = state_dict.pop(f'''segformer.encoder.block.{i}.{j}.attention.self.kv.bias''' ) # next, add keys and values (in that order) to the state dict __lowerCamelCase = kv_weight[ : config.hidden_sizes[i], : ] __lowerCamelCase = kv_bias[: config.hidden_sizes[i]] __lowerCamelCase = kv_weight[ config.hidden_sizes[i] :, : ] __lowerCamelCase = kv_bias[ config.hidden_sizes[i] : ] def __magic_name__ ( ) -> Dict: __lowerCamelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg''' __lowerCamelCase = Image.open(requests.get(__lowerCAmelCase , stream=__lowerCAmelCase ).raw ) return image @torch.no_grad() def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ) -> Dict: __lowerCamelCase = SegformerConfig() __lowerCamelCase = False # set attributes based on model_name __lowerCamelCase = '''huggingface/label-files''' if "segformer" in model_name: __lowerCamelCase = model_name[len('''segformer.''' ) : len('''segformer.''' ) + 2] if "ade" in model_name: __lowerCamelCase = 150 __lowerCamelCase = '''ade20k-id2label.json''' __lowerCamelCase = (1, 150, 128, 128) elif "city" in model_name: __lowerCamelCase = 19 __lowerCamelCase = '''cityscapes-id2label.json''' __lowerCamelCase = (1, 19, 128, 128) else: raise ValueError(f'''Model {model_name} not supported''' ) elif "mit" in model_name: __lowerCamelCase = True __lowerCamelCase = model_name[4:6] __lowerCamelCase = 1000 __lowerCamelCase = '''imagenet-1k-id2label.json''' __lowerCamelCase = (1, 1000) else: raise ValueError(f'''Model {model_name} not supported''' ) # set config attributes __lowerCamelCase = json.load(open(hf_hub_download(__lowerCAmelCase , __lowerCAmelCase , repo_type='''dataset''' ) , '''r''' ) ) __lowerCamelCase = {int(__lowerCAmelCase ): v for k, v in idalabel.items()} __lowerCamelCase = idalabel __lowerCamelCase = {v: k for k, v in idalabel.items()} if size == "b0": pass elif size == "b1": __lowerCamelCase = [64, 128, 320, 512] __lowerCamelCase = 256 elif size == "b2": __lowerCamelCase = [64, 128, 320, 512] __lowerCamelCase = 768 __lowerCamelCase = [3, 4, 6, 3] elif size == "b3": __lowerCamelCase = [64, 128, 320, 512] __lowerCamelCase = 768 __lowerCamelCase = [3, 4, 18, 3] elif size == "b4": __lowerCamelCase = [64, 128, 320, 512] __lowerCamelCase = 768 __lowerCamelCase = [3, 8, 27, 3] elif size == "b5": __lowerCamelCase = [64, 128, 320, 512] __lowerCamelCase = 768 __lowerCamelCase = [3, 6, 40, 3] else: raise ValueError(f'''Size {size} not supported''' ) # load image processor (only resize + normalize) __lowerCamelCase = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=__lowerCAmelCase , align=__lowerCAmelCase , do_random_crop=__lowerCAmelCase ) # prepare image __lowerCamelCase = prepare_img() __lowerCamelCase = image_processor(images=__lowerCAmelCase , return_tensors='''pt''' ).pixel_values logger.info(f'''Converting model {model_name}...''' ) # load original state dict if encoder_only: __lowerCamelCase = torch.load(__lowerCAmelCase , map_location=torch.device('''cpu''' ) ) else: __lowerCamelCase = torch.load(__lowerCAmelCase , map_location=torch.device('''cpu''' ) )['''state_dict'''] # rename keys __lowerCamelCase = rename_keys(__lowerCAmelCase , encoder_only=__lowerCAmelCase ) if not encoder_only: del state_dict["decode_head.conv_seg.weight"] del state_dict["decode_head.conv_seg.bias"] # key and value matrices need special treatment read_in_k_v(__lowerCAmelCase , __lowerCAmelCase ) # create HuggingFace model and load state dict if encoder_only: __lowerCamelCase = False __lowerCamelCase = SegformerForImageClassification(__lowerCAmelCase ) else: __lowerCamelCase = SegformerForSemanticSegmentation(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # forward pass __lowerCamelCase = model(__lowerCAmelCase ) __lowerCamelCase = outputs.logits # set expected_slice based on model name # ADE20k checkpoints if model_name == "segformer.b0.512x512.ade.160k": __lowerCamelCase = torch.tensor( [ [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]], [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]], [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]], ] ) elif model_name == "segformer.b1.512x512.ade.160k": __lowerCamelCase = torch.tensor( [ [[-7.5820, -8.7231, -8.3215], [-8.0600, -10.3529, -10.0304], [-7.5208, -9.4103, -9.6239]], [[-12.6918, -13.8994, -13.7137], [-13.3196, -15.7523, -15.4789], [-12.9343, -14.8757, -14.9689]], [[-11.1911, -11.9421, -11.3243], [-11.3342, -13.6839, -13.3581], [-10.3909, -12.1832, -12.4858]], ] ) elif model_name == "segformer.b2.512x512.ade.160k": __lowerCamelCase = torch.tensor( [ [[-11.8173, -14.3850, -16.3128], [-14.5648, -16.5804, -18.6568], [-14.7223, -15.7387, -18.4218]], [[-15.7290, -17.9171, -19.4423], [-18.3105, -19.9448, -21.4661], [-17.9296, -18.6497, -20.7910]], [[-15.0783, -17.0336, -18.2789], [-16.8771, -18.6870, -20.1612], [-16.2454, -17.1426, -19.5055]], ] ) elif model_name == "segformer.b3.512x512.ade.160k": __lowerCamelCase = torch.tensor( [ [[-9.0878, -10.2081, -10.1891], [-9.3144, -10.7941, -10.9843], [-9.2294, -10.3855, -10.5704]], [[-12.2316, -13.9068, -13.6102], [-12.9161, -14.3702, -14.3235], [-12.5233, -13.7174, -13.7932]], [[-14.6275, -15.2490, -14.9727], [-14.3400, -15.9687, -16.2827], [-14.1484, -15.4033, -15.8937]], ] ) elif model_name == "segformer.b4.512x512.ade.160k": __lowerCamelCase = torch.tensor( [ [[-12.3144, -13.2447, -14.0802], [-13.3614, -14.5816, -15.6117], [-13.3340, -14.4433, -16.2219]], [[-19.2781, -20.4128, -20.7506], [-20.6153, -21.6566, -22.0998], [-19.9800, -21.0430, -22.1494]], [[-18.8739, -19.7804, -21.1834], [-20.1233, -21.6765, -23.2944], [-20.0315, -21.2641, -23.6944]], ] ) elif model_name == "segformer.b5.640x640.ade.160k": __lowerCamelCase = torch.tensor( [ [[-9.5524, -12.0835, -11.7348], [-10.5229, -13.6446, -14.5662], [-9.5842, -12.8851, -13.9414]], [[-15.3432, -17.5323, -17.0818], [-16.3330, -18.9255, -19.2101], [-15.1340, -17.7848, -18.3971]], [[-12.6072, -14.9486, -14.6631], [-13.7629, -17.0907, -17.7745], [-12.7899, -16.1695, -17.1671]], ] ) # Cityscapes checkpoints elif model_name == "segformer.b0.1024x1024.city.160k": __lowerCamelCase = torch.tensor( [ [[-11.9295, -13.4057, -14.8106], [-13.3431, -14.8179, -15.3781], [-14.2836, -15.5942, -16.1588]], [[-11.4906, -12.8067, -13.6564], [-13.1189, -14.0500, -14.1543], [-13.8748, -14.5136, -14.8789]], [[0.5374, 0.1067, -0.4742], [0.1141, -0.2255, -0.7099], [-0.3000, -0.5924, -1.3105]], ] ) elif model_name == "segformer.b0.512x1024.city.160k": __lowerCamelCase = torch.tensor( [ [[-7.8217, -9.8767, -10.1717], [-9.4438, -10.9058, -11.4047], [-9.7939, -12.3495, -12.1079]], [[-7.1514, -9.5336, -10.0860], [-9.7776, -11.6822, -11.8439], [-10.1411, -12.7655, -12.8972]], [[0.3021, 0.0805, -0.2310], [-0.0328, -0.1605, -0.2714], [-0.1408, -0.5477, -0.6976]], ] ) elif model_name == "segformer.b0.640x1280.city.160k": __lowerCamelCase = torch.tensor( [ [ [-1.1372E01, -1.2787E01, -1.3477E01], [-1.2536E01, -1.4194E01, -1.4409E01], [-1.3217E01, -1.4888E01, -1.5327E01], ], [ [-1.4791E01, -1.7122E01, -1.8277E01], [-1.7163E01, -1.9192E01, -1.9533E01], [-1.7897E01, -1.9991E01, -2.0315E01], ], [ [7.6723E-01, 4.1921E-01, -7.7878E-02], [4.7772E-01, 9.5557E-03, -2.8082E-01], [3.6032E-01, -2.4826E-01, -5.1168E-01], ], ] ) elif model_name == "segformer.b0.768x768.city.160k": __lowerCamelCase = torch.tensor( [ [[-9.4959, -11.3087, -11.7479], [-11.0025, -12.6540, -12.3319], [-11.4064, -13.0487, -12.9905]], [[-9.8905, -11.3084, -12.0854], [-11.1726, -12.7698, -12.9583], [-11.5985, -13.3278, -14.1774]], [[0.2213, 0.0192, -0.2466], [-0.1731, -0.4213, -0.4874], [-0.3126, -0.6541, -1.1389]], ] ) elif model_name == "segformer.b1.1024x1024.city.160k": __lowerCamelCase = torch.tensor( [ [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]], [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]], [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]], ] ) elif model_name == "segformer.b2.1024x1024.city.160k": __lowerCamelCase = torch.tensor( [ [[-16.0976, -16.4856, -17.3962], [-16.6234, -19.0342, -19.7685], [-16.0900, -18.0661, -19.1180]], [[-18.4750, -18.8488, -19.5074], [-19.4030, -22.1570, -22.5977], [-19.1191, -20.8486, -22.3783]], [[-4.5178, -5.5037, -6.5109], [-5.0884, -7.2174, -8.0334], [-4.4156, -5.8117, -7.2970]], ] ) elif model_name == "segformer.b3.1024x1024.city.160k": __lowerCamelCase = torch.tensor( [ [[-14.2081, -14.4732, -14.1977], [-14.5867, -16.4423, -16.6356], [-13.4441, -14.9685, -16.8696]], [[-14.4576, -14.7073, -15.0451], [-15.0816, -17.6237, -17.9873], [-14.4213, -16.0199, -18.5992]], [[-4.7349, -4.9588, -5.0966], [-4.3210, -6.9325, -7.2591], [-3.4312, -4.7484, -7.1917]], ] ) elif model_name == "segformer.b4.1024x1024.city.160k": __lowerCamelCase = torch.tensor( [ [[-11.7737, -11.9526, -11.3273], [-13.6692, -14.4574, -13.8878], [-13.8937, -14.6924, -15.9345]], [[-14.6706, -14.5330, -14.1306], [-16.1502, -16.8180, -16.4269], [-16.8338, -17.8939, -20.1746]], [[1.0491, 0.8289, 1.0310], [1.1044, 0.5219, 0.8055], [1.0899, 0.6926, 0.5590]], ] ) elif model_name == "segformer.b5.1024x1024.city.160k": __lowerCamelCase = torch.tensor( [ [[-12.5641, -13.4777, -13.0684], [-13.9587, -15.8983, -16.6557], [-13.3109, -15.7350, -16.3141]], [[-14.7074, -15.4352, -14.5944], [-16.6353, -18.1663, -18.6120], [-15.1702, -18.0329, -18.1547]], [[-1.7990, -2.0951, -1.7784], [-2.6397, -3.8245, -3.9686], [-1.5264, -2.8126, -2.9316]], ] ) else: __lowerCamelCase = logits.argmax(-1 ).item() print('''Predicted class:''' , model.config.idalabel[predicted_class_idx] ) # verify logits if not encoder_only: assert logits.shape == expected_shape assert torch.allclose(logits[0, :3, :3, :3] , __lowerCAmelCase , atol=1E-2 ) # finally, save model and image processor logger.info(f'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) image_processor.save_pretrained(__lowerCAmelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( "--model_name", default="segformer.b0.512x512.ade.160k", type=str, help="Name of the model you'd like to convert.", ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original PyTorch checkpoint (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model." ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args() convert_segformer_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path)
270
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ : int = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : Dict ) -> Tuple: if version.parse(scb.__version__ ) < version.parse('''1.4.12''' ): raise ImportWarning( '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n''' '''You can install it with `pip install "sacrebleu>=1.4.12"`.''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf'''] , reference_urls=[ '''https://github.com/m-popovic/chrF''', ] , ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int = CHRF.CHAR_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.WORD_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.BETA , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Optional[Any]: __lowerCamelCase = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) __lowerCamelCase = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase = CHRF(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sb_chrf.corpus_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
270
1
def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str ) -> str: if not (isinstance(__lowerCAmelCase , __lowerCAmelCase ) and isinstance(__lowerCAmelCase , __lowerCAmelCase )): raise ValueError('''longest_common_substring() takes two strings for inputs''' ) __lowerCamelCase = len(__lowerCAmelCase ) __lowerCamelCase = len(__lowerCAmelCase ) __lowerCamelCase = [[0] * (texta_length + 1) for _ in range(texta_length + 1 )] __lowerCamelCase = 0 __lowerCamelCase = 0 for i in range(1 , texta_length + 1 ): for j in range(1 , texta_length + 1 ): if texta[i - 1] == texta[j - 1]: __lowerCamelCase = 1 + dp[i - 1][j - 1] if dp[i][j] > ans_length: __lowerCamelCase = i __lowerCamelCase = dp[i][j] return texta[ans_index - ans_length : ans_index] if __name__ == "__main__": import doctest doctest.testmod()
270
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
270
1
import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class lowerCAmelCase__ : def __init__( self : str , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str=13 , SCREAMING_SNAKE_CASE__ : Optional[int]=7 , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Tuple=99 , SCREAMING_SNAKE_CASE__ : Optional[Any]=64 , SCREAMING_SNAKE_CASE__ : Tuple=5 , SCREAMING_SNAKE_CASE__ : Tuple=4 , SCREAMING_SNAKE_CASE__ : Dict=37 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : List[str]=0.1 , SCREAMING_SNAKE_CASE__ : List[Any]=5_12 , SCREAMING_SNAKE_CASE__ : Optional[int]=16 , SCREAMING_SNAKE_CASE__ : Any=2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.02 , SCREAMING_SNAKE_CASE__ : List[Any]=3 , SCREAMING_SNAKE_CASE__ : Dict=4 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , ) -> Optional[int]: __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = seq_length __lowerCamelCase = is_training __lowerCamelCase = use_input_mask __lowerCamelCase = use_token_type_ids __lowerCamelCase = use_labels __lowerCamelCase = vocab_size __lowerCamelCase = hidden_size __lowerCamelCase = num_hidden_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = intermediate_size __lowerCamelCase = hidden_act __lowerCamelCase = hidden_dropout_prob __lowerCamelCase = attention_probs_dropout_prob __lowerCamelCase = max_position_embeddings __lowerCamelCase = type_vocab_size __lowerCamelCase = type_sequence_label_size __lowerCamelCase = initializer_range __lowerCamelCase = num_labels __lowerCamelCase = num_choices __lowerCamelCase = scope __lowerCamelCase = vocab_size - 1 def __A ( self : Any ) -> int: __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCamelCase = None if self.use_input_mask: __lowerCamelCase = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCamelCase = None if self.use_labels: __lowerCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCamelCase = self.get_config() return config, input_ids, input_mask, token_labels def __A ( self : Optional[Any] ) -> List[str]: return GPTNeoXConfig( 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=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , pad_token_id=self.pad_token_id , ) def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = self.prepare_config_and_inputs() __lowerCamelCase = True return config, input_ids, input_mask, token_labels def __A ( self : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : List[str] ) -> int: __lowerCamelCase = GPTNeoXModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> str: __lowerCamelCase = True __lowerCamelCase = GPTNeoXModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> int: __lowerCamelCase = GPTNeoXForCausalLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: __lowerCamelCase = self.num_labels __lowerCamelCase = GPTNeoXForQuestionAnswering(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Optional[int]: __lowerCamelCase = self.num_labels __lowerCamelCase = GPTNeoXForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: __lowerCamelCase = self.num_labels __lowerCamelCase = GPTNeoXForTokenClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : str ) -> Tuple: __lowerCamelCase = True __lowerCamelCase = GPTNeoXForCausalLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() # first forward pass __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __lowerCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size ) __lowerCamelCase = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __lowerCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 ) __lowerCamelCase = torch.cat([input_mask, next_mask] , dim=-1 ) __lowerCamelCase = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = output_from_no_past['''hidden_states'''][0] __lowerCamelCase = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , )['''hidden_states'''][0] # select random slice __lowerCamelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item() __lowerCamelCase = output_from_no_past[:, -3:, random_slice_idx].detach() __lowerCamelCase = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) def __A ( self : Optional[Any] ) -> Tuple: __lowerCamelCase = self.prepare_config_and_inputs() __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = config_and_inputs __lowerCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowerCAmelCase__ ( __lowercase , __lowercase , __lowercase , unittest.TestCase ): a__ : Optional[Any] = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) a__ : List[Any] = (GPTNeoXForCausalLM,) if is_torch_available() else () a__ : Dict = ( { """feature-extraction""": GPTNeoXModel, """question-answering""": GPTNeoXForQuestionAnswering, """text-classification""": GPTNeoXForSequenceClassification, """text-generation""": GPTNeoXForCausalLM, """token-classification""": GPTNeoXForTokenClassification, """zero-shot""": GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) a__ : Dict = False a__ : List[Any] = False a__ : int = False a__ : Union[str, Any] = False def __A ( self : Dict ) -> Optional[int]: __lowerCamelCase = GPTNeoXModelTester(self ) __lowerCamelCase = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=64 , num_attention_heads=8 ) def __A ( self : Dict ) -> Optional[Any]: self.config_tester.run_common_tests() def __A ( self : Tuple ) -> Dict: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[str] ) -> Any: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> Union[str, Any]: # This regression test was failing with PyTorch < 1.3 __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder() __lowerCamelCase = None self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict ) -> Dict: __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : int ) -> Union[str, Any]: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*SCREAMING_SNAKE_CASE__ ) def __A ( self : str ) -> Optional[Any]: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def __A ( self : Dict ) -> str: __lowerCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason='''Feed forward chunking is not implemented''' ) def __A ( self : Optional[int] ) -> int: pass @parameterized.expand([('''linear''',), ('''dynamic''',)] ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> int: __lowerCamelCase , __lowerCamelCase = self.model_tester.prepare_config_and_inputs_for_common() __lowerCamelCase = ids_tensor([1, 10] , config.vocab_size ) __lowerCamelCase = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __lowerCamelCase = GPTNeoXModel(SCREAMING_SNAKE_CASE__ ) original_model.to(SCREAMING_SNAKE_CASE__ ) original_model.eval() __lowerCamelCase = original_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state __lowerCamelCase = original_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __lowerCamelCase = {'''type''': scaling_type, '''factor''': 10.0} __lowerCamelCase = GPTNeoXModel(SCREAMING_SNAKE_CASE__ ) scaled_model.to(SCREAMING_SNAKE_CASE__ ) scaled_model.eval() __lowerCamelCase = scaled_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state __lowerCamelCase = scaled_model(SCREAMING_SNAKE_CASE__ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-5 ) ) else: self.assertFalse(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-5 ) ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): @slow def __A ( self : Any ) -> str: __lowerCamelCase = AutoTokenizer.from_pretrained('''EleutherAI/pythia-410m-deduped''' ) for checkpointing in [True, False]: __lowerCamelCase = GPTNeoXForCausalLM.from_pretrained('''EleutherAI/pythia-410m-deduped''' ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = tokenizer('''My favorite food is''' , return_tensors='''pt''' ).to(SCREAMING_SNAKE_CASE__ ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 __lowerCamelCase = '''My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI\'m not sure''' __lowerCamelCase = model.generate(**SCREAMING_SNAKE_CASE__ , do_sample=SCREAMING_SNAKE_CASE__ , max_new_tokens=20 ) __lowerCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ )[0] self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
270
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : str = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Tuple=18 , SCREAMING_SNAKE_CASE__ : int=30 , SCREAMING_SNAKE_CASE__ : Any=4_00 , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , ) -> Union[str, Any]: __lowerCamelCase = size if size is not None else {'''height''': 20, '''width''': 20} __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = num_channels __lowerCamelCase = image_size __lowerCamelCase = min_resolution __lowerCamelCase = max_resolution __lowerCamelCase = size __lowerCamelCase = do_normalize __lowerCamelCase = do_convert_rgb __lowerCamelCase = [5_12, 10_24, 20_48, 40_96] __lowerCamelCase = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def __A ( self : Union[str, Any] ) -> Union[str, Any]: return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __A ( self : int ) -> Any: __lowerCamelCase = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' __lowerCamelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Dict = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Optional[Any] ) -> List[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self ) @property def __A ( self : Optional[int] ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> Dict: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : int ) -> str: __lowerCamelCase = self.image_processor_tester.prepare_dummy_image() __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) __lowerCamelCase = 20_48 __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __A ( self : Union[str, Any] ) -> Dict: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Dict ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 __lowerCamelCase = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches __lowerCamelCase = '''Hello''' __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : List[str] ) -> Any: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Tuple ) -> List[str]: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Any = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self , num_channels=4 ) __lowerCamelCase = 3 @property def __A ( self : List[Any] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : Optional[int] ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
270
1
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__ ( __lowercase , __lowercase , unittest.TestCase ): a__ : Any = StableDiffusionPanoramaPipeline a__ : Any = TEXT_TO_IMAGE_PARAMS a__ : List[str] = TEXT_TO_IMAGE_BATCH_PARAMS a__ : Union[str, Any] = TEXT_TO_IMAGE_IMAGE_PARAMS a__ : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS def __A ( self : List[Any] ) -> str: torch.manual_seed(0 ) __lowerCamelCase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , ) __lowerCamelCase = DDIMScheduler() torch.manual_seed(0 ) __lowerCamelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) __lowerCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) __lowerCamelCase = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) __lowerCamelCase = { '''unet''': unet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int=0 ) -> int: __lowerCamelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''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 __A ( self : List[Any] ) -> List[Any]: __lowerCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase = np.array([0.6186, 0.5374, 0.4915, 0.4135, 0.4114, 0.4563, 0.5128, 0.4977, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : Optional[int] ) -> str: super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def __A ( self : Tuple ) -> Union[str, Any]: super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25e-3 ) def __A ( self : Optional[Any] ) -> List[str]: __lowerCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = '''french fries''' __lowerCamelCase = sd_pipe(**SCREAMING_SNAKE_CASE__ , negative_prompt=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = output.images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : Any ) -> Union[str, Any]: __lowerCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sd_pipe(**SCREAMING_SNAKE_CASE__ , view_batch_size=2 ) __lowerCamelCase = output.images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase = np.array([0.6187, 0.5375, 0.4915, 0.4136, 0.4114, 0.4563, 0.5128, 0.4976, 0.4757] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : Tuple ) -> List[Any]: __lowerCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = EulerAncestralDiscreteScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='''scaled_linear''' ) __lowerCamelCase = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase = np.array([0.4024, 0.6510, 0.4901, 0.5378, 0.5813, 0.5622, 0.4795, 0.4467, 0.4952] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __A ( self : List[Any] ) -> Any: __lowerCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator __lowerCamelCase = self.get_dummy_components() __lowerCamelCase = PNDMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , skip_prk_steps=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) __lowerCamelCase = np.array([0.6391, 0.6291, 0.4861, 0.5134, 0.5552, 0.4578, 0.5032, 0.5023, 0.4539] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Any ) -> List[str]: super().tearDown() gc.collect() torch.cuda.empty_cache() def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : str=0 ) -> List[str]: __lowerCamelCase = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = { '''prompt''': '''a photo of the dolomites''', '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def __A ( self : Union[str, Any] ) -> Dict: __lowerCamelCase = '''stabilityai/stable-diffusion-2-base''' __lowerCamelCase = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder='''scheduler''' ) __lowerCamelCase = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() __lowerCamelCase = self.get_inputs() __lowerCamelCase = pipe(**SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) __lowerCamelCase = np.array( [ 0.36968392, 0.27025372, 0.32446766, 0.28379387, 0.36363274, 0.30733347, 0.27100027, 0.27054125, 0.25536096, ] ) assert np.abs(expected_slice - image_slice ).max() < 1e-2 def __A ( self : List[str] ) -> Tuple: __lowerCamelCase = StableDiffusionPanoramaPipeline.from_pretrained( '''stabilityai/stable-diffusion-2-base''' , safety_checker=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() __lowerCamelCase = self.get_inputs() __lowerCamelCase = pipe(**SCREAMING_SNAKE_CASE__ ).images __lowerCamelCase = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 5_12, 20_48, 3) __lowerCamelCase = 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 __A ( self : Tuple ) -> int: __lowerCamelCase = 0 def callback_fn(SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : torch.FloatTensor ) -> None: __lowerCamelCase = True nonlocal number_of_steps number_of_steps += 1 if step == 1: __lowerCamelCase = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) __lowerCamelCase = latents[0, -3:, -3:, -1] __lowerCamelCase = np.array( [ 0.18681869, 0.33907816, 0.5361276, 0.14432865, -0.02856611, -0.73941123, 0.23397987, 0.47322682, -0.37823164, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: __lowerCamelCase = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 2_56) __lowerCamelCase = latents[0, -3:, -3:, -1] __lowerCamelCase = np.array( [ 0.18539645, 0.33987248, 0.5378559, 0.14437142, -0.02455261, -0.7338317, 0.23990755, 0.47356272, -0.3786505, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 __lowerCamelCase = False __lowerCamelCase = '''stabilityai/stable-diffusion-2-base''' __lowerCamelCase = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder='''scheduler''' ) __lowerCamelCase = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() __lowerCamelCase = self.get_inputs() pipe(**SCREAMING_SNAKE_CASE__ , callback=SCREAMING_SNAKE_CASE__ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __A ( self : Union[str, Any] ) -> List[Any]: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __lowerCamelCase = '''stabilityai/stable-diffusion-2-base''' __lowerCamelCase = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder='''scheduler''' ) __lowerCamelCase = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() __lowerCamelCase = self.get_inputs() __lowerCamelCase = pipe(**SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
270
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class lowerCAmelCase__ ( __lowercase ): def __init__( self : int ) -> Optional[int]: __lowerCamelCase = [] def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: self.events.append('''on_init_end''' ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: self.events.append('''on_train_begin''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Any: self.events.append('''on_train_end''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: self.events.append('''on_epoch_begin''' ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: self.events.append('''on_epoch_end''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.events.append('''on_step_begin''' ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: self.events.append('''on_step_end''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: self.events.append('''on_evaluate''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : str ) -> str: self.events.append('''on_predict''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: self.events.append('''on_save''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: self.events.append('''on_log''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: self.events.append('''on_prediction_step''' ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = tempfile.mkdtemp() def __A ( self : int ) -> List[str]: shutil.rmtree(self.output_dir ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Any=0 , SCREAMING_SNAKE_CASE__ : List[str]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[int]=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionModelConfig(a=SCREAMING_SNAKE_CASE__ , b=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionPreTrainedModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = TrainingArguments(self.output_dir , disable_tqdm=SCREAMING_SNAKE_CASE__ , report_to=[] , **SCREAMING_SNAKE_CASE__ ) return Trainer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , callbacks=SCREAMING_SNAKE_CASE__ , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) # Order doesn't matter __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) for cba, cba in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , cba.__class__ ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(cba.__class__ , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: __lowerCamelCase = ['''on_init_end''', '''on_train_begin'''] __lowerCamelCase = 0 __lowerCamelCase = len(trainer.get_eval_dataloader() ) __lowerCamelCase = ['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append('''on_epoch_begin''' ) for _ in range(SCREAMING_SNAKE_CASE__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('''on_log''' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('''on_save''' ) expected_events.append('''on_epoch_end''' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = self.get_trainer() __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # Callbacks passed at init are added to the default callbacks __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback __lowerCamelCase = self.get_trainer(disable_tqdm=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> str: __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] __lowerCamelCase = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(cb.__class__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # We can also add, pop, or remove by instance __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> Any: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='''ignore''' , category=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # Independent log/save/eval __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='''steps''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='''epoch''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # A bit of everything __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy='''steps''' , ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # warning should be emitted for duplicated callbacks with patch('''transformers.trainer_callback.logger.warning''' ) as warn_mock: __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(SCREAMING_SNAKE_CASE__ ) in warn_mock.call_args[0][0]
270
1
import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def _a ( *a :Optional[Any] , a :Optional[Union[Dict, Any]] = None , a :List[str]=True , a :List[str]=2 ) -> int: from .. import __version__ a = take_from a = () if not isinstance(args[0] , a ): a = (args,) for attribute, version_name, message in args: if version.parse(version.parse(a ).base_version ) >= version.parse(a ): raise ValueError( F"""The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'""" F""" version {__version__} is >= {version_name}""" ) a = None if isinstance(a , a ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(a ),) a = F"""The `{attribute}` argument is deprecated and will be removed in version {version_name}.""" elif hasattr(a , a ): values += (getattr(a , a ),) a = F"""The `{attribute}` attribute is deprecated and will be removed in version {version_name}.""" elif deprecated_kwargs is None: a = F"""`{attribute}` is deprecated and will be removed in version {version_name}.""" if warning is not None: a = warning + ''' ''' if standard_warn else '''''' warnings.warn(warning + message , a , stacklevel=a ) if isinstance(a , a ) and len(a ) > 0: a = inspect.getouterframes(inspect.currentframe() )[1] a = call_frame.filename a = call_frame.lineno a = call_frame.function a , a = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F"""{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`""" ) if len(a ) == 0: return elif len(a ) == 1: return values[0] return values
0
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowerCAmelCase__ : def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) __lowerCamelCase = img __lowerCamelCase = img.shape[1] __lowerCamelCase = img.shape[0] __lowerCamelCase = dst_width __lowerCamelCase = dst_height __lowerCamelCase = self.src_w / self.dst_w __lowerCamelCase = self.src_h / self.dst_h __lowerCamelCase = __lowerCamelCase = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def __A ( self : List[Any] ) -> str: for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase = self.img[self.get_y(SCREAMING_SNAKE_CASE__ )][self.get_x(SCREAMING_SNAKE_CASE__ )] def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_x * x ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_y * y ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = 800, 600 SCREAMING_SNAKE_CASE__ : int = imread("image_data/lena.jpg", 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
270
0
'''simple docstring''' from ...processing_utils import ProcessorMixin class __A ( UpperCamelCase__ ): a__ : Dict = ["""image_processor""", """feature_extractor"""] a__ : List[str] = """TvltImageProcessor""" a__ : Tuple = """TvltFeatureExtractor""" def __init__(self : Tuple , __a : List[str] , __a : List[Any] ): super().__init__(image_processor=__a , feature_extractor=__a ) UpperCAmelCase_ = image_processor UpperCAmelCase_ = feature_extractor def __call__(self : Dict , __a : Dict=None , __a : Union[str, Any]=None , __a : str=None , __a : List[str]=None , __a : Tuple=False , __a : Dict=False , *__a : Optional[int] , **__a : List[Any] , ): if images is None and audio is None: raise ValueError("You need to specify either an `images` or `audio` input to process." ) UpperCAmelCase_ = None if images is not None: UpperCAmelCase_ = self.image_processor(__a , mask_pixel=__a , *__a , **__a ) if images_mixed is not None: UpperCAmelCase_ = self.image_processor(__a , is_mixed=__a , *__a , **__a ) if audio is not None: UpperCAmelCase_ = self.feature_extractor( __a , *__a , sampling_rate=__a , mask_audio=__a , **__a ) UpperCAmelCase_ = {} if audio is not None: output_dict.update(__a ) if images is not None: output_dict.update(__a ) if images_mixed_dict is not None: output_dict.update(__a ) return output_dict @property def _lowercase (self : Any ): UpperCAmelCase_ = self.image_processor.model_input_names UpperCAmelCase_ = self.feature_extractor.model_input_names return list(dict.fromkeys(image_processor_input_names + feature_extractor_input_names ) )
1
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( __lowerCAmelCase : dict , __lowerCAmelCase : str , __lowerCAmelCase : set , __lowerCAmelCase : set , __lowerCAmelCase : dict , __lowerCAmelCase : dict , __lowerCAmelCase : PriorityQueue , __lowerCAmelCase : dict , __lowerCAmelCase : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCamelCase = cst_fwd.get(__lowerCAmelCase , np.inf ) __lowerCamelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCamelCase = new_cost_f __lowerCamelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCamelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : dict , __lowerCAmelCase : dict ) -> int: __lowerCamelCase = -1 __lowerCamelCase = set() __lowerCamelCase = set() __lowerCamelCase = {source: 0} __lowerCamelCase = {destination: 0} __lowerCamelCase = {source: None} __lowerCamelCase = {destination: None} __lowerCamelCase = PriorityQueue() __lowerCamelCase = PriorityQueue() __lowerCamelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCamelCase , __lowerCamelCase = queue_forward.get() visited_forward.add(__lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = queue_backward.get() visited_backward.add(__lowerCAmelCase ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCamelCase = shortest_distance return shortest_path_distance SCREAMING_SNAKE_CASE__ : List[Any] = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } SCREAMING_SNAKE_CASE__ : Optional[int] = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
270
0
'''simple docstring''' def _SCREAMING_SNAKE_CASE (A = 1_000 ) -> int: """simple docstring""" return sum(e for e in range(3 , A ) if e % 3 == 0 or e % 5 == 0 ) if __name__ == "__main__": print(f"""{solution() = }""")
2
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : List[Any] = TypeVar("T") def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (position - 1) // 2 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 1 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 2 class lowerCAmelCase__ ( Generic[T] ): def __init__( self : List[str] ) -> None: __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 def __len__( self : Optional[int] ) -> int: return self.elements def __repr__( self : Optional[int] ) -> str: return str(self.heap ) def __A ( self : Union[str, Any] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def __A ( self : str , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __lowerCamelCase = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __lowerCamelCase , __lowerCamelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowerCamelCase , __lowerCamelCase = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Update the weight of the given key __lowerCamelCase = self.position_map[elem] __lowerCamelCase = (elem, weight) if position > 0: __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __lowerCamelCase = self.position_map[elem] if curr_pos == 0: return None __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __lowerCamelCase = self.position_map[elem] __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: # Swap the nodes at the given positions __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase , __lowerCamelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowerCamelCase = nodea_pos __lowerCamelCase = nodea_pos class lowerCAmelCase__ ( Generic[T] ): def __init__( self : Tuple ) -> None: __lowerCamelCase = {} __lowerCamelCase = 0 def __repr__( self : Optional[int] ) -> str: return str(self.connections ) def __len__( self : List[str] ) -> int: return self.nodes def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __lowerCamelCase = {} self.nodes += 1 def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = weight __lowerCamelCase = weight def __magic_name__ ( __lowerCAmelCase : GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: __lowerCamelCase = {node: maxsize for node in graph.connections} __lowerCamelCase = {node: None for node in graph.connections} __lowerCamelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__lowerCAmelCase , __lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization __lowerCamelCase = priority_queue.extract_min() __lowerCamelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node # running prim's algorithm while not priority_queue.is_empty(): __lowerCamelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node return dist, parent
270
0
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case__ , snake_case__ ): '''simple docstring''' if len(snake_case__ ) < k or k < 0: raise ValueError('''Invalid Input''' ) A : Any = sum(array[:k] ) for i in range(len(snake_case__ ) - k ): A : Union[str, Any] = current_sum - array[i] + array[i + k] A : List[Any] = max(snake_case__ , snake_case__ ) return max_sum if __name__ == "__main__": from doctest import testmod from random import randint testmod() lowercase : int = [randint(-10_00, 10_00) for i in range(1_00)] lowercase : List[str] = randint(0, 1_10) print(f'''The maximum sum of {k} consecutive elements is {max_sum_in_array(array,k)}''')
3
from __future__ import annotations from statistics import mean def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> list[int]: __lowerCamelCase = [0] * no_of_processes __lowerCamelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] __lowerCamelCase = [] __lowerCamelCase = 0 __lowerCamelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCamelCase = [] __lowerCamelCase = -1 for i in range(__lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: __lowerCamelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCamelCase = i total_time += burst_time[target_process] completed += 1 __lowerCamelCase = 0 __lowerCamelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : int , __lowerCAmelCase : list[int] ) -> list[int]: __lowerCamelCase = [0] * no_of_processes for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") SCREAMING_SNAKE_CASE__ : Tuple = 4 SCREAMING_SNAKE_CASE__ : Optional[int] = [2, 5, 3, 7] SCREAMING_SNAKE_CASE__ : List[str] = [0, 0, 0, 0] SCREAMING_SNAKE_CASE__ : str = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( F'{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t' F'{waiting_time[i]}\t\t\t\t{turn_around_time[i]}' ) print(F'\nAverage waiting time = {mean(waiting_time):.5f}') print(F'Average turnaround time = {mean(turn_around_time):.5f}')
270
0
'''simple docstring''' def a_ ( lowerCamelCase : str ): return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
4
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( __lowercase ): @staticmethod @abstractmethod def __A ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> str: raise NotImplementedError() @abstractmethod def __A ( self : Optional[int] ) -> Union[str, Any]: raise NotImplementedError()
270
0
import sys from typing import Tuple import numpy as np import torch from PIL import Image from torch import nn from transformers.image_utils import PILImageResampling from utils import img_tensorize class lowerCamelCase__ : def __init__(self , UpperCAmelCase , UpperCAmelCase=sys.maxsize ) -> str: _lowercase ='''bilinear''' _lowercase =max_size _lowercase =short_edge_length def __call__(self , UpperCAmelCase ) -> int: _lowercase =[] for img in imgs: _lowercase , _lowercase =img.shape[:2] # later: provide list and randomly choose index for resize _lowercase =np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 ) if size == 0: return img _lowercase =size * 1.0 / min(UpperCAmelCase , UpperCAmelCase ) if h < w: _lowercase , _lowercase =size, scale * w else: _lowercase , _lowercase =scale * h, size if max(UpperCAmelCase , UpperCAmelCase ) > self.max_size: _lowercase =self.max_size * 1.0 / max(UpperCAmelCase , UpperCAmelCase ) _lowercase =newh * scale _lowercase =neww * scale _lowercase =int(neww + 0.5 ) _lowercase =int(newh + 0.5 ) if img.dtype == np.uinta: _lowercase =Image.fromarray(UpperCAmelCase ) _lowercase =pil_image.resize((neww, newh) , PILImageResampling.BILINEAR ) _lowercase =np.asarray(UpperCAmelCase ) else: _lowercase =img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw _lowercase =nn.functional.interpolate( UpperCAmelCase , (newh, neww) , mode=self.interp_method , align_corners=UpperCAmelCase ).squeeze(0 ) img_augs.append(UpperCAmelCase ) return img_augs class lowerCamelCase__ : def __init__(self , UpperCAmelCase ) -> Tuple: _lowercase =ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST ) _lowercase =cfg.INPUT.FORMAT _lowercase =cfg.SIZE_DIVISIBILITY _lowercase =cfg.PAD_VALUE _lowercase =cfg.INPUT.MAX_SIZE_TEST _lowercase =cfg.MODEL.DEVICE _lowercase =torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) _lowercase =torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 ) _lowercase =lambda UpperCAmelCase : (x - self.pixel_mean) / self.pixel_std def __A (self , UpperCAmelCase ) -> List[str]: _lowercase =tuple(max(UpperCAmelCase ) for s in zip(*[img.shape for img in images] ) ) _lowercase =[im.shape[-2:] for im in images] _lowercase =[ nn.functional.pad( UpperCAmelCase , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , ) for size, im in zip(UpperCAmelCase , UpperCAmelCase ) ] return torch.stack(UpperCAmelCase ), torch.tensor(UpperCAmelCase ) def __call__(self , UpperCAmelCase , UpperCAmelCase=False ) -> str: with torch.no_grad(): if not isinstance(UpperCAmelCase , UpperCAmelCase ): _lowercase =[images] if single_image: assert len(UpperCAmelCase ) == 1 for i in range(len(UpperCAmelCase ) ): if isinstance(images[i] , torch.Tensor ): images.insert(UpperCAmelCase , images.pop(UpperCAmelCase ).to(self.device ).float() ) elif not isinstance(images[i] , torch.Tensor ): images.insert( UpperCAmelCase , torch.as_tensor(img_tensorize(images.pop(UpperCAmelCase ) , input_format=self.input_format ) ) .to(self.device ) .float() , ) # resize smallest edge _lowercase =torch.tensor([im.shape[:2] for im in images] ) _lowercase =self.aug(UpperCAmelCase ) # transpose images and convert to torch tensors # images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images] # now normalize before pad to avoid useless arithmetic _lowercase =[self.normalizer(UpperCAmelCase ) for x in images] # now pad them to do the following operations _lowercase , _lowercase =self.pad(UpperCAmelCase ) # Normalize if self.size_divisibility > 0: raise NotImplementedError() # pad _lowercase =torch.true_divide(UpperCAmelCase , UpperCAmelCase ) if single_image: return images[0], sizes[0], scales_yx[0] else: return images, sizes, scales_yx def UpperCAmelCase_ ( __snake_case , __snake_case ) -> Tuple: """simple docstring""" boxes[:, 0::2] *= scale_yx[:, 1] boxes[:, 1::2] *= scale_yx[:, 0] return boxes def UpperCAmelCase_ ( __snake_case , __snake_case ) -> Optional[int]: """simple docstring""" assert torch.isfinite(__snake_case ).all(), "Box tensor contains infinite or NaN!" _lowercase , _lowercase =box_size tensor[:, 0].clamp_(min=0 , max=__snake_case ) tensor[:, 1].clamp_(min=0 , max=__snake_case ) tensor[:, 2].clamp_(min=0 , max=__snake_case ) tensor[:, 3].clamp_(min=0 , max=__snake_case )
5
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue_model_parallelism.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> List[Any]: if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=SCREAMING_SNAKE_CASE__ , ) assert hasattr(self , '''env''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: # configuration for running training on smdistributed Model Parallel __lowerCamelCase = { '''enabled''': True, '''processes_per_host''': 8, } __lowerCamelCase = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __lowerCamelCase = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __lowerCamelCase = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=SCREAMING_SNAKE_CASE__ , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE__ , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 5_00, } , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE__ , py_version='''py36''' , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: TrainingJobAnalytics(SCREAMING_SNAKE_CASE__ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: # create estimator __lowerCamelCase = self.create_estimator(SCREAMING_SNAKE_CASE__ ) # run training estimator.fit() # result dataframe __lowerCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # 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} , SCREAMING_SNAKE_CASE__ )
270
0
from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class __A( nn.Module ): def __init__( self , _snake_case = 16 , _snake_case = 88 , _snake_case = None , _snake_case = 1 , _snake_case = 0.0 , _snake_case = 32 , _snake_case = None , _snake_case = False , _snake_case = None , _snake_case = None , _snake_case = "geglu" , _snake_case = None , ) -> Any: '''simple docstring''' super().__init__() __a = nn.ModuleList( [ TransformeraDModel( num_attention_heads=_snake_case , attention_head_dim=_snake_case , in_channels=_snake_case , num_layers=_snake_case , dropout=_snake_case , norm_num_groups=_snake_case , cross_attention_dim=_snake_case , attention_bias=_snake_case , sample_size=_snake_case , num_vector_embeds=_snake_case , activation_fn=_snake_case , num_embeds_ada_norm=_snake_case , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference __a = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` __a = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` __a = [1, 0] def SCREAMING_SNAKE_CASE_ ( self , _snake_case , _snake_case , _snake_case=None , _snake_case=None , _snake_case=None , _snake_case = True , ) -> Tuple: '''simple docstring''' __a = hidden_states __a = [] __a = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens __a = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] __a = self.transformer_index_for_condition[i] __a = self.transformers[transformer_index]( _snake_case , encoder_hidden_states=_snake_case , timestep=_snake_case , cross_attention_kwargs=_snake_case , return_dict=_snake_case , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] __a = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) __a = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=_snake_case )
6
from __future__ import annotations from fractions import Fraction def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def __magic_name__ ( __lowerCAmelCase : int ) -> list[str]: __lowerCamelCase = [] __lowerCamelCase = 11 __lowerCamelCase = int('''1''' + '''0''' * digit_len ) for num in range(__lowerCAmelCase , __lowerCAmelCase ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(__lowerCAmelCase , __lowerCAmelCase ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 __lowerCamelCase = 10 return solutions def __magic_name__ ( __lowerCAmelCase : int = 2 ) -> int: __lowerCamelCase = 1.0 for fraction in fraction_list(__lowerCAmelCase ): __lowerCamelCase = Fraction(__lowerCAmelCase ) result *= frac.denominator / frac.numerator return int(__lowerCAmelCase ) if __name__ == "__main__": print(solution())
270
0
def _snake_case( SCREAMING_SNAKE_CASE__ : str ) -> Dict: '''simple docstring''' A__ = [] A__ = [] A__ = { '^': 3, '*': 2, '/': 2, '%': 2, '+': 1, '-': 1, } # Priority of each operator A__ = len(SCREAMING_SNAKE_CASE__ ) if (len(SCREAMING_SNAKE_CASE__ ) > 7) else 7 # Print table header for output print( 'Symbol'.center(8 ) , 'Stack'.center(SCREAMING_SNAKE_CASE__ ) , 'Postfix'.center(SCREAMING_SNAKE_CASE__ ) , sep=' | ' , ) print('-' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(SCREAMING_SNAKE_CASE__ ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(SCREAMING_SNAKE_CASE__ ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(SCREAMING_SNAKE_CASE__ ) == 0: stack.append(SCREAMING_SNAKE_CASE__ ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(SCREAMING_SNAKE_CASE__ ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(SCREAMING_SNAKE_CASE__ ) # push x to stack print( x.center(8 ) , (''.join(SCREAMING_SNAKE_CASE__ )).ljust(SCREAMING_SNAKE_CASE__ ) , (''.join(SCREAMING_SNAKE_CASE__ )).ljust(SCREAMING_SNAKE_CASE__ ) , sep=' | ' , ) # Output in tabular format while len(SCREAMING_SNAKE_CASE__ ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ' '.center(8 ) , (''.join(SCREAMING_SNAKE_CASE__ )).ljust(SCREAMING_SNAKE_CASE__ ) , (''.join(SCREAMING_SNAKE_CASE__ )).ljust(SCREAMING_SNAKE_CASE__ ) , sep=' | ' , ) # Output in tabular format return "".join(SCREAMING_SNAKE_CASE__ ) # return Postfix as str def _snake_case( SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: '''simple docstring''' A__ = list(infix[::-1] ) # reverse the infix equation for i in range(len(SCREAMING_SNAKE_CASE__ ) ): if infix[i] == "(": A__ = ')' # change "(" to ")" elif infix[i] == ")": A__ = '(' # change ")" to "(" return (infix_2_postfix(''.join(SCREAMING_SNAKE_CASE__ ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": lowercase_ = input("\nEnter an Infix Equation = ") # Input an Infix equation lowercase_ = "".join(Infix.split()) # Remove spaces from the input print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
7
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipTextConfig", "BlipVisionConfig", ], "processing_blip": ["BlipProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = ["BlipImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipModel", "BlipPreTrainedModel", "BlipForConditionalGeneration", "BlipForQuestionAnswering", "BlipVisionModel", "BlipTextModel", "BlipForImageTextRetrieval", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBlipModel", "TFBlipPreTrainedModel", "TFBlipForConditionalGeneration", "TFBlipForQuestionAnswering", "TFBlipVisionModel", "TFBlipTextModel", "TFBlipForImageTextRetrieval", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class snake_case_ ( nn.Module ): '''simple docstring''' def __init__( self : Dict , _UpperCamelCase : int = 1_6 , _UpperCamelCase : int = 8_8 , _UpperCamelCase : Optional[int] = None , _UpperCamelCase : int = 1 , _UpperCamelCase : float = 0.0 , _UpperCamelCase : int = 3_2 , _UpperCamelCase : Optional[int] = None , _UpperCamelCase : bool = False , _UpperCamelCase : Optional[int] = None , _UpperCamelCase : Optional[int] = None , _UpperCamelCase : str = "geglu" , _UpperCamelCase : Optional[int] = None , ) ->Any: super().__init__() snake_case_ = nn.ModuleList( [ TransformeraDModel( num_attention_heads=_UpperCamelCase , attention_head_dim=_UpperCamelCase , in_channels=_UpperCamelCase , num_layers=_UpperCamelCase , dropout=_UpperCamelCase , norm_num_groups=_UpperCamelCase , cross_attention_dim=_UpperCamelCase , attention_bias=_UpperCamelCase , sample_size=_UpperCamelCase , num_vector_embeds=_UpperCamelCase , activation_fn=_UpperCamelCase , num_embeds_ada_norm=_UpperCamelCase , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference snake_case_ = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` snake_case_ = [7_7, 2_5_7] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` snake_case_ = [1, 0] def snake_case__( self : Dict , _UpperCamelCase : str , _UpperCamelCase : str , _UpperCamelCase : Optional[Any]=None , _UpperCamelCase : List[Any]=None , _UpperCamelCase : List[str]=None , _UpperCamelCase : bool = True , ) ->Optional[Any]: snake_case_ = hidden_states snake_case_ = [] snake_case_ = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens snake_case_ = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] snake_case_ = self.transformer_index_for_condition[i] snake_case_ = self.transformers[transformer_index]( _UpperCamelCase , encoder_hidden_states=_UpperCamelCase , timestep=_UpperCamelCase , cross_attention_kwargs=_UpperCamelCase , return_dict=_UpperCamelCase , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] snake_case_ = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) snake_case_ = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=_UpperCamelCase )
8
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class _lowercase ( A__ ): '''simple docstring''' def __init__( self :int , lowerCAmelCase__ :Union[str, "sqlalchemy.sql.Selectable"] , lowerCAmelCase__ :Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , lowerCAmelCase__ :Optional[Features] = None , lowerCAmelCase__ :str = None , lowerCAmelCase__ :bool = False , **lowerCAmelCase__ :Union[str, Any] , ) -> Optional[int]: super().__init__(features=lowerCAmelCase__ , cache_dir=lowerCAmelCase__ , keep_in_memory=lowerCAmelCase__ , **lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Any = Sql( cache_dir=lowerCAmelCase__ , features=lowerCAmelCase__ , sql=lowerCAmelCase__ , con=lowerCAmelCase__ , **lowerCAmelCase__ , ) def __magic_name__( self :List[Any] ) -> Union[str, Any]: __SCREAMING_SNAKE_CASE : Optional[int] = None __SCREAMING_SNAKE_CASE : int = None __SCREAMING_SNAKE_CASE : Optional[Any] = None __SCREAMING_SNAKE_CASE : Dict = None self.builder.download_and_prepare( download_config=lowerCAmelCase__ , download_mode=lowerCAmelCase__ , verification_mode=lowerCAmelCase__ , base_path=lowerCAmelCase__ , ) # Build dataset for splits __SCREAMING_SNAKE_CASE : List[Any] = self.builder.as_dataset( split='''train''' , verification_mode=lowerCAmelCase__ , in_memory=self.keep_in_memory ) return dataset class _lowercase : '''simple docstring''' def __init__( self :int , lowerCAmelCase__ :Dataset , lowerCAmelCase__ :str , lowerCAmelCase__ :Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] , lowerCAmelCase__ :Optional[int] = None , lowerCAmelCase__ :Optional[int] = None , **lowerCAmelCase__ :Union[str, Any] , ) -> int: if num_proc is not None and num_proc <= 0: raise ValueError(f'''num_proc {num_proc} must be an integer > 0.''' ) __SCREAMING_SNAKE_CASE : List[Any] = dataset __SCREAMING_SNAKE_CASE : Tuple = name __SCREAMING_SNAKE_CASE : Optional[Any] = con __SCREAMING_SNAKE_CASE : Union[str, Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE __SCREAMING_SNAKE_CASE : List[Any] = num_proc __SCREAMING_SNAKE_CASE : Optional[int] = to_sql_kwargs def __magic_name__( self :Tuple ) -> int: __SCREAMING_SNAKE_CASE : Optional[int] = self.to_sql_kwargs.pop('''sql''' , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : Optional[int] = self.to_sql_kwargs.pop('''con''' , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : int = self.to_sql_kwargs.pop('''index''' , lowerCAmelCase__ ) __SCREAMING_SNAKE_CASE : int = self._write(index=lowerCAmelCase__ , **self.to_sql_kwargs ) return written def __magic_name__( self :Dict , lowerCAmelCase__ :List[Any] ) -> Optional[Any]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = args __SCREAMING_SNAKE_CASE : Union[str, Any] = {**to_sql_kwargs, '''if_exists''': '''append'''} if offset > 0 else to_sql_kwargs __SCREAMING_SNAKE_CASE : List[str] = query_table( table=self.dataset.data , key=slice(lowerCAmelCase__ , offset + self.batch_size ) , indices=self.dataset._indices , ) __SCREAMING_SNAKE_CASE : Union[str, Any] = batch.to_pandas() __SCREAMING_SNAKE_CASE : Union[str, Any] = df.to_sql(self.name , self.con , index=lowerCAmelCase__ , **lowerCAmelCase__ ) return num_rows or len(lowerCAmelCase__ ) def __magic_name__( self :str , lowerCAmelCase__ :str , **lowerCAmelCase__ :Tuple ) -> int: __SCREAMING_SNAKE_CASE : str = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 , len(self.dataset ) , self.batch_size ) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating SQL from Arrow format''' , ): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , lowerCAmelCase__ , lowerCAmelCase__ )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating SQL from Arrow format''' , ): written += num_rows return written
9
import pprint import requests SCREAMING_SNAKE_CASE__ : str = "https://zenquotes.io/api" def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = random_quotes() pprint.pprint(response)
270
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging __A = logging.get_logger(__name__) __A = { "google/pix2struct-textcaps-base": ( "https://huggingface.co/google/pix2struct-textcaps-base/resolve/main/config.json" ), } class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "pix2struct_text_model" lowercase_ = ["past_key_values"] lowercase_ = { "hidden_size": "hidden_size", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__(self : Dict , UpperCAmelCase_ : Any=50_244 , UpperCAmelCase_ : Union[str, Any]=768 , UpperCAmelCase_ : Tuple=64 , UpperCAmelCase_ : Tuple=2_048 , UpperCAmelCase_ : Dict=12 , UpperCAmelCase_ : List[Any]=12 , UpperCAmelCase_ : Any=32 , UpperCAmelCase_ : Union[str, Any]=128 , UpperCAmelCase_ : List[str]=0.1 , UpperCAmelCase_ : List[str]=1E-6 , UpperCAmelCase_ : str=1.0 , UpperCAmelCase_ : Dict="gelu_new" , UpperCAmelCase_ : List[Any]=0 , UpperCAmelCase_ : Dict=False , UpperCAmelCase_ : Optional[int]=0 , UpperCAmelCase_ : Union[str, Any]=1 , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : Union[str, Any]=True , **UpperCAmelCase_ : str , ) ->Optional[Any]: '''simple docstring''' lowerCamelCase__: Any =vocab_size lowerCamelCase__: Union[str, Any] =hidden_size lowerCamelCase__: Tuple =d_kv lowerCamelCase__: Optional[int] =d_ff lowerCamelCase__: Any =num_layers lowerCamelCase__: int =num_heads lowerCamelCase__: Any =relative_attention_num_buckets lowerCamelCase__: List[str] =relative_attention_max_distance lowerCamelCase__: Optional[int] =dropout_rate lowerCamelCase__: Optional[int] =layer_norm_epsilon lowerCamelCase__: Dict =initializer_factor lowerCamelCase__: List[Any] =use_cache lowerCamelCase__: Union[str, Any] =eos_token_id lowerCamelCase__: List[Any] =decoder_start_token_id # for backwards compatibility lowerCamelCase__: int =dense_act_fn super().__init__( pad_token_id=UpperCAmelCase_ , eos_token_id=UpperCAmelCase_ , decoder_start_token_id=UpperCAmelCase_ , tie_word_embeddings=UpperCAmelCase_ , is_decoder=UpperCAmelCase_ , **UpperCAmelCase_ , ) @classmethod def SCREAMING_SNAKE_CASE_ (cls : Union[str, Any] , UpperCAmelCase_ : Union[str, os.PathLike] , **UpperCAmelCase_ : Any) ->"PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__: List[Any] =cls.get_config_dict(UpperCAmelCase_ , **UpperCAmelCase_) # get the text config dict if we are loading from Pix2StructConfig if config_dict.get("model_type") == "pix2struct": lowerCamelCase__: Optional[Any] =config_dict["text_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(UpperCAmelCase_ , **UpperCAmelCase_) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "pix2struct_vision_model" def __init__(self : int , UpperCAmelCase_ : Optional[int]=768 , UpperCAmelCase_ : Any=768 , UpperCAmelCase_ : List[Any]=2_048 , UpperCAmelCase_ : Optional[Any]=64 , UpperCAmelCase_ : Dict=12 , UpperCAmelCase_ : Optional[Any]=12 , UpperCAmelCase_ : Tuple="gelu_new" , UpperCAmelCase_ : List[str]=1E-6 , UpperCAmelCase_ : Dict=0.0 , UpperCAmelCase_ : Optional[int]=0.0 , UpperCAmelCase_ : Any=1E-1_0 , UpperCAmelCase_ : Optional[int]=1.0 , UpperCAmelCase_ : Dict=4_096 , UpperCAmelCase_ : str=32 , UpperCAmelCase_ : Any=128 , **UpperCAmelCase_ : Union[str, Any] , ) ->Optional[Any]: '''simple docstring''' super().__init__(**UpperCAmelCase_) lowerCamelCase__: str =hidden_size lowerCamelCase__: Union[str, Any] =patch_embed_hidden_size lowerCamelCase__: str =d_ff lowerCamelCase__: Any =dropout_rate lowerCamelCase__: int =num_hidden_layers lowerCamelCase__: int =num_attention_heads lowerCamelCase__: str =initializer_range lowerCamelCase__: Any =initializer_factor lowerCamelCase__: Union[str, Any] =attention_dropout lowerCamelCase__: Tuple =layer_norm_eps lowerCamelCase__: int =dense_act_fn lowerCamelCase__: Tuple =seq_len lowerCamelCase__: Optional[Any] =relative_attention_num_buckets lowerCamelCase__: int =relative_attention_max_distance lowerCamelCase__: Dict =d_kv @classmethod def SCREAMING_SNAKE_CASE_ (cls : Any , UpperCAmelCase_ : Union[str, os.PathLike] , **UpperCAmelCase_ : List[str]) ->"PretrainedConfig": '''simple docstring''' cls._set_token_in_kwargs(UpperCAmelCase_) lowerCamelCase__ , lowerCamelCase__: str =cls.get_config_dict(UpperCAmelCase_ , **UpperCAmelCase_) # get the vision config dict if we are loading from Pix2StructConfig if config_dict.get("model_type") == "pix2struct": lowerCamelCase__: Tuple =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(UpperCAmelCase_ , **UpperCAmelCase_) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "pix2struct" lowercase_ = True def __init__(self : Tuple , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Optional[int]=None , UpperCAmelCase_ : List[str]=1.0 , UpperCAmelCase_ : Union[str, Any]=0.02 , UpperCAmelCase_ : Any=False , UpperCAmelCase_ : List[Any]=False , UpperCAmelCase_ : Dict=True , **UpperCAmelCase_ : List[Any] , ) ->List[str]: '''simple docstring''' super().__init__(tie_word_embeddings=UpperCAmelCase_ , is_encoder_decoder=UpperCAmelCase_ , **UpperCAmelCase_) if text_config is None: lowerCamelCase__: List[str] ={} logger.info("text_config is None. Initializing the Pix2StructTextConfig with default values.") if vision_config is None: lowerCamelCase__: str ={} logger.info("vision_config is None. Initializing the Pix2StructVisionConfig with default values.") lowerCamelCase__: int =PixaStructTextConfig(**UpperCAmelCase_) lowerCamelCase__: int =PixaStructVisionConfig(**UpperCAmelCase_) lowerCamelCase__: Union[str, Any] =self.text_config.decoder_start_token_id lowerCamelCase__: Tuple =self.text_config.pad_token_id lowerCamelCase__: List[str] =self.text_config.eos_token_id lowerCamelCase__: Union[str, Any] =initializer_factor lowerCamelCase__: str =initializer_range lowerCamelCase__: Optional[int] =self.initializer_range lowerCamelCase__: Dict =self.initializer_range lowerCamelCase__: str =is_vqa @classmethod def SCREAMING_SNAKE_CASE_ (cls : List[Any] , UpperCAmelCase_ : PixaStructTextConfig , UpperCAmelCase_ : PixaStructVisionConfig , **UpperCAmelCase_ : Optional[Any]) ->Optional[Any]: '''simple docstring''' return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **UpperCAmelCase_) def SCREAMING_SNAKE_CASE_ (self : str) ->List[Any]: '''simple docstring''' lowerCamelCase__: int =copy.deepcopy(self.__dict__) lowerCamelCase__: List[Any] =self.text_config.to_dict() lowerCamelCase__: List[str] =self.vision_config.to_dict() lowerCamelCase__: Dict =self.__class__.model_type return output
10
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __magic_name__ ( __lowerCAmelCase : int ) -> int: __lowerCamelCase = prime_factors(__lowerCAmelCase ) if is_square_free(__lowerCAmelCase ): return -1 if len(__lowerCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
270
0
import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_torch_available from transformers.testing_utils import require_torch, torch_device if is_torch_available(): from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments @require_torch class lowerCAmelCase__ ( unittest.TestCase): '''simple docstring''' def _lowerCamelCase ( self , __lowerCamelCase) -> Dict: for model_result in results.values(): for batch_size, sequence_length in zip(model_result["bs"] , model_result["ss"]): _A : Optional[int] = model_result["result"][batch_size][sequence_length] self.assertIsNotNone(__lowerCamelCase) def _lowerCamelCase ( self) -> int: _A : Optional[int] = "sshleifer/tiny-gpt2" _A : int = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) _A : List[str] = PyTorchBenchmark(__lowerCamelCase) _A : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result) self.check_results_dict_not_empty(results.memory_inference_result) def _lowerCamelCase ( self) -> Dict: _A : int = "sgugger/tiny-distilbert-classification" _A : str = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , only_pretrain_model=__lowerCamelCase , ) _A : Dict = PyTorchBenchmark(__lowerCamelCase) _A : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result) self.check_results_dict_not_empty(results.memory_inference_result) def _lowerCamelCase ( self) -> Optional[Any]: _A : Tuple = "sshleifer/tiny-gpt2" _A : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , torchscript=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) _A : Union[str, Any] = PyTorchBenchmark(__lowerCamelCase) _A : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result) self.check_results_dict_not_empty(results.memory_inference_result) @unittest.skipIf(torch_device == "cpu" , "Cant do half precision") def _lowerCamelCase ( self) -> int: _A : Any = "sshleifer/tiny-gpt2" _A : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , fpaa=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) _A : Any = PyTorchBenchmark(__lowerCamelCase) _A : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result) self.check_results_dict_not_empty(results.memory_inference_result) def _lowerCamelCase ( self) -> Any: _A : Union[str, Any] = "sshleifer/tiny-gpt2" _A : Any = AutoConfig.from_pretrained(__lowerCamelCase) # set architectures equal to `None` _A : Dict = None _A : Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) _A : Union[str, Any] = PyTorchBenchmark(__lowerCamelCase , configs=[config]) _A : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result) self.check_results_dict_not_empty(results.memory_inference_result) def _lowerCamelCase ( self) -> int: _A : List[Any] = "sshleifer/tiny-gpt2" _A : int = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) _A : Optional[Any] = PyTorchBenchmark(__lowerCamelCase) _A : int = benchmark.run() self.check_results_dict_not_empty(results.time_train_result) self.check_results_dict_not_empty(results.memory_train_result) @unittest.skipIf(torch_device == "cpu" , "Can't do half precision") def _lowerCamelCase ( self) -> Optional[Any]: _A : Any = "sshleifer/tiny-gpt2" _A : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , fpaa=__lowerCamelCase , multi_process=__lowerCamelCase , ) _A : List[Any] = PyTorchBenchmark(__lowerCamelCase) _A : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result) self.check_results_dict_not_empty(results.memory_train_result) def _lowerCamelCase ( self) -> str: _A : List[str] = "sshleifer/tiny-gpt2" _A : Union[str, Any] = AutoConfig.from_pretrained(__lowerCamelCase) _A : Any = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) _A : Optional[Any] = PyTorchBenchmark(__lowerCamelCase , configs=[config]) _A : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result) self.check_results_dict_not_empty(results.memory_inference_result) def _lowerCamelCase ( self) -> int: _A : Tuple = "sshleifer/tinier_bart" _A : Optional[Any] = AutoConfig.from_pretrained(__lowerCamelCase) _A : Optional[int] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) _A : Dict = PyTorchBenchmark(__lowerCamelCase , configs=[config]) _A : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result) self.check_results_dict_not_empty(results.memory_inference_result) def _lowerCamelCase ( self) -> str: _A : List[Any] = "sshleifer/tiny-gpt2" _A : Optional[Any] = AutoConfig.from_pretrained(__lowerCamelCase) _A : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) _A : List[str] = PyTorchBenchmark(__lowerCamelCase , configs=[config]) _A : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_train_result) self.check_results_dict_not_empty(results.memory_train_result) def _lowerCamelCase ( self) -> int: _A : int = "sshleifer/tinier_bart" _A : str = AutoConfig.from_pretrained(__lowerCamelCase) _A : Tuple = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__lowerCamelCase , ) _A : Tuple = PyTorchBenchmark(__lowerCamelCase , configs=[config]) _A : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result) self.check_results_dict_not_empty(results.memory_train_result) def _lowerCamelCase ( self) -> Dict: _A : List[str] = "sshleifer/tiny-gpt2" with tempfile.TemporaryDirectory() as tmp_dir: _A : Optional[Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , save_to_csv=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(__lowerCamelCase , "inf_time.csv") , train_memory_csv_file=os.path.join(__lowerCamelCase , "train_mem.csv") , inference_memory_csv_file=os.path.join(__lowerCamelCase , "inf_mem.csv") , train_time_csv_file=os.path.join(__lowerCamelCase , "train_time.csv") , env_info_csv_file=os.path.join(__lowerCamelCase , "env.csv") , multi_process=__lowerCamelCase , ) _A : Tuple = PyTorchBenchmark(__lowerCamelCase) benchmark.run() self.assertTrue(Path(os.path.join(__lowerCamelCase , "inf_time.csv")).exists()) self.assertTrue(Path(os.path.join(__lowerCamelCase , "train_time.csv")).exists()) self.assertTrue(Path(os.path.join(__lowerCamelCase , "inf_mem.csv")).exists()) self.assertTrue(Path(os.path.join(__lowerCamelCase , "train_mem.csv")).exists()) self.assertTrue(Path(os.path.join(__lowerCamelCase , "env.csv")).exists()) def _lowerCamelCase ( self) -> int: _A : Dict = "sshleifer/tiny-gpt2" def _check_summary_is_not_empty(__lowerCamelCase): self.assertTrue(hasattr(__lowerCamelCase , "sequential")) self.assertTrue(hasattr(__lowerCamelCase , "cumulative")) self.assertTrue(hasattr(__lowerCamelCase , "current")) self.assertTrue(hasattr(__lowerCamelCase , "total")) with tempfile.TemporaryDirectory() as tmp_dir: _A : Union[str, Any] = PyTorchBenchmarkArguments( models=[MODEL_ID] , training=__lowerCamelCase , inference=__lowerCamelCase , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(__lowerCamelCase , "log.txt") , log_print=__lowerCamelCase , trace_memory_line_by_line=__lowerCamelCase , multi_process=__lowerCamelCase , ) _A : Optional[int] = PyTorchBenchmark(__lowerCamelCase) _A : Dict = benchmark.run() _check_summary_is_not_empty(result.inference_summary) _check_summary_is_not_empty(result.train_summary) self.assertTrue(Path(os.path.join(__lowerCamelCase , "log.txt")).exists())
11
import argparse import collections import json import os import re import string import sys import numpy as np SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"\b(a|an|the)\b", re.UNICODE) SCREAMING_SNAKE_CASE__ : int = None def __magic_name__ ( ) -> str: __lowerCamelCase = argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.''' ) parser.add_argument('''data_file''' , metavar='''data.json''' , help='''Input data JSON file.''' ) parser.add_argument('''pred_file''' , metavar='''pred.json''' , help='''Model predictions.''' ) parser.add_argument( '''--out-file''' , '''-o''' , metavar='''eval.json''' , help='''Write accuracy metrics to file (default is stdout).''' ) parser.add_argument( '''--na-prob-file''' , '''-n''' , metavar='''na_prob.json''' , help='''Model estimates of probability of no answer.''' ) parser.add_argument( '''--na-prob-thresh''' , '''-t''' , type=__lowerCAmelCase , default=1.0 , help='''Predict "" if no-answer probability exceeds this (default = 1.0).''' , ) parser.add_argument( '''--out-image-dir''' , '''-p''' , metavar='''out_images''' , default=__lowerCAmelCase , help='''Save precision-recall curves to directory.''' ) parser.add_argument('''--verbose''' , '''-v''' , action='''store_true''' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = bool(qa['''answers''']['''text'''] ) return qid_to_has_ans def __magic_name__ ( __lowerCAmelCase : Dict ) -> Optional[Any]: def remove_articles(__lowerCAmelCase : Optional[int] ): return ARTICLES_REGEX.sub(''' ''' , __lowerCAmelCase ) def white_space_fix(__lowerCAmelCase : Optional[int] ): return " ".join(text.split() ) def remove_punc(__lowerCAmelCase : Union[str, Any] ): __lowerCamelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__lowerCAmelCase : Dict ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__lowerCAmelCase ) ) ) ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Optional[int]: if not s: return [] return normalize_answer(__lowerCAmelCase ).split() def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple ) -> int: return int(normalize_answer(__lowerCAmelCase ) == normalize_answer(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple ) -> str: __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = collections.Counter(__lowerCAmelCase ) & collections.Counter(__lowerCAmelCase ) __lowerCamelCase = sum(common.values() ) if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = (2 * precision * recall) / (precision + recall) return fa def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] ) -> Optional[Any]: __lowerCamelCase = {} __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = qa['''id'''] __lowerCamelCase = [t for t in qa['''answers''']['''text'''] if normalize_answer(__lowerCAmelCase )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __lowerCamelCase = [''''''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue __lowerCamelCase = preds[qid] # Take max over all gold answers __lowerCamelCase = max(compute_exact(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) __lowerCamelCase = max(compute_fa(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) return exact_scores, fa_scores def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ) -> List[str]: __lowerCamelCase = {} for qid, s in scores.items(): __lowerCamelCase = na_probs[qid] > na_prob_thresh if pred_na: __lowerCamelCase = float(not qid_to_has_ans[qid] ) else: __lowerCamelCase = s return new_scores def __magic_name__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=None ) -> Union[str, Any]: if not qid_list: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores.values() ) / total), ('''f1''', 100.0 * sum(fa_scores.values() ) / total), ('''total''', total), ] ) else: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('''f1''', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('''total''', total), ] ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ) -> int: for k in new_eval: __lowerCamelCase = new_eval[k] def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ) -> Optional[Any]: plt.step(__lowerCAmelCase , __lowerCAmelCase , color='''b''' , alpha=0.2 , where='''post''' ) plt.fill_between(__lowerCAmelCase , __lowerCAmelCase , step='''post''' , alpha=0.2 , color='''b''' ) plt.xlabel('''Recall''' ) plt.ylabel('''Precision''' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__lowerCAmelCase ) plt.savefig(__lowerCAmelCase ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Tuple=None ) -> int: __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) __lowerCamelCase = 0.0 __lowerCamelCase = 1.0 __lowerCamelCase = 0.0 __lowerCamelCase = [1.0] __lowerCamelCase = [0.0] __lowerCamelCase = 0.0 for i, qid in enumerate(__lowerCAmelCase ): if qid_to_has_ans[qid]: true_pos += scores[qid] __lowerCamelCase = true_pos / float(i + 1 ) __lowerCamelCase = true_pos / float(__lowerCAmelCase ) if i == len(__lowerCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__lowerCAmelCase ) recalls.append(__lowerCAmelCase ) if out_image: plot_pr_curve(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return {"ap": 100.0 * avg_prec} def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] ) -> List[Any]: if out_image_dir and not os.path.exists(__lowerCAmelCase ): os.makedirs(__lowerCAmelCase ) __lowerCamelCase = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_exact.png''' ) , title='''Precision-Recall curve for Exact Match score''' , ) __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_f1.png''' ) , title='''Precision-Recall curve for F1 score''' , ) __lowerCamelCase = {k: float(__lowerCAmelCase ) for k, v in qid_to_has_ans.items()} __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_oracle.png''' ) , title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)''' , ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_exact''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_f1''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_oracle''' ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> Optional[Any]: if not qid_list: return __lowerCamelCase = [na_probs[k] for k in qid_list] __lowerCamelCase = np.ones_like(__lowerCAmelCase ) / float(len(__lowerCAmelCase ) ) plt.hist(__lowerCAmelCase , weights=__lowerCAmelCase , bins=20 , range=(0.0, 1.0) ) plt.xlabel('''Model probability of no-answer''' ) plt.ylabel('''Proportion of dataset''' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__lowerCAmelCase , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ) -> Optional[int]: __lowerCamelCase = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __lowerCamelCase = num_no_ans __lowerCamelCase = cur_score __lowerCamelCase = 0.0 __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) for i, qid in enumerate(__lowerCAmelCase ): if qid not in scores: continue if qid_to_has_ans[qid]: __lowerCamelCase = scores[qid] else: if preds[qid]: __lowerCamelCase = -1 else: __lowerCamelCase = 0 cur_score += diff if cur_score > best_score: __lowerCamelCase = cur_score __lowerCamelCase = na_probs[qid] return 100.0 * best_score / len(__lowerCAmelCase ), best_thresh def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] ) -> int: __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = best_exact __lowerCamelCase = exact_thresh __lowerCamelCase = best_fa __lowerCamelCase = fa_thresh def __magic_name__ ( ) -> Optional[int]: with open(OPTS.data_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) __lowerCamelCase = dataset_json['''data'''] with open(OPTS.pred_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) else: __lowerCamelCase = {k: 0.0 for k in preds} __lowerCamelCase = make_qid_to_has_ans(__lowerCAmelCase ) # maps qid to True/False __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if v] __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if not v] __lowerCamelCase , __lowerCamelCase = get_raw_scores(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase ) if has_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''HasAns''' ) if no_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''NoAns''' ) if OPTS.na_prob_file: find_all_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''hasAns''' ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''noAns''' ) if OPTS.out_file: with open(OPTS.out_file , '''w''' ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) else: print(json.dumps(__lowerCAmelCase , indent=2 ) ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
270
0
from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging UpperCAmelCase_ = logging.get_logger(__name__) class lowerCamelCase__( __lowerCamelCase): UpperCAmelCase__ : Tuple = ['pixel_values'] def __init__( self: Any , UpperCamelCase_: bool = True , UpperCamelCase_: Union[int, float] = 1 / 2_55 , UpperCamelCase_: bool = True , UpperCamelCase_: int = 8 , **UpperCamelCase_: Tuple , ): super().__init__(**UpperCamelCase_ ) __lowerCamelCase = do_rescale __lowerCamelCase = rescale_factor __lowerCamelCase = do_pad __lowerCamelCase = pad_size def lowerCAmelCase__ ( self: List[str] , UpperCamelCase_: np.ndarray , UpperCamelCase_: float , UpperCamelCase_: Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase_: Tuple ): return rescale(UpperCamelCase_ , scale=UpperCamelCase_ , data_format=UpperCamelCase_ , **UpperCamelCase_ ) def lowerCAmelCase__ ( self: Union[str, Any] , UpperCamelCase_: np.ndarray , UpperCamelCase_: int , UpperCamelCase_: Optional[Union[str, ChannelDimension]] = None ): __lowerCamelCase, __lowerCamelCase = get_image_size(UpperCamelCase_ ) __lowerCamelCase = (old_height // size + 1) * size - old_height __lowerCamelCase = (old_width // size + 1) * size - old_width return pad(UpperCamelCase_ , ((0, pad_height), (0, pad_width)) , mode="""symmetric""" , data_format=UpperCamelCase_ ) def lowerCAmelCase__ ( self: str , UpperCamelCase_: ImageInput , UpperCamelCase_: Optional[bool] = None , UpperCamelCase_: Optional[float] = None , UpperCamelCase_: Optional[bool] = None , UpperCamelCase_: Optional[int] = None , UpperCamelCase_: Optional[Union[str, TensorType]] = None , UpperCamelCase_: Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase_: Any , ): __lowerCamelCase = do_rescale if do_rescale is not None else self.do_rescale __lowerCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor __lowerCamelCase = do_pad if do_pad is not None else self.do_pad __lowerCamelCase = pad_size if pad_size is not None else self.pad_size __lowerCamelCase = make_list_of_images(UpperCamelCase_ ) if not valid_images(UpperCamelCase_ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) # All transformations expect numpy arrays. __lowerCamelCase = [to_numpy_array(UpperCamelCase_ ) for image in images] if do_rescale: __lowerCamelCase = [self.rescale(image=UpperCamelCase_ , scale=UpperCamelCase_ ) for image in images] if do_pad: __lowerCamelCase = [self.pad(UpperCamelCase_ , size=UpperCamelCase_ ) for image in images] __lowerCamelCase = [to_channel_dimension_format(UpperCamelCase_ , UpperCamelCase_ ) for image in images] __lowerCamelCase = {"""pixel_values""": images} return BatchFeature(data=UpperCamelCase_ , tensor_type=UpperCamelCase_ )
12
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F'{bindir}/../../examples/pytorch/translation'): from run_translation import main # noqa set_seed(42) SCREAMING_SNAKE_CASE__ : Any = "sshleifer/student_marian_en_ro_6_1" SCREAMING_SNAKE_CASE__ : Tuple = "sshleifer/tiny-mbart" @require_torch class lowerCAmelCase__ ( __lowercase ): def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , ) -> Optional[int]: __lowerCamelCase = self.run_trainer( eval_steps=1 , max_len=12 , model_name=SCREAMING_SNAKE_CASE__ , num_train_epochs=1 , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , predict_with_generate=SCREAMING_SNAKE_CASE__ , do_train=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history if not do_eval: return __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats __lowerCamelCase = eval_metrics[-1] assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) assert not math.isnan(float(last_step_stats['''eval_loss'''] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def __A ( self : Optional[int] ) -> int: self.run_seqaseq_quick() @require_torch_multi_gpu def __A ( self : int ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @require_torch_multi_gpu def __A ( self : Optional[Any] ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Optional[int] ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple --fp16''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Tuple ) -> Any: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick( distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2 --fp16''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @require_apex @require_torch_gpu def __A ( self : Union[str, Any] ) -> List[str]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) @parameterized.expand(['''base''', '''low''', '''high''', '''mixed'''] ) @require_torch_multi_gpu def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout __lowerCamelCase = { # test with the default log_level - should be info and thus log info once '''base''': {'''extra_args_str''': '''''', '''n_matches''': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes '''low''': {'''extra_args_str''': '''--log_level debug --log_level_replica debug''', '''n_matches''': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica '''high''': {'''extra_args_str''': '''--log_level error --log_level_replica debug''', '''n_matches''': 1}, # test with high log_level and log_level_replica - should be quiet on all processes '''mixed''': {'''extra_args_str''': '''--log_level error --log_level_replica error''', '''n_matches''': 0}, } __lowerCamelCase = experiments[experiment_id] __lowerCamelCase = {'''distributed''': True, '''predict_with_generate''': False, '''do_eval''': False, '''do_predict''': False} __lowerCamelCase = '''Running training''' with CaptureStderr() as cl: self.run_seqaseq_quick(**SCREAMING_SNAKE_CASE__ , extra_args_str=data['''extra_args_str'''] ) __lowerCamelCase = len(re.findall(SCREAMING_SNAKE_CASE__ , cl.err ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ , data['''n_matches'''] ) @slow def __A ( self : Any ) -> Optional[Any]: __lowerCamelCase = self.run_trainer( eval_steps=2 , max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=10 , distributed=SCREAMING_SNAKE_CASE__ , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] __lowerCamelCase = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) # test if do_predict saves generations and metrics __lowerCamelCase = os.listdir(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {os.path.basename(SCREAMING_SNAKE_CASE__ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def __A ( self : Optional[int] ) -> str: from transformers.training_args import OptimizerNames def train_and_return_metrics(SCREAMING_SNAKE_CASE__ : str ) -> Tuple[int, float]: __lowerCamelCase = '''--skip_memory_metrics 0''' __lowerCamelCase = self.run_trainer( max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=1 , optim=SCREAMING_SNAKE_CASE__ , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , n_gpus_to_use=1 , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(Path(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = int(logs[0]['''train_mem_gpu_peaked_delta'''] / 2**20 ) __lowerCamelCase = int(logs[0]['''train_mem_gpu_alloc_delta'''] / 2**20 ) __lowerCamelCase = logs[0]['''train_loss'''] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) __lowerCamelCase = gpu_alloc_mem_orig - gpu_alloc_mem_bnb __lowerCamelCase = gpu_peak_mem_orig + gpu_alloc_mem_orig __lowerCamelCase = gpu_peak_mem_bnb + gpu_alloc_mem_bnb __lowerCamelCase = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings __lowerCamelCase = 1_20 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and''' f''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , ) self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less total gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and''' f''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , ) self.assertEqual( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , f'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = 3e-3 , SCREAMING_SNAKE_CASE__ : str = "adafactor" , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : int = None , ) -> List[Any]: __lowerCamelCase = self.test_file_dir / '''../fixtures/tests_samples/wmt_en_ro''' __lowerCamelCase = self.get_auto_remove_tmp_dir() __lowerCamelCase = f''' --model_name_or_path {model_name} --train_file {data_dir}/train.json --validation_file {data_dir}/val.json --test_file {data_dir}/test.json --output_dir {output_dir} --overwrite_output_dir --max_train_samples 8 --max_source_length {max_len} --max_target_length {max_len} --do_train --num_train_epochs {str(SCREAMING_SNAKE_CASE__ )} --per_device_train_batch_size 4 --learning_rate {learning_rate} --warmup_steps 8 --logging_steps 0 --logging_strategy no --save_steps {str(SCREAMING_SNAKE_CASE__ )} --group_by_length --label_smoothing_factor 0.1 --target_lang ro_RO --source_lang en_XX '''.split() __lowerCamelCase = f''' --do_eval --per_device_eval_batch_size 4 --max_eval_samples 8 --val_max_target_length {max_len} --evaluation_strategy steps --eval_steps {str(SCREAMING_SNAKE_CASE__ )} '''.split() __lowerCamelCase = ''' --do_predict '''.split() __lowerCamelCase = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f'''--optim {optim}'''.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: __lowerCamelCase = get_gpu_count() __lowerCamelCase = get_torch_dist_unique_port() __lowerCamelCase = f''' -m torch.distributed.run --nproc_per_node={n_gpus_to_use} --master_port={master_port} {self.examples_dir_str}/pytorch/translation/run_translation.py '''.split() __lowerCamelCase = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) else: __lowerCamelCase = ['''run_translation.py'''] + args with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): main() return output_dir
270
0
import warnings from functools import wraps from typing import Callable def A_ ( _UpperCAmelCase ): @wraps(_UpperCAmelCase ) def _inner_fn(*_UpperCAmelCase , **_UpperCAmelCase ): warnings.warn( (f"'{fn.__name__}' is experimental and might be subject to breaking changes in the future.") , _UpperCAmelCase , ) return fn(*_UpperCAmelCase , **_UpperCAmelCase ) return _inner_fn
13
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__ : Dict = { "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__ : int = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowercase ): a__ : Any = """mask2former""" a__ : Dict = ["""swin"""] a__ : Any = {"""hidden_size""": """hidden_dim"""} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 20_48 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_55 , SCREAMING_SNAKE_CASE__ : int = 1_00 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_25_44 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 16, 32] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> str: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.''' ) __lowerCamelCase = CONFIG_MAPPING['''swin''']( image_size=2_24 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = backbone_config.pop('''model_type''' ) __lowerCamelCase = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # 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 )}''' ) __lowerCamelCase = backbone_config __lowerCamelCase = feature_size __lowerCamelCase = mask_feature_size __lowerCamelCase = hidden_dim __lowerCamelCase = encoder_feedforward_dim __lowerCamelCase = activation_function __lowerCamelCase = encoder_layers __lowerCamelCase = decoder_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = dropout __lowerCamelCase = dim_feedforward __lowerCamelCase = pre_norm __lowerCamelCase = enforce_input_projection __lowerCamelCase = common_stride __lowerCamelCase = ignore_value __lowerCamelCase = num_queries __lowerCamelCase = no_object_weight __lowerCamelCase = class_weight __lowerCamelCase = mask_weight __lowerCamelCase = dice_weight __lowerCamelCase = train_num_points __lowerCamelCase = oversample_ratio __lowerCamelCase = importance_sample_ratio __lowerCamelCase = init_std __lowerCamelCase = init_xavier_std __lowerCamelCase = use_auxiliary_loss __lowerCamelCase = feature_strides __lowerCamelCase = output_auxiliary_logits __lowerCamelCase = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def __A ( cls : Any , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Any ) -> Dict[str, any]: __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.backbone_config.to_dict() __lowerCamelCase = self.__class__.model_type return output
270
0
from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class UpperCamelCase_ : '''simple docstring''' UpperCAmelCase__ = 42 UpperCAmelCase__ = None UpperCAmelCase__ = None def SCREAMING_SNAKE_CASE ( ) -> Node | None: """simple docstring""" A__ = Node(1 ) A__ = Node(2 ) A__ = Node(3 ) A__ = Node(4 ) A__ = Node(5 ) return tree def SCREAMING_SNAKE_CASE ( lowercase_ ) -> list[int]: """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def SCREAMING_SNAKE_CASE ( lowercase_ ) -> list[int]: """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def SCREAMING_SNAKE_CASE ( lowercase_ ) -> list[int]: """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Sequence[Node | None]: """simple docstring""" A__ = [] if root is None: return output A__ = deque([root] ) while process_queue: A__ = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Sequence[Node | None]: """simple docstring""" A__ = [] def populate_output(lowercase_ , lowercase_ ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(lowercase_ , lowercase_ ) return output def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Sequence[Node | None]: """simple docstring""" A__ = [] def populate_output(lowercase_ , lowercase_ ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(lowercase_ , lowercase_ ) return output def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Sequence[Node | None] | list[Any]: """simple docstring""" if root is None: return [] A__ = [] A__ = 0 A__ = height(lowercase_ ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(lowercase_ , lowercase_ ) ) A__ = 1 else: output.append(get_nodes_from_right_to_left(lowercase_ , lowercase_ ) ) A__ = 0 return output def SCREAMING_SNAKE_CASE ( ) -> None: # Main function for testing. """simple docstring""" A__ = make_tree() print(f"""In-order Traversal: {inorder(lowercase_ )}""" ) print(f"""Pre-order Traversal: {preorder(lowercase_ )}""" ) print(f"""Post-order Traversal: {postorder(lowercase_ )}""" , '''\n''' ) print(f"""Height of Tree: {height(lowercase_ )}""" , '''\n''' ) print('''Complete Level Order Traversal: ''' ) print(level_order(lowercase_ ) , '''\n''' ) print('''Level-wise order Traversal: ''' ) for level in range(1 , height(lowercase_ ) + 1 ): print(f"""Level {level}:""" , get_nodes_from_left_to_right(lowercase_ , level=lowercase_ ) ) print('''\nZigZag order Traversal: ''' ) print(zigzag(lowercase_ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
14
import os def __magic_name__ ( ) -> str: __lowerCamelCase = os.path.join(os.path.dirname(__lowerCAmelCase ) , '''num.txt''' ) with open(__lowerCAmelCase ) as file_hand: return str(sum(int(__lowerCAmelCase ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
270
0
import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE :Optional[int] = '▁' SCREAMING_SNAKE_CASE :List[Any] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = BigBirdTokenizer snake_case_ = BigBirdTokenizerFast snake_case_ = True snake_case_ = True def UpperCamelCase_ ( self : Dict ): super().setUp() __A = self.tokenizer_class(A ,keep_accents=A ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase_ ( self : Optional[Any] ): __A = "<s>" __A = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(A ) ,A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(A ) ,A ) def UpperCamelCase_ ( self : int ): __A = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,"<unk>" ) self.assertEqual(vocab_keys[1] ,"<s>" ) self.assertEqual(vocab_keys[-1] ,"[MASK]" ) self.assertEqual(len(A ) ,10_04 ) def UpperCamelCase_ ( self : Dict ): self.assertEqual(self.get_tokenizer().vocab_size ,10_00 ) def UpperCamelCase_ ( self : str ): if not self.test_rust_tokenizer: return __A = self.get_tokenizer() __A = self.get_rust_tokenizer() __A = "I was born in 92000, and this is falsé." __A = tokenizer.tokenize(A ) __A = rust_tokenizer.tokenize(A ) self.assertListEqual(A ,A ) __A = tokenizer.encode(A ,add_special_tokens=A ) __A = rust_tokenizer.encode(A ,add_special_tokens=A ) self.assertListEqual(A ,A ) __A = self.get_rust_tokenizer() __A = tokenizer.encode(A ) __A = rust_tokenizer.encode(A ) self.assertListEqual(A ,A ) def UpperCamelCase_ ( self : Any ): __A = BigBirdTokenizer(A ,keep_accents=A ) __A = tokenizer.tokenize("This is a test" ) self.assertListEqual(A ,["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(A ) ,[2_85, 46, 10, 1_70, 3_82] ,) __A = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( A ,[ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] ,) __A = tokenizer.convert_tokens_to_ids(A ) self.assertListEqual( A ,[8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] ,) __A = tokenizer.convert_ids_to_tokens(A ) self.assertListEqual( A ,[ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] ,) @cached_property def UpperCamelCase_ ( self : str ): return BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) @slow def UpperCamelCase_ ( self : List[str] ): __A = "Hello World!" __A = [65, 1_85_36, 22_60, 1_01, 66] self.assertListEqual(A ,self.big_tokenizer.encode(A ) ) @slow def UpperCamelCase_ ( self : Dict ): __A = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) # fmt: off __A = [65, 8_71, 4_19, 3_58, 9_46, 9_91, 25_21, 4_52, 3_58, 13_57, 3_87, 77_51, 35_36, 1_12, 9_85, 4_56, 1_26, 8_65, 9_38, 54_00, 57_34, 4_58, 13_68, 4_67, 7_86, 24_62, 52_46, 11_59, 6_33, 8_65, 45_19, 4_57, 5_82, 8_52, 25_57, 4_27, 9_16, 5_08, 4_05, 3_43_24, 4_97, 3_91, 4_08, 1_13_42, 12_44, 3_85, 1_00, 9_38, 9_85, 4_56, 5_74, 3_62, 1_25_97, 32_00, 31_29, 11_72, 66] # noqa: E231 # fmt: on self.assertListEqual(A ,self.big_tokenizer.encode(A ) ) @require_torch @slow def UpperCamelCase_ ( self : Any ): import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence __A = list(self.big_tokenizer.get_vocab().keys() )[:10] __A = " ".join(A ) __A = self.big_tokenizer.encode_plus(A ,return_tensors="pt" ,return_token_type_ids=A ) __A = self.big_tokenizer.batch_encode_plus( [sequence + " " + sequence] ,return_tensors="pt" ,return_token_type_ids=A ) __A = BigBirdConfig(attention_type="original_full" ) __A = BigBirdModel(A ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**A ) model(**A ) @slow def UpperCamelCase_ ( self : List[str] ): __A = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" ) __A = tokenizer.decode(tokenizer("Paris is the [MASK]." ).input_ids ) self.assertTrue(decoded_text == "[CLS] Paris is the[MASK].[SEP]" ) @slow def UpperCamelCase_ ( self : str ): # fmt: off __A = {"input_ids": [[65, 3_92_86, 4_58, 3_63_35, 20_01, 4_56, 1_30_73, 1_32_66, 4_55, 1_13, 77_46, 17_41, 1_11_57, 3_91, 1_30_73, 1_32_66, 4_55, 1_13, 39_67, 3_54_12, 1_13, 49_36, 1_09, 38_70, 23_77, 1_13, 3_00_84, 4_57_20, 4_58, 1_34, 1_74_96, 1_12, 5_03, 1_16_72, 1_13, 1_18, 1_12, 56_65, 1_33_47, 3_86_87, 1_12, 14_96, 3_13_89, 1_12, 32_68, 4_72_64, 1_34, 9_62, 1_12, 1_63_77, 80_35, 2_31_30, 4_30, 1_21_69, 1_55_18, 2_85_92, 4_58, 1_46, 4_16_97, 1_09, 3_91, 1_21_69, 1_55_18, 1_66_89, 4_58, 1_46, 4_13_58, 1_09, 4_52, 7_26, 40_34, 1_11, 7_63, 3_54_12, 50_82, 3_88, 19_03, 1_11, 90_51, 3_91, 28_70, 4_89_18, 19_00, 11_23, 5_50, 9_98, 1_12, 95_86, 1_59_85, 4_55, 3_91, 4_10, 2_29_55, 3_76_36, 1_14, 66], [65, 4_48, 1_74_96, 4_19, 36_63, 3_85, 7_63, 1_13, 2_75_33, 28_70, 32_83, 1_30_43, 16_39, 2_47_13, 5_23, 6_56, 2_40_13, 1_85_50, 25_21, 5_17, 2_70_14, 2_12_44, 4_20, 12_12, 14_65, 3_91, 9_27, 48_33, 3_88, 5_78, 1_17_86, 1_14, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 4_84, 21_69, 76_87, 2_19_32, 1_81_46, 7_26, 3_63, 1_70_32, 33_91, 1_14, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=A ,model_name="google/bigbird-roberta-base" ,revision="215c99f1600e06f83acce68422f2035b2b5c3510" ,)
15
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str a__ : List[str] a__ : Optional[List[str]] @dataclass class lowerCAmelCase__ : a__ : List[int] a__ : List[int] a__ : Optional[List[int]] = None a__ : Optional[List[int]] = None class lowerCAmelCase__ ( __lowercase ): a__ : Optional[Any] = """train""" a__ : Optional[int] = """dev""" a__ : Dict = """test""" class lowerCAmelCase__ : @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[Split, str] ) -> List[InputExample]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : str ) -> List[str]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : List[InputExample] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]="[CLS]" , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str="[SEP]" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : str=-1_00 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[Any]=True , ) -> List[InputFeatures]: __lowerCamelCase = {label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} __lowerCamelCase = [] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE__ ): if ex_index % 1_00_00 == 0: logger.info('''Writing example %d of %d''' , SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [] __lowerCamelCase = [] for word, label in zip(example.words , example.labels ): __lowerCamelCase = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE__ ) > 0: tokens.extend(SCREAMING_SNAKE_CASE__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __lowerCamelCase = tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE__ ) > max_seq_length - special_tokens_count: __lowerCamelCase = tokens[: (max_seq_length - special_tokens_count)] __lowerCamelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __lowerCamelCase = [sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __lowerCamelCase = [cls_token] + tokens __lowerCamelCase = [pad_token_label_id] + label_ids __lowerCamelCase = [cls_token_segment_id] + segment_ids __lowerCamelCase = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __lowerCamelCase = [1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE__ ) # Zero-pad up to the sequence length. __lowerCamelCase = max_seq_length - len(SCREAMING_SNAKE_CASE__ ) if pad_on_left: __lowerCamelCase = ([pad_token] * padding_length) + input_ids __lowerCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __lowerCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids __lowerCamelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , label_ids=SCREAMING_SNAKE_CASE__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowerCAmelCase__ ( __lowercase ): a__ : List[InputFeatures] a__ : int = nn.CrossEntropyLoss().ignore_index def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> Union[str, Any]: # Load data features from cache or dataset file __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __lowerCamelCase = cached_features_file + '''.lock''' with FileLock(SCREAMING_SNAKE_CASE__ ): if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) __lowerCamelCase = torch.load(SCREAMING_SNAKE_CASE__ ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , SCREAMING_SNAKE_CASE__ ) def __len__( self : Dict ) -> str: return len(self.features ) def __getitem__( self : Any , SCREAMING_SNAKE_CASE__ : Dict ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowerCAmelCase__ : a__ : List[InputFeatures] a__ : int = -100 def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> List[Any]: __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : List[Any] ) -> Any: return len(self.features ) def __getitem__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> InputFeatures: return self.features[i]
270
0
"""simple docstring""" def __UpperCAmelCase ( __lowerCamelCase ) -> float: lowercase__ : Optional[int] = 0 while len(__lowerCamelCase ) > 1: lowercase__ : Optional[int] = 0 # Consider two files with minimum cost to be merged for _ in range(2 ): lowercase__ : List[Any] = files.index(min(__lowerCamelCase ) ) temp += files[min_index] files.pop(__lowerCamelCase ) files.append(__lowerCamelCase ) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
16
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase__ ( __lowercase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : NestedDataStructureLike[PathLike] , SCREAMING_SNAKE_CASE__ : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE__ : Optional[Features] = None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : str , ) -> Union[str, Any]: super().__init__( SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ , streaming=SCREAMING_SNAKE_CASE__ , num_proc=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = path_or_paths if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else {self.split: path_or_paths} __lowerCamelCase = Text( cache_dir=SCREAMING_SNAKE_CASE__ , data_files=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : int ) -> Dict: # Build iterable dataset if self.streaming: __lowerCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE__ , download_mode=SCREAMING_SNAKE_CASE__ , verification_mode=SCREAMING_SNAKE_CASE__ , base_path=SCREAMING_SNAKE_CASE__ , num_proc=self.num_proc , ) __lowerCamelCase = self.builder.as_dataset( split=self.split , verification_mode=SCREAMING_SNAKE_CASE__ , in_memory=self.keep_in_memory ) return dataset
270
0
"""simple docstring""" import torch from diffusers import EulerDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class _lowerCAmelCase ( lowercase ): """simple docstring""" __UpperCAmelCase : str = (EulerDiscreteScheduler,) __UpperCAmelCase : Optional[Any] = 1_0 def _lowercase ( self : List[str], **UpperCAmelCase__ : Optional[int] ): __lowercase = { "num_train_timesteps": 1_1_0_0, "beta_start": 0.0_001, "beta_end": 0.02, "beta_schedule": "linear", } config.update(**UpperCAmelCase__ ) return config def _lowercase ( self : str ): for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=UpperCAmelCase__ ) def _lowercase ( self : Dict ): 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=UpperCAmelCase__, beta_end=UpperCAmelCase__ ) def _lowercase ( self : Optional[Any] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=UpperCAmelCase__ ) def _lowercase ( self : int ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=UpperCAmelCase__ ) def _lowercase ( self : Dict ): __lowercase = self.scheduler_classes[0] __lowercase = self.get_scheduler_config() __lowercase = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(self.num_inference_steps ) __lowercase = torch.manual_seed(0 ) __lowercase = self.dummy_model() __lowercase = self.dummy_sample_deter * scheduler.init_noise_sigma __lowercase = sample.to(UpperCAmelCase__ ) for i, t in enumerate(scheduler.timesteps ): __lowercase = scheduler.scale_model_input(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = model(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = scheduler.step(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, generator=UpperCAmelCase__ ) __lowercase = output.prev_sample __lowercase = torch.sum(torch.abs(UpperCAmelCase__ ) ) __lowercase = torch.mean(torch.abs(UpperCAmelCase__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1E-2 assert abs(result_mean.item() - 0.0_131 ) < 1E-3 def _lowercase ( self : List[Any] ): __lowercase = self.scheduler_classes[0] __lowercase = self.get_scheduler_config(prediction_type="v_prediction" ) __lowercase = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(self.num_inference_steps ) __lowercase = torch.manual_seed(0 ) __lowercase = self.dummy_model() __lowercase = self.dummy_sample_deter * scheduler.init_noise_sigma __lowercase = sample.to(UpperCAmelCase__ ) for i, t in enumerate(scheduler.timesteps ): __lowercase = scheduler.scale_model_input(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = model(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = scheduler.step(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, generator=UpperCAmelCase__ ) __lowercase = output.prev_sample __lowercase = torch.sum(torch.abs(UpperCAmelCase__ ) ) __lowercase = torch.mean(torch.abs(UpperCAmelCase__ ) ) assert abs(result_sum.item() - 0.0_002 ) < 1E-2 assert abs(result_mean.item() - 2.2_676E-06 ) < 1E-3 def _lowercase ( self : str ): __lowercase = self.scheduler_classes[0] __lowercase = self.get_scheduler_config() __lowercase = scheduler_class(**UpperCAmelCase__ ) scheduler.set_timesteps(self.num_inference_steps, device=UpperCAmelCase__ ) __lowercase = torch.manual_seed(0 ) __lowercase = self.dummy_model() __lowercase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __lowercase = sample.to(UpperCAmelCase__ ) for t in scheduler.timesteps: __lowercase = scheduler.scale_model_input(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = model(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = scheduler.step(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, generator=UpperCAmelCase__ ) __lowercase = output.prev_sample __lowercase = torch.sum(torch.abs(UpperCAmelCase__ ) ) __lowercase = torch.mean(torch.abs(UpperCAmelCase__ ) ) assert abs(result_sum.item() - 10.0_807 ) < 1E-2 assert abs(result_mean.item() - 0.0_131 ) < 1E-3 def _lowercase ( self : str ): __lowercase = self.scheduler_classes[0] __lowercase = self.get_scheduler_config() __lowercase = scheduler_class(**UpperCAmelCase__, use_karras_sigmas=UpperCAmelCase__ ) scheduler.set_timesteps(self.num_inference_steps, device=UpperCAmelCase__ ) __lowercase = torch.manual_seed(0 ) __lowercase = self.dummy_model() __lowercase = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu() __lowercase = sample.to(UpperCAmelCase__ ) for t in scheduler.timesteps: __lowercase = scheduler.scale_model_input(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = model(UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = scheduler.step(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__, generator=UpperCAmelCase__ ) __lowercase = output.prev_sample __lowercase = torch.sum(torch.abs(UpperCAmelCase__ ) ) __lowercase = torch.mean(torch.abs(UpperCAmelCase__ ) ) assert abs(result_sum.item() - 124.52_299_499_511_719 ) < 1E-2 assert abs(result_mean.item() - 0.16_213_932_633_399_963 ) < 1E-3
17
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
270
0
def _snake_case ( lowerCAmelCase : Tuple ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 1 SCREAMING_SNAKE_CASE_ : Optional[Any] = 2 while i * i <= n: SCREAMING_SNAKE_CASE_ : Optional[Any] = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors def _snake_case ( ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[Any] = 1 SCREAMING_SNAKE_CASE_ : List[str] = 1 while True: i += 1 t_num += i if count_divisors(lowerCAmelCase ) > 5_0_0: break return t_num if __name__ == "__main__": print(solution())
18
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ : int = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : Dict ) -> Tuple: if version.parse(scb.__version__ ) < version.parse('''1.4.12''' ): raise ImportWarning( '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n''' '''You can install it with `pip install "sacrebleu>=1.4.12"`.''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf'''] , reference_urls=[ '''https://github.com/m-popovic/chrF''', ] , ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int = CHRF.CHAR_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.WORD_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.BETA , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Optional[Any]: __lowerCamelCase = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) __lowerCamelCase = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase = CHRF(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sb_chrf.corpus_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
270
0
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('''9.1.0'''): __A ={ '''linear''': PIL.Image.Resampling.BILINEAR, '''bilinear''': PIL.Image.Resampling.BILINEAR, '''bicubic''': PIL.Image.Resampling.BICUBIC, '''lanczos''': PIL.Image.Resampling.LANCZOS, '''nearest''': PIL.Image.Resampling.NEAREST, } else: __A ={ '''linear''': PIL.Image.LINEAR, '''bilinear''': PIL.Image.BILINEAR, '''bicubic''': PIL.Image.BICUBIC, '''lanczos''': PIL.Image.LANCZOS, '''nearest''': PIL.Image.NEAREST, } def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = (images / 2 + 0.5).clamp(0 , 1 ) lowerCamelCase_ = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() lowerCamelCase_ = numpy_to_pil(lowerCamelCase__ ) return images def lowerCamelCase_ ( lowerCamelCase__ ): if images.ndim == 3: lowerCamelCase_ = images[None, ...] lowerCamelCase_ = (images * 2_5_5).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images lowerCamelCase_ = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: lowerCamelCase_ = [Image.fromarray(lowerCamelCase__ ) for image in images] return pil_images
19
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
270
0
from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class __snake_case : _a : int _a : TreeNode | None= None _a : TreeNode | None= None lowercase : Dict = namedtuple("""CoinsDistribResult""", """moves excess""") def _snake_case( SCREAMING_SNAKE_CASE__ ) -> int: if root is None: return 0 # Validation def count_nodes(SCREAMING_SNAKE_CASE__ ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(SCREAMING_SNAKE_CASE__ ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(SCREAMING_SNAKE_CASE__ ) != count_coins(SCREAMING_SNAKE_CASE__ ): raise ValueError("""The nodes number should be same as the number of coins""" ) # Main calculation def get_distrib(SCREAMING_SNAKE_CASE__ ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) lowercase , lowercase : int = get_distrib(node.left ) lowercase , lowercase : List[Any] = get_distrib(node.right ) lowercase : Optional[Any] = 1 - left_distrib_excess lowercase : Union[str, Any] = 1 - right_distrib_excess lowercase : List[Any] = ( left_distrib_moves + right_distrib_moves + abs(SCREAMING_SNAKE_CASE__ ) + abs(SCREAMING_SNAKE_CASE__ ) ) lowercase : Any = node.data - coins_to_left - coins_to_right return CoinsDistribResult(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return get_distrib(SCREAMING_SNAKE_CASE__ )[0] if __name__ == "__main__": import doctest doctest.testmod()
20
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : str = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Tuple=18 , SCREAMING_SNAKE_CASE__ : int=30 , SCREAMING_SNAKE_CASE__ : Any=4_00 , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , ) -> Union[str, Any]: __lowerCamelCase = size if size is not None else {'''height''': 20, '''width''': 20} __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = num_channels __lowerCamelCase = image_size __lowerCamelCase = min_resolution __lowerCamelCase = max_resolution __lowerCamelCase = size __lowerCamelCase = do_normalize __lowerCamelCase = do_convert_rgb __lowerCamelCase = [5_12, 10_24, 20_48, 40_96] __lowerCamelCase = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def __A ( self : Union[str, Any] ) -> Union[str, Any]: return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __A ( self : int ) -> Any: __lowerCamelCase = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' __lowerCamelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Dict = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Optional[Any] ) -> List[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self ) @property def __A ( self : Optional[int] ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> Dict: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : int ) -> str: __lowerCamelCase = self.image_processor_tester.prepare_dummy_image() __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) __lowerCamelCase = 20_48 __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __A ( self : Union[str, Any] ) -> Dict: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Dict ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 __lowerCamelCase = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches __lowerCamelCase = '''Hello''' __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : List[str] ) -> Any: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Tuple ) -> List[str]: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Any = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self , num_channels=4 ) __lowerCamelCase = 3 @property def __A ( self : List[Any] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : Optional[int] ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
270
0
from __future__ import annotations import time import numpy as np SCREAMING_SNAKE_CASE : Optional[Any] = [8, 5, 9, 7] SCREAMING_SNAKE_CASE : int = [ [2, 0, 1, 1], [0, 1, 2, 1], [4, 0, 0, 3], [0, 2, 1, 0], [1, 0, 3, 0], ] SCREAMING_SNAKE_CASE : Union[str, Any] = [ [3, 2, 1, 4], [0, 2, 5, 2], [5, 1, 0, 5], [1, 5, 3, 0], [3, 0, 3, 3], ] class _lowerCamelCase: def __init__( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, ) -> None: """simple docstring""" _lowercase : List[str] = claim_vector _lowercase : int = allocated_resources_table _lowercase : Dict = maximum_claim_table def UpperCamelCase ( self) -> list[int]: """simple docstring""" return [ sum(p_item[i] for p_item in self.__allocated_resources_table) for i in range(len(self.__allocated_resources_table[0])) ] def UpperCamelCase ( self) -> list[int]: """simple docstring""" return np.array(self.__claim_vector) - np.array( self.__processes_resource_summation()) def UpperCamelCase ( self) -> list[list[int]]: """simple docstring""" return [ list(np.array(self.__maximum_claim_table[i]) - np.array(lowerCamelCase)) for i, allocated_resource in enumerate(self.__allocated_resources_table) ] def UpperCamelCase ( self) -> dict[int, list[int]]: """simple docstring""" return {self.__need().index(lowerCamelCase): i for i in self.__need()} def UpperCamelCase ( self, **lowerCamelCase) -> None: """simple docstring""" _lowercase : Union[str, Any] = self.__need() _lowercase : List[str] = self.__allocated_resources_table _lowercase : List[Any] = self.__available_resources() _lowercase : Union[str, Any] = self.__need_index_manager() for kw, val in kwargs.items(): if kw and val is True: self.__pretty_data() print('_' * 50 + '\n') while need_list: _lowercase : int = False for each_need in need_list: _lowercase : Dict = True for index, need in enumerate(lowerCamelCase): if need > available_resources[index]: _lowercase : Tuple = False break if execution: _lowercase : Tuple = True # get the original index of the process from ind_ctrl db for original_need_index, need_clone in need_index_manager.items(): if each_need == need_clone: _lowercase : Tuple = original_need_index print(F'''Process {process_number + 1} is executing.''') # remove the process run from stack need_list.remove(lowerCamelCase) # update available/freed resources stack _lowercase : Optional[Any] = np.array(lowerCamelCase) + np.array( alloc_resources_table[process_number]) print( 'Updated available resource stack for processes: ' + ' '.join([str(lowerCamelCase) for x in available_resources])) break if safe: print('The process is in a safe state.\n') else: print('System in unsafe state. Aborting...\n') break def UpperCamelCase ( self) -> List[Any]: """simple docstring""" print(' ' * 9 + 'Allocated Resource Table') for item in self.__allocated_resources_table: print( F'''P{self.__allocated_resources_table.index(lowerCamelCase) + 1}''' + ' '.join(F'''{it:>8}''' for it in item) + '\n') print(' ' * 9 + 'System Resource Table') for item in self.__maximum_claim_table: print( F'''P{self.__maximum_claim_table.index(lowerCamelCase) + 1}''' + ' '.join(F'''{it:>8}''' for it in item) + '\n') print( 'Current Usage by Active Processes: ' + ' '.join(str(lowerCamelCase) for x in self.__claim_vector)) print( 'Initial Available Resources: ' + ' '.join(str(lowerCamelCase) for x in self.__available_resources())) time.sleep(1) if __name__ == "__main__": import doctest doctest.testmod()
21
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class lowerCAmelCase__ ( __lowercase ): def __init__( self : int ) -> Optional[int]: __lowerCamelCase = [] def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: self.events.append('''on_init_end''' ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: self.events.append('''on_train_begin''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Any: self.events.append('''on_train_end''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: self.events.append('''on_epoch_begin''' ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: self.events.append('''on_epoch_end''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.events.append('''on_step_begin''' ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: self.events.append('''on_step_end''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: self.events.append('''on_evaluate''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : str ) -> str: self.events.append('''on_predict''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: self.events.append('''on_save''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: self.events.append('''on_log''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: self.events.append('''on_prediction_step''' ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = tempfile.mkdtemp() def __A ( self : int ) -> List[str]: shutil.rmtree(self.output_dir ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Any=0 , SCREAMING_SNAKE_CASE__ : List[str]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[int]=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionModelConfig(a=SCREAMING_SNAKE_CASE__ , b=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionPreTrainedModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = TrainingArguments(self.output_dir , disable_tqdm=SCREAMING_SNAKE_CASE__ , report_to=[] , **SCREAMING_SNAKE_CASE__ ) return Trainer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , callbacks=SCREAMING_SNAKE_CASE__ , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) # Order doesn't matter __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) for cba, cba in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , cba.__class__ ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(cba.__class__ , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: __lowerCamelCase = ['''on_init_end''', '''on_train_begin'''] __lowerCamelCase = 0 __lowerCamelCase = len(trainer.get_eval_dataloader() ) __lowerCamelCase = ['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append('''on_epoch_begin''' ) for _ in range(SCREAMING_SNAKE_CASE__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('''on_log''' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('''on_save''' ) expected_events.append('''on_epoch_end''' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = self.get_trainer() __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # Callbacks passed at init are added to the default callbacks __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback __lowerCamelCase = self.get_trainer(disable_tqdm=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> str: __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] __lowerCamelCase = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(cb.__class__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # We can also add, pop, or remove by instance __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> Any: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='''ignore''' , category=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # Independent log/save/eval __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='''steps''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='''epoch''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # A bit of everything __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy='''steps''' , ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # warning should be emitted for duplicated callbacks with patch('''transformers.trainer_callback.logger.warning''' ) as warn_mock: __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(SCREAMING_SNAKE_CASE__ ) in warn_mock.call_args[0][0]
270
0
'''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 :Union[str, Any] = logging.getLogger(__name__) def UpperCAmelCase_ ( __lowercase : str ) -> Tuple: '''simple docstring''' _UpperCAmelCase = git.Repo(search_parent_directories=__lowercase ) _UpperCAmelCase = { "repo_id": str(__lowercase ), "repo_sha": str(repo.head.object.hexsha ), "repo_branch": str(repo.active_branch ), } with open(os.path.join(__lowercase , "git_log.json" ) , "w" ) as f: json.dump(__lowercase , __lowercase , indent=4 ) def UpperCAmelCase_ ( __lowercase : Tuple ) -> Tuple: '''simple docstring''' if params.n_gpu <= 0: _UpperCAmelCase = 0 _UpperCAmelCase = -1 _UpperCAmelCase = True _UpperCAmelCase = False return assert torch.cuda.is_available() logger.info("Initializing GPUs" ) if params.n_gpu > 1: assert params.local_rank != -1 _UpperCAmelCase = int(os.environ["WORLD_SIZE"] ) _UpperCAmelCase = int(os.environ["N_GPU_NODE"] ) _UpperCAmelCase = int(os.environ["RANK"] ) # number of nodes / node ID _UpperCAmelCase = params.world_size // params.n_gpu_per_node _UpperCAmelCase = params.global_rank // params.n_gpu_per_node _UpperCAmelCase = 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 _UpperCAmelCase = 1 _UpperCAmelCase = 0 _UpperCAmelCase = 0 _UpperCAmelCase = 0 _UpperCAmelCase = 1 _UpperCAmelCase = 1 _UpperCAmelCase = 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 _UpperCAmelCase = params.node_id == 0 and params.local_rank == 0 _UpperCAmelCase = params.n_nodes > 1 # summary _UpperCAmelCase = 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 UpperCAmelCase_ ( __lowercase : Union[str, Any] ) -> str: '''simple docstring''' np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
22
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowerCAmelCase__ : def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) __lowerCamelCase = img __lowerCamelCase = img.shape[1] __lowerCamelCase = img.shape[0] __lowerCamelCase = dst_width __lowerCamelCase = dst_height __lowerCamelCase = self.src_w / self.dst_w __lowerCamelCase = self.src_h / self.dst_h __lowerCamelCase = __lowerCamelCase = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def __A ( self : List[Any] ) -> str: for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase = self.img[self.get_y(SCREAMING_SNAKE_CASE__ )][self.get_x(SCREAMING_SNAKE_CASE__ )] def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_x * x ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_y * y ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = 800, 600 SCREAMING_SNAKE_CASE__ : int = imread("image_data/lena.jpg", 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
270
0
'''simple docstring''' import datasets UpperCamelCase__: Tuple = "\\n@InProceedings{conneau2018xnli,\n author = \"Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin\",\n title = \"XNLI: Evaluating Cross-lingual Sentence Representations\",\n booktitle = \"Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing\",\n year = \"2018\",\n publisher = \"Association for Computational Linguistics\",\n location = \"Brussels, Belgium\",\n}\n" UpperCamelCase__: List[str] = "\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n" UpperCamelCase__: List[Any] = "\nComputes XNLI score which is just simple accuracy.\nArgs:\n predictions: Predicted labels.\n references: Ground truth labels.\nReturns:\n 'accuracy': accuracy\nExamples:\n\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> xnli_metric = datasets.load_metric(\"xnli\")\n >>> results = xnli_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n" def snake_case_ ( _lowerCAmelCase : Tuple , _lowerCAmelCase : Tuple ) -> List[str]: return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class SCREAMING_SNAKE_CASE( datasets.Metric ): """simple docstring""" def A ( self : List[Any] ) -> Optional[int]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int64''' if self.config_name != '''sts-b''' else '''float32''' ), '''references''': datasets.Value('''int64''' if self.config_name != '''sts-b''' else '''float32''' ), } ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' , ) def A ( self : Dict , __snake_case : Union[str, Any] , __snake_case : Union[str, Any] ) -> List[str]: return {"accuracy": simple_accuracy(__snake_case , __snake_case )}
23
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( __lowerCAmelCase : dict , __lowerCAmelCase : str , __lowerCAmelCase : set , __lowerCAmelCase : set , __lowerCAmelCase : dict , __lowerCAmelCase : dict , __lowerCAmelCase : PriorityQueue , __lowerCAmelCase : dict , __lowerCAmelCase : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCamelCase = cst_fwd.get(__lowerCAmelCase , np.inf ) __lowerCamelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCamelCase = new_cost_f __lowerCamelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCamelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : dict , __lowerCAmelCase : dict ) -> int: __lowerCamelCase = -1 __lowerCamelCase = set() __lowerCamelCase = set() __lowerCamelCase = {source: 0} __lowerCamelCase = {destination: 0} __lowerCamelCase = {source: None} __lowerCamelCase = {destination: None} __lowerCamelCase = PriorityQueue() __lowerCamelCase = PriorityQueue() __lowerCamelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCamelCase , __lowerCamelCase = queue_forward.get() visited_forward.add(__lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = queue_backward.get() visited_backward.add(__lowerCAmelCase ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCamelCase = shortest_distance return shortest_path_distance SCREAMING_SNAKE_CASE__ : List[Any] = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } SCREAMING_SNAKE_CASE__ : Optional[int] = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
270
0
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model snake_case_ = '0.12' # assumed parallelism: 8 if is_torch_available(): import torch def lowerCamelCase__ ( snake_case_ : Dict , snake_case_ : List[str] , snake_case_ : str=None ) -> List[str]: if rng is None: __snake_case = random.Random() __snake_case = 1 for dim in shape: total_dims *= dim __snake_case = [] for _ in range(snake_case_ ): values.append(rng.randint(0 , vocab_size - 1 ) ) __snake_case = np.array(snake_case_ , dtype=jnp.intaa ).reshape(snake_case_ ) return output def lowerCamelCase__ ( snake_case_ : int , snake_case_ : List[str]=None ) -> Tuple: __snake_case = ids_tensor(snake_case_ , vocab_size=2 , rng=snake_case_ ) # make sure that at least one token is attended to for each batch __snake_case = 1 return attn_mask @require_flax class SCREAMING_SNAKE_CASE__ : A_ : Optional[int] = None A_ : Union[str, Any] = () def a (self : int ): """simple docstring""" __snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 __snake_case = 2 __snake_case = inputs['''input_ids'''].shape[-1] // 2 __snake_case = inputs['''input_ids'''][:max_batch_size, :sequence_length] __snake_case = jnp.ones_like(a__ ) __snake_case = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens __snake_case = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` __snake_case = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def a (self : Optional[int] ): """simple docstring""" __snake_case , __snake_case , __snake_case , __snake_case = self._get_input_ids_and_config() __snake_case = False __snake_case = max_length __snake_case = 0 for model_class in self.all_generative_model_classes: __snake_case = model_class(a__ ) __snake_case = model_class.__name__[4:] # Skip the "Flax" at the beginning __snake_case = getattr(a__ , a__ ) __snake_case = pt_model_class(a__ ).eval() __snake_case = load_flax_weights_in_pytorch_model(a__ , flax_model.params ) __snake_case = flax_model.generate(a__ ).sequences __snake_case = pt_model.generate(torch.tensor(a__ , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: __snake_case = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def a (self : Optional[int] ): """simple docstring""" __snake_case , __snake_case , __snake_case , __snake_case = self._get_input_ids_and_config() __snake_case = False __snake_case = max_length for model_class in self.all_generative_model_classes: __snake_case = model_class(a__ ) __snake_case = model.generate(a__ ).sequences self.assertEqual(generation_outputs.shape[-1] , a__ ) __snake_case = jit(model.generate ) __snake_case = jit_generate(a__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def a (self : List[Any] ): """simple docstring""" __snake_case , __snake_case , __snake_case , __snake_case = self._get_input_ids_and_config() __snake_case = True __snake_case = max_length for model_class in self.all_generative_model_classes: __snake_case = model_class(a__ ) __snake_case = model.generate(a__ ).sequences self.assertEqual(generation_outputs.shape[-1] , a__ ) __snake_case = jit(model.generate ) __snake_case = jit_generate(a__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def a (self : int ): """simple docstring""" __snake_case , __snake_case , __snake_case , __snake_case = self._get_input_ids_and_config() __snake_case = False __snake_case = max_length __snake_case = 2 for model_class in self.all_generative_model_classes: __snake_case = model_class(a__ ) __snake_case = model.generate(a__ ).sequences self.assertEqual(generation_outputs.shape[-1] , a__ ) __snake_case = jit(model.generate ) __snake_case = jit_generate(a__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def a (self : Optional[int] ): """simple docstring""" __snake_case , __snake_case , __snake_case , __snake_case = self._get_input_ids_and_config() __snake_case = False __snake_case = max_length __snake_case = 2 __snake_case = 2 for model_class in self.all_generative_model_classes: __snake_case = model_class(a__ ) __snake_case = model.generate(a__ ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def a (self : List[str] ): """simple docstring""" __snake_case , __snake_case , __snake_case , __snake_case = self._get_input_ids_and_config() __snake_case = True __snake_case = max_length __snake_case = 0.8 __snake_case = 10 __snake_case = 0.3 __snake_case = 1 __snake_case = 8 __snake_case = 9 for model_class in self.all_generative_model_classes: __snake_case = model_class(a__ ) __snake_case = model.generate(a__ ).sequences self.assertEqual(generation_outputs.shape[-1] , a__ ) __snake_case = jit(model.generate ) __snake_case = jit_generate(a__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def a (self : str ): """simple docstring""" __snake_case , __snake_case , __snake_case , __snake_case = self._get_input_ids_and_config() __snake_case = max_length __snake_case = 1 __snake_case = 8 __snake_case = 9 for model_class in self.all_generative_model_classes: __snake_case = model_class(a__ ) __snake_case = model.generate(a__ ).sequences self.assertEqual(generation_outputs.shape[-1] , a__ ) __snake_case = jit(model.generate ) __snake_case = jit_generate(a__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def a (self : Dict ): """simple docstring""" __snake_case , __snake_case , __snake_case , __snake_case = self._get_input_ids_and_config() __snake_case = max_length __snake_case = 2 __snake_case = 1 __snake_case = 8 __snake_case = 9 for model_class in self.all_generative_model_classes: __snake_case = model_class(a__ ) __snake_case = model.generate(a__ ).sequences self.assertEqual(generation_outputs.shape[-1] , a__ ) __snake_case = jit(model.generate ) __snake_case = jit_generate(a__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def a (self : Optional[Any] ): """simple docstring""" __snake_case , __snake_case , __snake_case , __snake_case = self._get_input_ids_and_config() # pad attention mask on the left __snake_case = attention_mask.at[(0, 0)].set(0 ) __snake_case = False __snake_case = max_length for model_class in self.all_generative_model_classes: __snake_case = model_class(a__ ) __snake_case = model.generate(a__ , attention_mask=a__ ).sequences self.assertEqual(generation_outputs.shape[-1] , a__ ) __snake_case = jit(model.generate ) __snake_case = jit_generate(a__ , attention_mask=a__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def a (self : Any ): """simple docstring""" __snake_case , __snake_case , __snake_case , __snake_case = self._get_input_ids_and_config() # pad attention mask on the left __snake_case = attention_mask.at[(0, 0)].set(0 ) __snake_case = True __snake_case = max_length for model_class in self.all_generative_model_classes: __snake_case = model_class(a__ ) __snake_case = model.generate(a__ , attention_mask=a__ ).sequences self.assertEqual(generation_outputs.shape[-1] , a__ ) __snake_case = jit(model.generate ) __snake_case = jit_generate(a__ , attention_mask=a__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def a (self : str ): """simple docstring""" __snake_case , __snake_case , __snake_case , __snake_case = self._get_input_ids_and_config() # pad attention mask on the left __snake_case = attention_mask.at[(0, 0)].set(0 ) __snake_case = 2 __snake_case = max_length for model_class in self.all_generative_model_classes: __snake_case = model_class(a__ ) __snake_case = model.generate(a__ , attention_mask=a__ ).sequences self.assertEqual(generation_outputs.shape[-1] , a__ ) __snake_case = jit(model.generate ) __snake_case = jit_generate(a__ , attention_mask=a__ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): def a (self : Any ): """simple docstring""" __snake_case = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-bert''' ) __snake_case = FlaxAutoModelForCausalLM.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' ) __snake_case = '''Hello world''' __snake_case = tokenizer(a__ , return_tensors='''np''' ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(a__ , '''do_samples''' ): model.generate(a__ , do_samples=a__ ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(a__ , '''foo''' ): __snake_case = {'''foo''': '''bar'''} model.generate(a__ , **a__ )
24
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : List[Any] = TypeVar("T") def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (position - 1) // 2 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 1 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 2 class lowerCAmelCase__ ( Generic[T] ): def __init__( self : List[str] ) -> None: __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 def __len__( self : Optional[int] ) -> int: return self.elements def __repr__( self : Optional[int] ) -> str: return str(self.heap ) def __A ( self : Union[str, Any] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def __A ( self : str , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __lowerCamelCase = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __lowerCamelCase , __lowerCamelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowerCamelCase , __lowerCamelCase = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Update the weight of the given key __lowerCamelCase = self.position_map[elem] __lowerCamelCase = (elem, weight) if position > 0: __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __lowerCamelCase = self.position_map[elem] if curr_pos == 0: return None __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __lowerCamelCase = self.position_map[elem] __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: # Swap the nodes at the given positions __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase , __lowerCamelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowerCamelCase = nodea_pos __lowerCamelCase = nodea_pos class lowerCAmelCase__ ( Generic[T] ): def __init__( self : Tuple ) -> None: __lowerCamelCase = {} __lowerCamelCase = 0 def __repr__( self : Optional[int] ) -> str: return str(self.connections ) def __len__( self : List[str] ) -> int: return self.nodes def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __lowerCamelCase = {} self.nodes += 1 def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = weight __lowerCamelCase = weight def __magic_name__ ( __lowerCAmelCase : GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: __lowerCamelCase = {node: maxsize for node in graph.connections} __lowerCamelCase = {node: None for node in graph.connections} __lowerCamelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__lowerCAmelCase , __lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization __lowerCamelCase = priority_queue.extract_min() __lowerCamelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node # running prim's algorithm while not priority_queue.is_empty(): __lowerCamelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node return dist, parent
270
0
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging UpperCAmelCase__ : Any = logging.get_logger(__name__) # pylint: disable=invalid-name class lowerCAmelCase_ (a__ ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) -> Optional[int]: """simple docstring""" super().__init__() self.register_modules( vae=SCREAMING_SNAKE_CASE__ , text_encoder=SCREAMING_SNAKE_CASE__ , tokenizer=SCREAMING_SNAKE_CASE__ , unet=SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ , feature_extractor=SCREAMING_SNAKE_CASE__ , ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ = "auto" ) -> List[str]: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory SCREAMING_SNAKE_CASE__ : Dict = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self ) -> Optional[int]: """simple docstring""" self.enable_attention_slicing(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def __call__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = 5_12 , SCREAMING_SNAKE_CASE__ = 5_12 , SCREAMING_SNAKE_CASE__ = 50 , SCREAMING_SNAKE_CASE__ = 7.5 , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 1 , SCREAMING_SNAKE_CASE__ = 0.0 , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "pil" , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 1 , SCREAMING_SNAKE_CASE__ = None , **SCREAMING_SNAKE_CASE__ , ) -> Union[str, Any]: """simple docstring""" if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : str = 1 elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : List[str] = len(SCREAMING_SNAKE_CASE__ ) else: raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(SCREAMING_SNAKE_CASE__ )}''' ) 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(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) or callback_steps <= 0) ): raise ValueError( F'''`callback_steps` has to be a positive integer but is {callback_steps} of type''' F''' {type(SCREAMING_SNAKE_CASE__ )}.''' ) # get prompt text embeddings SCREAMING_SNAKE_CASE__ : int = self.tokenizer( SCREAMING_SNAKE_CASE__ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , ) SCREAMING_SNAKE_CASE__ : str = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: SCREAMING_SNAKE_CASE__ : Dict = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] ) logger.warning( """The following part of your input was truncated because CLIP can only handle sequences up to""" F''' {self.tokenizer.model_max_length} tokens: {removed_text}''' ) SCREAMING_SNAKE_CASE__ : str = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: SCREAMING_SNAKE_CASE__ : Dict = self.text_encoder(text_input_ids.to(self.device ) )[0] # duplicate text embeddings for each generation per prompt, using mps friendly method SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = text_embeddings.shape SCREAMING_SNAKE_CASE__ : int = text_embeddings.repeat(1 , SCREAMING_SNAKE_CASE__ , 1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = text_embeddings.view(bs_embed * num_images_per_prompt , SCREAMING_SNAKE_CASE__ , -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. SCREAMING_SNAKE_CASE__ : Optional[int] = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: SCREAMING_SNAKE_CASE__ : List[str] if negative_prompt is None: SCREAMING_SNAKE_CASE__ : str = [""""""] elif type(SCREAMING_SNAKE_CASE__ ) is not type(SCREAMING_SNAKE_CASE__ ): raise TypeError( F'''`negative_prompt` should be the same type to `prompt`, but got {type(SCREAMING_SNAKE_CASE__ )} !=''' F''' {type(SCREAMING_SNAKE_CASE__ )}.''' ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): SCREAMING_SNAKE_CASE__ : Optional[Any] = [negative_prompt] elif batch_size != len(SCREAMING_SNAKE_CASE__ ): raise ValueError( F'''`negative_prompt`: {negative_prompt} has batch size {len(SCREAMING_SNAKE_CASE__ )}, but `prompt`:''' F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches''' """ the batch size of `prompt`.""" ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = negative_prompt SCREAMING_SNAKE_CASE__ : Tuple = text_input_ids.shape[-1] SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer( SCREAMING_SNAKE_CASE__ , padding="""max_length""" , max_length=SCREAMING_SNAKE_CASE__ , truncation=SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" , ) SCREAMING_SNAKE_CASE__ : List[str] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method SCREAMING_SNAKE_CASE__ : Any = uncond_embeddings.shape[1] SCREAMING_SNAKE_CASE__ : Any = uncond_embeddings.repeat(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) SCREAMING_SNAKE_CASE__ : Tuple = uncond_embeddings.view(batch_size * num_images_per_prompt , SCREAMING_SNAKE_CASE__ , -1 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes SCREAMING_SNAKE_CASE__ : Optional[int] = 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`. SCREAMING_SNAKE_CASE__ : List[str] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) SCREAMING_SNAKE_CASE__ : str = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) SCREAMING_SNAKE_CASE__ : Optional[int] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.randn( SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE__ ).to(self.device ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , device="""cpu""" , dtype=SCREAMING_SNAKE_CASE__ ).to( self.device ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.randn( SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , device=self.device , dtype=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.randn(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , device=self.device , dtype=SCREAMING_SNAKE_CASE__ ) else: if latents_reference.shape != latents_shape: raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = latents_reference.to(self.device ) SCREAMING_SNAKE_CASE__ : Any = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images SCREAMING_SNAKE_CASE__ : List[str] = (latents_shape[3] - latents_shape_reference[3]) // 2 SCREAMING_SNAKE_CASE__ : Optional[int] = (latents_shape[2] - latents_shape_reference[2]) // 2 SCREAMING_SNAKE_CASE__ : Dict = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx SCREAMING_SNAKE_CASE__ : Dict = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy SCREAMING_SNAKE_CASE__ : int = 0 if dx < 0 else dx SCREAMING_SNAKE_CASE__ : Tuple = 0 if dy < 0 else dy SCREAMING_SNAKE_CASE__ : List[Any] = max(-dx , 0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = max(-dy , 0 ) # import pdb # pdb.set_trace() SCREAMING_SNAKE_CASE__ : List[Any] = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE__ ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand SCREAMING_SNAKE_CASE__ : Optional[int] = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler SCREAMING_SNAKE_CASE__ : int = 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] SCREAMING_SNAKE_CASE__ : Tuple = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) SCREAMING_SNAKE_CASE__ : Optional[int] = {} if accepts_eta: SCREAMING_SNAKE_CASE__ : Optional[Any] = eta for i, t in enumerate(self.progress_bar(SCREAMING_SNAKE_CASE__ ) ): # expand the latents if we are doing classifier free guidance SCREAMING_SNAKE_CASE__ : List[str] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents SCREAMING_SNAKE_CASE__ : List[str] = self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # predict the noise residual SCREAMING_SNAKE_CASE__ : Dict = self.unet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ ).sample # perform guidance if do_classifier_free_guidance: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = noise_pred.chunk(2 ) SCREAMING_SNAKE_CASE__ : Dict = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 SCREAMING_SNAKE_CASE__ : int = self.scheduler.step(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = 1 / 0.18215 * latents SCREAMING_SNAKE_CASE__ : Any = self.vae.decode(SCREAMING_SNAKE_CASE__ ).sample SCREAMING_SNAKE_CASE__ : Dict = (image / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 SCREAMING_SNAKE_CASE__ : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: SCREAMING_SNAKE_CASE__ : str = self.feature_extractor(self.numpy_to_pil(SCREAMING_SNAKE_CASE__ ) , return_tensors="""pt""" ).to( self.device ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = self.safety_checker( images=SCREAMING_SNAKE_CASE__ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: SCREAMING_SNAKE_CASE__ : Tuple = None if output_type == "pil": SCREAMING_SNAKE_CASE__ : Dict = self.numpy_to_pil(SCREAMING_SNAKE_CASE__ ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=SCREAMING_SNAKE_CASE__ , nsfw_content_detected=SCREAMING_SNAKE_CASE__ )
25
from __future__ import annotations from statistics import mean def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> list[int]: __lowerCamelCase = [0] * no_of_processes __lowerCamelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] __lowerCamelCase = [] __lowerCamelCase = 0 __lowerCamelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCamelCase = [] __lowerCamelCase = -1 for i in range(__lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: __lowerCamelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCamelCase = i total_time += burst_time[target_process] completed += 1 __lowerCamelCase = 0 __lowerCamelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : int , __lowerCAmelCase : list[int] ) -> list[int]: __lowerCamelCase = [0] * no_of_processes for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") SCREAMING_SNAKE_CASE__ : Tuple = 4 SCREAMING_SNAKE_CASE__ : Optional[int] = [2, 5, 3, 7] SCREAMING_SNAKE_CASE__ : List[str] = [0, 0, 0, 0] SCREAMING_SNAKE_CASE__ : str = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( F'{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t' F'{waiting_time[i]}\t\t\t\t{turn_around_time[i]}' ) print(F'\nAverage waiting time = {mean(waiting_time):.5f}') print(F'Average turnaround time = {mean(turn_around_time):.5f}')
270
0
import random def lowerCAmelCase_ ( snake_case_ ): _A : Optional[Any] = num - 1 _A : Optional[int] = 0 while s % 2 == 0: _A : str = s // 2 t += 1 for _ in range(5 ): _A : Tuple = random.randrange(2,num - 1 ) _A : Dict = pow(snake_case_,snake_case_,snake_case_ ) if v != 1: _A : int = 0 while v != (num - 1): if i == t - 1: return False else: _A : int = i + 1 _A : Dict = (v**2) % num return True def lowerCAmelCase_ ( snake_case_ ): if num < 2: return False _A : int = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(snake_case_ ) def lowerCAmelCase_ ( snake_case_ = 1024 ): while True: _A : List[Any] = random.randrange(2 ** (keysize - 1),2 ** (keysize) ) if is_prime_low_num(snake_case_ ): return num if __name__ == "__main__": _snake_case = generate_large_prime() print(("Prime number:", num)) print(("is_prime_low_num:", is_prime_low_num(num)))
26
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( __lowercase ): @staticmethod @abstractmethod def __A ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> str: raise NotImplementedError() @abstractmethod def __A ( self : Optional[int] ) -> Union[str, Any]: raise NotImplementedError()
270
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging __lowercase : int = logging.get_logger(__name__) __lowercase : Optional[Any] = { 'microsoft/trocr-base-handwritten': ( 'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json' ), # See all TrOCR models at https://huggingface.co/models?filter=trocr } class __UpperCamelCase ( lowerCAmelCase_ ): A_ = "trocr" A_ = ["past_key_values"] A_ = { "num_attention_heads": "decoder_attention_heads", "hidden_size": "d_model", "num_hidden_layers": "decoder_layers", } def __init__( self , __a=5_0265 , __a=1024 , __a=12 , __a=16 , __a=4096 , __a="gelu" , __a=512 , __a=0.1 , __a=0.0 , __a=0.0 , __a=2 , __a=0.02 , __a=0.0 , __a=True , __a=False , __a=True , __a=True , __a=1 , __a=0 , __a=2 , **__a , ): '''simple docstring''' __a : Union[str, Any] = vocab_size __a : Dict = d_model __a : Optional[Any] = decoder_layers __a : Tuple = decoder_attention_heads __a : int = decoder_ffn_dim __a : Union[str, Any] = activation_function __a : List[str] = max_position_embeddings __a : List[Any] = dropout __a : Union[str, Any] = attention_dropout __a : Optional[int] = activation_dropout __a : Optional[Any] = init_std __a : List[Any] = decoder_layerdrop __a : int = use_cache __a : List[Any] = scale_embedding __a : Any = use_learned_position_embeddings __a : List[str] = layernorm_embedding super().__init__( pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , decoder_start_token_id=__a , **__a , )
27
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue_model_parallelism.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> List[Any]: if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=SCREAMING_SNAKE_CASE__ , ) assert hasattr(self , '''env''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: # configuration for running training on smdistributed Model Parallel __lowerCamelCase = { '''enabled''': True, '''processes_per_host''': 8, } __lowerCamelCase = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __lowerCamelCase = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __lowerCamelCase = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=SCREAMING_SNAKE_CASE__ , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE__ , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 5_00, } , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE__ , py_version='''py36''' , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: TrainingJobAnalytics(SCREAMING_SNAKE_CASE__ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: # create estimator __lowerCamelCase = self.create_estimator(SCREAMING_SNAKE_CASE__ ) # run training estimator.fit() # result dataframe __lowerCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # 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} , SCREAMING_SNAKE_CASE__ )
270
0
'''simple docstring''' import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" _SCREAMING_SNAKE_CASE = 42 _SCREAMING_SNAKE_CASE = None def __lowerCamelCase ( A__ , A__=0.999 , A__="cosine" , ) -> Tuple: """simple docstring""" if alpha_transform_type == "cosine": def alpha_bar_fn(A__ ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(A__ ): return math.exp(t * -12.0 ) else: raise ValueError(F"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) UpperCamelCase = [] for i in range(A__ ): UpperCamelCase = i / num_diffusion_timesteps UpperCamelCase = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(A__ ) / alpha_bar_fn(A__ ) , A__ ) ) return torch.tensor(A__ , dtype=torch.floataa ) class SCREAMING_SNAKE_CASE ( _a , _a ): """simple docstring""" @register_to_config def __init__( self : List[str] , UpperCamelCase__ : int = 1_0_0_0 , UpperCamelCase__ : str = "fixed_small_log" , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[float] = 1.0 , UpperCamelCase__ : str = "epsilon" , UpperCamelCase__ : str = "squaredcos_cap_v2" , ): """simple docstring""" if beta_schedule != "squaredcos_cap_v2": raise ValueError('UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'' ) UpperCamelCase = betas_for_alpha_bar(UpperCamelCase__ ) UpperCamelCase = 1.0 - self.betas UpperCamelCase = torch.cumprod(self.alphas , dim=0 ) UpperCamelCase = torch.tensor(1.0 ) # standard deviation of the initial noise distribution UpperCamelCase = 1.0 # setable values UpperCamelCase = None UpperCamelCase = torch.from_numpy(np.arange(0 , UpperCamelCase__ )[::-1].copy() ) UpperCamelCase = variance_type def A ( self : Dict , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : Optional[int] = None ): """simple docstring""" return sample def A ( self : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, torch.device] = None ): """simple docstring""" UpperCamelCase = num_inference_steps UpperCamelCase = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) UpperCamelCase = (np.arange(0 , UpperCamelCase__ ) * step_ratio).round()[::-1].copy().astype(np.intaa ) UpperCamelCase = torch.from_numpy(UpperCamelCase__ ).to(UpperCamelCase__ ) def A ( self : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Tuple=None ): """simple docstring""" if prev_timestep is None: UpperCamelCase = t - 1 UpperCamelCase = self.alphas_cumprod[t] UpperCamelCase = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one UpperCamelCase = 1 - alpha_prod_t UpperCamelCase = 1 - alpha_prod_t_prev if prev_timestep == t - 1: UpperCamelCase = self.betas[t] else: UpperCamelCase = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample UpperCamelCase = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: UpperCamelCase = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": UpperCamelCase = torch.log(torch.clamp(UpperCamelCase__ , min=1E-2_0 ) ) UpperCamelCase = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler UpperCamelCase = variance.log() UpperCamelCase = beta.log() UpperCamelCase = (predicted_variance + 1) / 2 UpperCamelCase = frac * max_log + (1 - frac) * min_log return variance def A ( self : int , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : int , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : str=None , UpperCamelCase__ : bool = True , ): """simple docstring""" UpperCamelCase = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": UpperCamelCase , UpperCamelCase = torch.split(UpperCamelCase__ , sample.shape[1] , dim=1 ) else: UpperCamelCase = None # 1. compute alphas, betas if prev_timestep is None: UpperCamelCase = t - 1 UpperCamelCase = self.alphas_cumprod[t] UpperCamelCase = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one UpperCamelCase = 1 - alpha_prod_t UpperCamelCase = 1 - alpha_prod_t_prev if prev_timestep == t - 1: UpperCamelCase = self.betas[t] UpperCamelCase = self.alphas[t] else: UpperCamelCase = 1 - alpha_prod_t / alpha_prod_t_prev UpperCamelCase = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": UpperCamelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": UpperCamelCase = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`""" ' for the UnCLIPScheduler.' ) # 3. Clip "predicted x_0" if self.config.clip_sample: UpperCamelCase = torch.clamp( UpperCamelCase__ , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCamelCase = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t UpperCamelCase = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf UpperCamelCase = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise UpperCamelCase = 0 if t > 0: UpperCamelCase = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=UpperCamelCase__ , device=model_output.device ) UpperCamelCase = self._get_variance( UpperCamelCase__ , predicted_variance=UpperCamelCase__ , prev_timestep=UpperCamelCase__ , ) if self.variance_type == "fixed_small_log": UpperCamelCase = variance elif self.variance_type == "learned_range": UpperCamelCase = (0.5 * variance).exp() else: raise ValueError( f"""variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`""" ' for the UnCLIPScheduler.' ) UpperCamelCase = variance * variance_noise UpperCamelCase = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=UpperCamelCase__ , pred_original_sample=UpperCamelCase__ ) def A ( self : int , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : torch.FloatTensor , UpperCamelCase__ : torch.IntTensor , ): """simple docstring""" UpperCamelCase = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) UpperCamelCase = timesteps.to(original_samples.device ) UpperCamelCase = alphas_cumprod[timesteps] ** 0.5 UpperCamelCase = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): UpperCamelCase = sqrt_alpha_prod.unsqueeze(-1 ) UpperCamelCase = (1 - alphas_cumprod[timesteps]) ** 0.5 UpperCamelCase = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): UpperCamelCase = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) UpperCamelCase = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
28
from __future__ import annotations from fractions import Fraction def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def __magic_name__ ( __lowerCAmelCase : int ) -> list[str]: __lowerCamelCase = [] __lowerCamelCase = 11 __lowerCamelCase = int('''1''' + '''0''' * digit_len ) for num in range(__lowerCAmelCase , __lowerCAmelCase ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(__lowerCAmelCase , __lowerCAmelCase ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 __lowerCamelCase = 10 return solutions def __magic_name__ ( __lowerCAmelCase : int = 2 ) -> int: __lowerCamelCase = 1.0 for fraction in fraction_list(__lowerCAmelCase ): __lowerCamelCase = Fraction(__lowerCAmelCase ) result *= frac.denominator / frac.numerator return int(__lowerCAmelCase ) if __name__ == "__main__": print(solution())
270
0
def lowercase__ ( __snake_case : int = 4_000_000 ): '''simple docstring''' UpperCAmelCase_ : int = [0, 1] UpperCAmelCase_ : List[str] = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 UpperCAmelCase_ : str = 0 for j in range(len(__snake_case ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(F'{solution() = }')
29
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipTextConfig", "BlipVisionConfig", ], "processing_blip": ["BlipProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = ["BlipImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipModel", "BlipPreTrainedModel", "BlipForConditionalGeneration", "BlipForQuestionAnswering", "BlipVisionModel", "BlipTextModel", "BlipForImageTextRetrieval", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBlipModel", "TFBlipPreTrainedModel", "TFBlipForConditionalGeneration", "TFBlipForQuestionAnswering", "TFBlipVisionModel", "TFBlipTextModel", "TFBlipForImageTextRetrieval", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
30
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) __SCREAMING_SNAKE_CASE : int = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : str = ["""NllbTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __SCREAMING_SNAKE_CASE : Union[str, Any] = ["""NllbTokenizerFast"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb import NllbTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_nllb_fast import NllbTokenizerFast else: import sys __SCREAMING_SNAKE_CASE : List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
31
import pprint import requests SCREAMING_SNAKE_CASE__ : str = "https://zenquotes.io/api" def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = random_quotes() pprint.pprint(response)
270
0
from __future__ import annotations import math def SCREAMING_SNAKE_CASE_ ( __A : int ) -> list[int]: """simple docstring""" if num <= 0: a_ : str = F"""{num}: Invalid input, please enter a positive integer.""" raise ValueError(__A ) a_ : Tuple = [True] * (num + 1) a_ : Union[str, Any] = [] a_ : Optional[int] = 2 a_ : Optional[Any] = int(math.sqrt(__A ) ) while start <= end: # If start is a prime if sieve[start] is True: prime.append(__A ) # Set multiples of start be False for i in range(start * start , num + 1 , __A ): if sieve[i] is True: a_ : Any = False start += 1 for j in range(end + 1 , num + 1 ): if sieve[j] is True: prime.append(__A ) return prime if __name__ == "__main__": print(prime_sieve(int(input('Enter a positive integer: ').strip())))
32
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __magic_name__ ( __lowerCAmelCase : int ) -> int: __lowerCamelCase = prime_factors(__lowerCAmelCase ) if is_square_free(__lowerCAmelCase ): return -1 if len(__lowerCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
270
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor __A : Dict = logging.get_logger(__name__) class _UpperCAmelCase ( _A ): def __init__( self : int , *A : Tuple , **A : int ) -> None: warnings.warn( '''The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use VideoMAEImageProcessor instead.''' , A , ) super().__init__(*A , **A )
33
import argparse import collections import json import os import re import string import sys import numpy as np SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"\b(a|an|the)\b", re.UNICODE) SCREAMING_SNAKE_CASE__ : int = None def __magic_name__ ( ) -> str: __lowerCamelCase = argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.''' ) parser.add_argument('''data_file''' , metavar='''data.json''' , help='''Input data JSON file.''' ) parser.add_argument('''pred_file''' , metavar='''pred.json''' , help='''Model predictions.''' ) parser.add_argument( '''--out-file''' , '''-o''' , metavar='''eval.json''' , help='''Write accuracy metrics to file (default is stdout).''' ) parser.add_argument( '''--na-prob-file''' , '''-n''' , metavar='''na_prob.json''' , help='''Model estimates of probability of no answer.''' ) parser.add_argument( '''--na-prob-thresh''' , '''-t''' , type=__lowerCAmelCase , default=1.0 , help='''Predict "" if no-answer probability exceeds this (default = 1.0).''' , ) parser.add_argument( '''--out-image-dir''' , '''-p''' , metavar='''out_images''' , default=__lowerCAmelCase , help='''Save precision-recall curves to directory.''' ) parser.add_argument('''--verbose''' , '''-v''' , action='''store_true''' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = bool(qa['''answers''']['''text'''] ) return qid_to_has_ans def __magic_name__ ( __lowerCAmelCase : Dict ) -> Optional[Any]: def remove_articles(__lowerCAmelCase : Optional[int] ): return ARTICLES_REGEX.sub(''' ''' , __lowerCAmelCase ) def white_space_fix(__lowerCAmelCase : Optional[int] ): return " ".join(text.split() ) def remove_punc(__lowerCAmelCase : Union[str, Any] ): __lowerCamelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__lowerCAmelCase : Dict ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__lowerCAmelCase ) ) ) ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Optional[int]: if not s: return [] return normalize_answer(__lowerCAmelCase ).split() def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple ) -> int: return int(normalize_answer(__lowerCAmelCase ) == normalize_answer(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple ) -> str: __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = collections.Counter(__lowerCAmelCase ) & collections.Counter(__lowerCAmelCase ) __lowerCamelCase = sum(common.values() ) if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = (2 * precision * recall) / (precision + recall) return fa def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] ) -> Optional[Any]: __lowerCamelCase = {} __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = qa['''id'''] __lowerCamelCase = [t for t in qa['''answers''']['''text'''] if normalize_answer(__lowerCAmelCase )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __lowerCamelCase = [''''''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue __lowerCamelCase = preds[qid] # Take max over all gold answers __lowerCamelCase = max(compute_exact(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) __lowerCamelCase = max(compute_fa(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) return exact_scores, fa_scores def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ) -> List[str]: __lowerCamelCase = {} for qid, s in scores.items(): __lowerCamelCase = na_probs[qid] > na_prob_thresh if pred_na: __lowerCamelCase = float(not qid_to_has_ans[qid] ) else: __lowerCamelCase = s return new_scores def __magic_name__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=None ) -> Union[str, Any]: if not qid_list: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores.values() ) / total), ('''f1''', 100.0 * sum(fa_scores.values() ) / total), ('''total''', total), ] ) else: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('''f1''', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('''total''', total), ] ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ) -> int: for k in new_eval: __lowerCamelCase = new_eval[k] def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ) -> Optional[Any]: plt.step(__lowerCAmelCase , __lowerCAmelCase , color='''b''' , alpha=0.2 , where='''post''' ) plt.fill_between(__lowerCAmelCase , __lowerCAmelCase , step='''post''' , alpha=0.2 , color='''b''' ) plt.xlabel('''Recall''' ) plt.ylabel('''Precision''' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__lowerCAmelCase ) plt.savefig(__lowerCAmelCase ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Tuple=None ) -> int: __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) __lowerCamelCase = 0.0 __lowerCamelCase = 1.0 __lowerCamelCase = 0.0 __lowerCamelCase = [1.0] __lowerCamelCase = [0.0] __lowerCamelCase = 0.0 for i, qid in enumerate(__lowerCAmelCase ): if qid_to_has_ans[qid]: true_pos += scores[qid] __lowerCamelCase = true_pos / float(i + 1 ) __lowerCamelCase = true_pos / float(__lowerCAmelCase ) if i == len(__lowerCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__lowerCAmelCase ) recalls.append(__lowerCAmelCase ) if out_image: plot_pr_curve(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return {"ap": 100.0 * avg_prec} def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] ) -> List[Any]: if out_image_dir and not os.path.exists(__lowerCAmelCase ): os.makedirs(__lowerCAmelCase ) __lowerCamelCase = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_exact.png''' ) , title='''Precision-Recall curve for Exact Match score''' , ) __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_f1.png''' ) , title='''Precision-Recall curve for F1 score''' , ) __lowerCamelCase = {k: float(__lowerCAmelCase ) for k, v in qid_to_has_ans.items()} __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_oracle.png''' ) , title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)''' , ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_exact''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_f1''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_oracle''' ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> Optional[Any]: if not qid_list: return __lowerCamelCase = [na_probs[k] for k in qid_list] __lowerCamelCase = np.ones_like(__lowerCAmelCase ) / float(len(__lowerCAmelCase ) ) plt.hist(__lowerCAmelCase , weights=__lowerCAmelCase , bins=20 , range=(0.0, 1.0) ) plt.xlabel('''Model probability of no-answer''' ) plt.ylabel('''Proportion of dataset''' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__lowerCAmelCase , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ) -> Optional[int]: __lowerCamelCase = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __lowerCamelCase = num_no_ans __lowerCamelCase = cur_score __lowerCamelCase = 0.0 __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) for i, qid in enumerate(__lowerCAmelCase ): if qid not in scores: continue if qid_to_has_ans[qid]: __lowerCamelCase = scores[qid] else: if preds[qid]: __lowerCamelCase = -1 else: __lowerCamelCase = 0 cur_score += diff if cur_score > best_score: __lowerCamelCase = cur_score __lowerCamelCase = na_probs[qid] return 100.0 * best_score / len(__lowerCAmelCase ), best_thresh def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] ) -> int: __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = best_exact __lowerCamelCase = exact_thresh __lowerCamelCase = best_fa __lowerCamelCase = fa_thresh def __magic_name__ ( ) -> Optional[int]: with open(OPTS.data_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) __lowerCamelCase = dataset_json['''data'''] with open(OPTS.pred_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) else: __lowerCamelCase = {k: 0.0 for k in preds} __lowerCamelCase = make_qid_to_has_ans(__lowerCAmelCase ) # maps qid to True/False __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if v] __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if not v] __lowerCamelCase , __lowerCamelCase = get_raw_scores(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase ) if has_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''HasAns''' ) if no_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''NoAns''' ) if OPTS.na_prob_file: find_all_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''hasAns''' ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''noAns''' ) if OPTS.out_file: with open(OPTS.out_file , '''w''' ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) else: print(json.dumps(__lowerCAmelCase , indent=2 ) ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
270
0
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class _a ( unittest.TestCase ): def __init__( self : int , lowercase : Union[str, Any] , lowercase : Dict=7 , lowercase : Union[str, Any]=3 , lowercase : int=30 , lowercase : List[str]=400 , lowercase : List[Any]=True , lowercase : Union[str, Any]=None , lowercase : Union[str, Any]=True , lowercase : Any=[0.5, 0.5, 0.5] , lowercase : int=[0.5, 0.5, 0.5] , lowercase : List[Any]=True , lowercase : Tuple=1 / 255 , lowercase : List[str]=True , ): '''simple docstring''' UpperCAmelCase = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1_333} UpperCAmelCase = parent UpperCAmelCase = batch_size UpperCAmelCase = num_channels UpperCAmelCase = min_resolution UpperCAmelCase = max_resolution UpperCAmelCase = do_resize UpperCAmelCase = size UpperCAmelCase = do_normalize UpperCAmelCase = image_mean UpperCAmelCase = image_std UpperCAmelCase = do_rescale UpperCAmelCase = rescale_factor UpperCAmelCase = do_pad def A ( self : List[str] ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def A ( self : Union[str, Any] , lowercase : Dict , lowercase : Optional[Any]=False ): '''simple docstring''' if not batched: UpperCAmelCase = image_inputs[0] if isinstance(lowercase , Image.Image ): UpperCAmelCase , UpperCAmelCase = image.size else: UpperCAmelCase , UpperCAmelCase = image.shape[1], image.shape[2] if w < h: UpperCAmelCase = int(self.size['''shortest_edge'''] * h / w ) UpperCAmelCase = self.size['''shortest_edge'''] elif w > h: UpperCAmelCase = self.size['''shortest_edge'''] UpperCAmelCase = int(self.size['''shortest_edge'''] * w / h ) else: UpperCAmelCase = self.size['''shortest_edge'''] UpperCAmelCase = self.size['''shortest_edge'''] else: UpperCAmelCase = [] for image in image_inputs: UpperCAmelCase , UpperCAmelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCAmelCase = max(lowercase , key=lambda lowercase : item[0] )[0] UpperCAmelCase = max(lowercase , key=lambda lowercase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _a ( __a , unittest.TestCase ): __a : List[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def A ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase = ConditionalDetrImageProcessingTester(self ) @property def A ( self : int ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def A ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(lowercase , '''image_mean''' ) ) self.assertTrue(hasattr(lowercase , '''image_std''' ) ) self.assertTrue(hasattr(lowercase , '''do_normalize''' ) ) self.assertTrue(hasattr(lowercase , '''do_resize''' ) ) self.assertTrue(hasattr(lowercase , '''size''' ) ) def A ( self : Dict ): '''simple docstring''' UpperCAmelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 18, '''longest_edge''': 1_333} ) self.assertEqual(image_processor.do_pad , lowercase ) UpperCAmelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowercase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 42, '''longest_edge''': 84} ) self.assertEqual(image_processor.do_pad , lowercase ) def A ( self : Union[str, Any] ): '''simple docstring''' pass def A ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , Image.Image ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(lowercase , batched=lowercase ) UpperCAmelCase = image_processing(lowercase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase , numpify=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , np.ndarray ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase = image_processing(lowercase , return_tensors='''pt''' ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(lowercase , batched=lowercase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def A ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=lowercase , torchify=lowercase ) for image in image_inputs: self.assertIsInstance(lowercase , torch.Tensor ) # Test not batched input UpperCAmelCase = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(lowercase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase = image_processing(lowercase , return_tensors='''pt''' ).pixel_values UpperCAmelCase , UpperCAmelCase = self.image_processor_tester.get_expected_values(lowercase , batched=lowercase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def A ( self : Dict ): '''simple docstring''' UpperCAmelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: UpperCAmelCase = json.loads(f.read() ) UpperCAmelCase = {'''image_id''': 39_769, '''annotations''': target} # encode them UpperCAmelCase = ConditionalDetrImageProcessor.from_pretrained('''microsoft/conditional-detr-resnet-50''' ) UpperCAmelCase = image_processing(images=lowercase , annotations=lowercase , return_tensors='''pt''' ) # verify pixel values UpperCAmelCase = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['''pixel_values'''].shape , lowercase ) UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , lowercase , atol=1E-4 ) ) # verify area UpperCAmelCase = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , lowercase ) ) # verify boxes UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , lowercase ) UpperCAmelCase = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , lowercase , atol=1E-3 ) ) # verify image_id UpperCAmelCase = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , lowercase ) ) # verify is_crowd UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , lowercase ) ) # verify class_labels UpperCAmelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , lowercase ) ) # verify orig_size UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , lowercase ) ) # verify size UpperCAmelCase = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , lowercase ) ) @slow def A ( self : str ): '''simple docstring''' UpperCAmelCase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: UpperCAmelCase = json.loads(f.read() ) UpperCAmelCase = {'''file_name''': '''000000039769.png''', '''image_id''': 39_769, '''segments_info''': target} UpperCAmelCase = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them UpperCAmelCase = ConditionalDetrImageProcessor(format='''coco_panoptic''' ) UpperCAmelCase = image_processing(images=lowercase , annotations=lowercase , masks_path=lowercase , return_tensors='''pt''' ) # verify pixel values UpperCAmelCase = torch.Size([1, 3, 800, 1_066] ) self.assertEqual(encoding['''pixel_values'''].shape , lowercase ) UpperCAmelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , lowercase , atol=1E-4 ) ) # verify area UpperCAmelCase = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , lowercase ) ) # verify boxes UpperCAmelCase = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , lowercase ) UpperCAmelCase = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , lowercase , atol=1E-3 ) ) # verify image_id UpperCAmelCase = torch.tensor([39_769] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , lowercase ) ) # verify is_crowd UpperCAmelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , lowercase ) ) # verify class_labels UpperCAmelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , lowercase ) ) # verify masks UpperCAmelCase = 822_873 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , lowercase ) # verify orig_size UpperCAmelCase = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , lowercase ) ) # verify size UpperCAmelCase = torch.tensor([800, 1_066] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , lowercase ) )
34
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F'{bindir}/../../examples/pytorch/translation'): from run_translation import main # noqa set_seed(42) SCREAMING_SNAKE_CASE__ : Any = "sshleifer/student_marian_en_ro_6_1" SCREAMING_SNAKE_CASE__ : Tuple = "sshleifer/tiny-mbart" @require_torch class lowerCAmelCase__ ( __lowercase ): def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , ) -> Optional[int]: __lowerCamelCase = self.run_trainer( eval_steps=1 , max_len=12 , model_name=SCREAMING_SNAKE_CASE__ , num_train_epochs=1 , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , predict_with_generate=SCREAMING_SNAKE_CASE__ , do_train=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history if not do_eval: return __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats __lowerCamelCase = eval_metrics[-1] assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) assert not math.isnan(float(last_step_stats['''eval_loss'''] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def __A ( self : Optional[int] ) -> int: self.run_seqaseq_quick() @require_torch_multi_gpu def __A ( self : int ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @require_torch_multi_gpu def __A ( self : Optional[Any] ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Optional[int] ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple --fp16''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Tuple ) -> Any: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick( distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2 --fp16''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @require_apex @require_torch_gpu def __A ( self : Union[str, Any] ) -> List[str]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) @parameterized.expand(['''base''', '''low''', '''high''', '''mixed'''] ) @require_torch_multi_gpu def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout __lowerCamelCase = { # test with the default log_level - should be info and thus log info once '''base''': {'''extra_args_str''': '''''', '''n_matches''': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes '''low''': {'''extra_args_str''': '''--log_level debug --log_level_replica debug''', '''n_matches''': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica '''high''': {'''extra_args_str''': '''--log_level error --log_level_replica debug''', '''n_matches''': 1}, # test with high log_level and log_level_replica - should be quiet on all processes '''mixed''': {'''extra_args_str''': '''--log_level error --log_level_replica error''', '''n_matches''': 0}, } __lowerCamelCase = experiments[experiment_id] __lowerCamelCase = {'''distributed''': True, '''predict_with_generate''': False, '''do_eval''': False, '''do_predict''': False} __lowerCamelCase = '''Running training''' with CaptureStderr() as cl: self.run_seqaseq_quick(**SCREAMING_SNAKE_CASE__ , extra_args_str=data['''extra_args_str'''] ) __lowerCamelCase = len(re.findall(SCREAMING_SNAKE_CASE__ , cl.err ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ , data['''n_matches'''] ) @slow def __A ( self : Any ) -> Optional[Any]: __lowerCamelCase = self.run_trainer( eval_steps=2 , max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=10 , distributed=SCREAMING_SNAKE_CASE__ , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] __lowerCamelCase = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) # test if do_predict saves generations and metrics __lowerCamelCase = os.listdir(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {os.path.basename(SCREAMING_SNAKE_CASE__ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def __A ( self : Optional[int] ) -> str: from transformers.training_args import OptimizerNames def train_and_return_metrics(SCREAMING_SNAKE_CASE__ : str ) -> Tuple[int, float]: __lowerCamelCase = '''--skip_memory_metrics 0''' __lowerCamelCase = self.run_trainer( max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=1 , optim=SCREAMING_SNAKE_CASE__ , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , n_gpus_to_use=1 , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(Path(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = int(logs[0]['''train_mem_gpu_peaked_delta'''] / 2**20 ) __lowerCamelCase = int(logs[0]['''train_mem_gpu_alloc_delta'''] / 2**20 ) __lowerCamelCase = logs[0]['''train_loss'''] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) __lowerCamelCase = gpu_alloc_mem_orig - gpu_alloc_mem_bnb __lowerCamelCase = gpu_peak_mem_orig + gpu_alloc_mem_orig __lowerCamelCase = gpu_peak_mem_bnb + gpu_alloc_mem_bnb __lowerCamelCase = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings __lowerCamelCase = 1_20 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and''' f''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , ) self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less total gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and''' f''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , ) self.assertEqual( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , f'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = 3e-3 , SCREAMING_SNAKE_CASE__ : str = "adafactor" , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : int = None , ) -> List[Any]: __lowerCamelCase = self.test_file_dir / '''../fixtures/tests_samples/wmt_en_ro''' __lowerCamelCase = self.get_auto_remove_tmp_dir() __lowerCamelCase = f''' --model_name_or_path {model_name} --train_file {data_dir}/train.json --validation_file {data_dir}/val.json --test_file {data_dir}/test.json --output_dir {output_dir} --overwrite_output_dir --max_train_samples 8 --max_source_length {max_len} --max_target_length {max_len} --do_train --num_train_epochs {str(SCREAMING_SNAKE_CASE__ )} --per_device_train_batch_size 4 --learning_rate {learning_rate} --warmup_steps 8 --logging_steps 0 --logging_strategy no --save_steps {str(SCREAMING_SNAKE_CASE__ )} --group_by_length --label_smoothing_factor 0.1 --target_lang ro_RO --source_lang en_XX '''.split() __lowerCamelCase = f''' --do_eval --per_device_eval_batch_size 4 --max_eval_samples 8 --val_max_target_length {max_len} --evaluation_strategy steps --eval_steps {str(SCREAMING_SNAKE_CASE__ )} '''.split() __lowerCamelCase = ''' --do_predict '''.split() __lowerCamelCase = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f'''--optim {optim}'''.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: __lowerCamelCase = get_gpu_count() __lowerCamelCase = get_torch_dist_unique_port() __lowerCamelCase = f''' -m torch.distributed.run --nproc_per_node={n_gpus_to_use} --master_port={master_port} {self.examples_dir_str}/pytorch/translation/run_translation.py '''.split() __lowerCamelCase = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) else: __lowerCamelCase = ['''run_translation.py'''] + args with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): main() return output_dir
270
0
'''simple docstring''' from .dependency_versions_table import deps from .utils.versions import require_version, require_version_core # define which module versions we always want to check at run time # (usually the ones defined in `install_requires` in setup.py) # # order specific notes: # - tqdm must be checked before tokenizers __a = [ "python", "tqdm", "regex", "requests", "packaging", "filelock", "numpy", "tokenizers", "huggingface-hub", "safetensors", "accelerate", "pyyaml", ] for pkg in pkgs_to_check_at_runtime: if pkg in deps: if pkg == "tokenizers": # must be loaded here, or else tqdm check may fail from .utils import is_tokenizers_available if not is_tokenizers_available(): continue # not required, check version only if installed elif pkg == "accelerate": # must be loaded here, or else tqdm check may fail from .utils import is_accelerate_available # Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of # Transformers with PyTorch if not is_accelerate_available(): continue # not required, check version only if installed require_version_core(deps[pkg]) else: raise ValueError(F"can't find {pkg} in {deps.keys()}, check dependency_versions_table.py") def __snake_case( _lowerCAmelCase , _lowerCAmelCase=None ) -> int: require_version(deps[pkg] , _lowerCAmelCase )
35
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__ : Dict = { "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__ : int = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowercase ): a__ : Any = """mask2former""" a__ : Dict = ["""swin"""] a__ : Any = {"""hidden_size""": """hidden_dim"""} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 20_48 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_55 , SCREAMING_SNAKE_CASE__ : int = 1_00 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_25_44 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 16, 32] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> str: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.''' ) __lowerCamelCase = CONFIG_MAPPING['''swin''']( image_size=2_24 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = backbone_config.pop('''model_type''' ) __lowerCamelCase = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # 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 )}''' ) __lowerCamelCase = backbone_config __lowerCamelCase = feature_size __lowerCamelCase = mask_feature_size __lowerCamelCase = hidden_dim __lowerCamelCase = encoder_feedforward_dim __lowerCamelCase = activation_function __lowerCamelCase = encoder_layers __lowerCamelCase = decoder_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = dropout __lowerCamelCase = dim_feedforward __lowerCamelCase = pre_norm __lowerCamelCase = enforce_input_projection __lowerCamelCase = common_stride __lowerCamelCase = ignore_value __lowerCamelCase = num_queries __lowerCamelCase = no_object_weight __lowerCamelCase = class_weight __lowerCamelCase = mask_weight __lowerCamelCase = dice_weight __lowerCamelCase = train_num_points __lowerCamelCase = oversample_ratio __lowerCamelCase = importance_sample_ratio __lowerCamelCase = init_std __lowerCamelCase = init_xavier_std __lowerCamelCase = use_auxiliary_loss __lowerCamelCase = feature_strides __lowerCamelCase = output_auxiliary_logits __lowerCamelCase = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def __A ( cls : Any , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Any ) -> Dict[str, any]: __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.backbone_config.to_dict() __lowerCamelCase = self.__class__.model_type return output
270
0
_snake_case = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Optional[int] = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1_000} _lowerCAmelCase : Union[str, Any] = 0 _lowerCAmelCase : Optional[int] = 0 while place < len(_lowerCamelCase ): if (place + 1 < len(_lowerCamelCase )) and (vals[roman[place]] < vals[roman[place + 1]]): total += vals[roman[place + 1]] - vals[roman[place]] place += 2 else: total += vals[roman[place]] place += 1 return total def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : str = [] for arabic, roman in ROMAN: ((_lowerCAmelCase) , (_lowerCAmelCase)) : List[str] = divmod(_lowerCamelCase , _lowerCamelCase ) result.append(roman * factor ) if number == 0: break return "".join(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod()
36
import os def __magic_name__ ( ) -> str: __lowerCamelCase = os.path.join(os.path.dirname(__lowerCAmelCase ) , '''num.txt''' ) with open(__lowerCAmelCase ) as file_hand: return str(sum(int(__lowerCAmelCase ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
270
0
'''simple docstring''' import os import re from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging _lowerCAmelCase = logging.get_logger(__name__) _lowerCAmelCase = { '''vocab_file''': '''vocab.txt''', '''merges_file''': '''bpe.codes''', } _lowerCAmelCase = { '''vocab_file''': { '''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt''', '''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt''', }, '''merges_file''': { '''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes''', '''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes''', }, } _lowerCAmelCase = { '''vinai/phobert-base''': 256, '''vinai/phobert-large''': 256, } def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : str = set() lowerCAmelCase__ : Optional[Any] = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCAmelCase__ : Dict = char lowerCAmelCase__ : Any = set(UpperCamelCase ) return pairs class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' __lowercase : Union[str, Any] = VOCAB_FILES_NAMES __lowercase : int = PRETRAINED_VOCAB_FILES_MAP __lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase="<s>" ,__UpperCAmelCase="</s>" ,__UpperCAmelCase="</s>" ,__UpperCAmelCase="<s>" ,__UpperCAmelCase="<unk>" ,__UpperCAmelCase="<pad>" ,__UpperCAmelCase="<mask>" ,**__UpperCAmelCase ,) -> List[str]: super().__init__( bos_token=__UpperCAmelCase ,eos_token=__UpperCAmelCase ,unk_token=__UpperCAmelCase ,sep_token=__UpperCAmelCase ,cls_token=__UpperCAmelCase ,pad_token=__UpperCAmelCase ,mask_token=__UpperCAmelCase ,**__UpperCAmelCase ,) lowerCAmelCase__ : List[Any] = vocab_file lowerCAmelCase__ : Dict = merges_file lowerCAmelCase__ : int = {} lowerCAmelCase__ : str = 0 lowerCAmelCase__ : Optional[Any] = 1 lowerCAmelCase__ : Union[str, Any] = 2 lowerCAmelCase__ : Optional[int] = 3 self.add_from_file(__UpperCAmelCase ) lowerCAmelCase__ : Optional[int] = {v: k for k, v in self.encoder.items()} with open(__UpperCAmelCase ,encoding="""utf-8""" ) as merges_handle: lowerCAmelCase__ : int = merges_handle.read().split("""\n""" )[:-1] lowerCAmelCase__ : Optional[int] = [tuple(merge.split()[:-1] ) for merge in merges] lowerCAmelCase__ : Dict = dict(zip(__UpperCAmelCase ,range(len(__UpperCAmelCase ) ) ) ) lowerCAmelCase__ : Dict = {} def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase = None ) -> List[int]: if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase__ : Optional[int] = [self.cls_token_id] lowerCAmelCase__ : Tuple = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase = None ,__UpperCAmelCase = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCAmelCase ,token_ids_a=__UpperCAmelCase ,already_has_special_tokens=__UpperCAmelCase ) if token_ids_a is None: return [1] + ([0] * len(__UpperCAmelCase )) + [1] return [1] + ([0] * len(__UpperCAmelCase )) + [1, 1] + ([0] * len(__UpperCAmelCase )) + [1] def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase = None ) -> List[int]: lowerCAmelCase__ : Optional[Any] = [self.sep_token_id] lowerCAmelCase__ : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCAmelCase_ ( self ) -> Tuple: return len(self.encoder ) def UpperCAmelCase_ ( self ) -> Optional[Any]: return dict(self.encoder ,**self.added_tokens_encoder ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> List[str]: if token in self.cache: return self.cache[token] lowerCAmelCase__ : List[Any] = tuple(__UpperCAmelCase ) lowerCAmelCase__ : List[str] = tuple(list(word[:-1] ) + [word[-1] + """</w>"""] ) lowerCAmelCase__ : Optional[int] = get_pairs(__UpperCAmelCase ) if not pairs: return token while True: lowerCAmelCase__ : Tuple = min(__UpperCAmelCase ,key=lambda __UpperCAmelCase : self.bpe_ranks.get(__UpperCAmelCase ,float("""inf""" ) ) ) if bigram not in self.bpe_ranks: break lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = bigram lowerCAmelCase__ : List[str] = [] lowerCAmelCase__ : List[str] = 0 while i < len(__UpperCAmelCase ): try: lowerCAmelCase__ : Any = word.index(__UpperCAmelCase ,__UpperCAmelCase ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCAmelCase__ : Dict = j if word[i] == first and i < len(__UpperCAmelCase ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCAmelCase__ : str = tuple(__UpperCAmelCase ) lowerCAmelCase__ : int = new_word if len(__UpperCAmelCase ) == 1: break else: lowerCAmelCase__ : Any = get_pairs(__UpperCAmelCase ) lowerCAmelCase__ : List[str] = """@@ """.join(__UpperCAmelCase ) lowerCAmelCase__ : Union[str, Any] = word[:-4] lowerCAmelCase__ : Optional[Any] = word return word def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> Optional[int]: lowerCAmelCase__ : Dict = [] lowerCAmelCase__ : str = re.findall(R"""\S+\n?""" ,__UpperCAmelCase ) for token in words: split_tokens.extend(list(self.bpe(__UpperCAmelCase ).split(""" """ ) ) ) return split_tokens def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> Union[str, Any]: return self.encoder.get(__UpperCAmelCase ,self.encoder.get(self.unk_token ) ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> Tuple: return self.decoder.get(__UpperCAmelCase ,self.unk_token ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> List[str]: lowerCAmelCase__ : List[str] = """ """.join(__UpperCAmelCase ).replace("""@@ """ ,"""""" ).strip() return out_string def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase = None ) -> Tuple[str]: if not os.path.isdir(__UpperCAmelCase ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return lowerCAmelCase__ : List[str] = os.path.join( __UpperCAmelCase ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) lowerCAmelCase__ : List[str] = os.path.join( __UpperCAmelCase ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ): copyfile(self.vocab_file ,__UpperCAmelCase ) if os.path.abspath(self.merges_file ) != os.path.abspath(__UpperCAmelCase ): copyfile(self.merges_file ,__UpperCAmelCase ) return out_vocab_file, out_merge_file def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> Tuple: if isinstance(__UpperCAmelCase ,__UpperCAmelCase ): try: with open(__UpperCAmelCase ,"""r""" ,encoding="""utf-8""" ) as fd: self.add_from_file(__UpperCAmelCase ) except FileNotFoundError as fnfe: raise fnfe except UnicodeError: raise Exception(F"""Incorrect encoding detected in {f}, please rebuild the dataset""" ) return lowerCAmelCase__ : Tuple = f.readlines() for lineTmp in lines: lowerCAmelCase__ : Optional[int] = lineTmp.strip() lowerCAmelCase__ : List[str] = line.rfind(""" """ ) if idx == -1: raise ValueError("""Incorrect dictionary format, expected '<token> <cnt>'""" ) lowerCAmelCase__ : Optional[Any] = line[:idx] lowerCAmelCase__ : int = len(self.encoder )
37
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str a__ : List[str] a__ : Optional[List[str]] @dataclass class lowerCAmelCase__ : a__ : List[int] a__ : List[int] a__ : Optional[List[int]] = None a__ : Optional[List[int]] = None class lowerCAmelCase__ ( __lowercase ): a__ : Optional[Any] = """train""" a__ : Optional[int] = """dev""" a__ : Dict = """test""" class lowerCAmelCase__ : @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[Split, str] ) -> List[InputExample]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : str ) -> List[str]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : List[InputExample] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]="[CLS]" , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str="[SEP]" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : str=-1_00 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[Any]=True , ) -> List[InputFeatures]: __lowerCamelCase = {label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} __lowerCamelCase = [] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE__ ): if ex_index % 1_00_00 == 0: logger.info('''Writing example %d of %d''' , SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [] __lowerCamelCase = [] for word, label in zip(example.words , example.labels ): __lowerCamelCase = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE__ ) > 0: tokens.extend(SCREAMING_SNAKE_CASE__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __lowerCamelCase = tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE__ ) > max_seq_length - special_tokens_count: __lowerCamelCase = tokens[: (max_seq_length - special_tokens_count)] __lowerCamelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __lowerCamelCase = [sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __lowerCamelCase = [cls_token] + tokens __lowerCamelCase = [pad_token_label_id] + label_ids __lowerCamelCase = [cls_token_segment_id] + segment_ids __lowerCamelCase = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __lowerCamelCase = [1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE__ ) # Zero-pad up to the sequence length. __lowerCamelCase = max_seq_length - len(SCREAMING_SNAKE_CASE__ ) if pad_on_left: __lowerCamelCase = ([pad_token] * padding_length) + input_ids __lowerCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __lowerCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids __lowerCamelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , label_ids=SCREAMING_SNAKE_CASE__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowerCAmelCase__ ( __lowercase ): a__ : List[InputFeatures] a__ : int = nn.CrossEntropyLoss().ignore_index def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> Union[str, Any]: # Load data features from cache or dataset file __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __lowerCamelCase = cached_features_file + '''.lock''' with FileLock(SCREAMING_SNAKE_CASE__ ): if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) __lowerCamelCase = torch.load(SCREAMING_SNAKE_CASE__ ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , SCREAMING_SNAKE_CASE__ ) def __len__( self : Dict ) -> str: return len(self.features ) def __getitem__( self : Any , SCREAMING_SNAKE_CASE__ : Dict ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowerCAmelCase__ : a__ : List[InputFeatures] a__ : int = -100 def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> List[Any]: __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : List[Any] ) -> Any: return len(self.features ) def __getitem__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> InputFeatures: return self.features[i]
270
0
from math import isqrt def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int ) -> bool: """simple docstring""" return all(number % divisor != 0 for divisor in range(2 , isqrt(__magic_name__ ) + 1 ) ) def SCREAMING_SNAKE_CASE_ ( __magic_name__ : int = 10**6 ) -> int: """simple docstring""" UpperCamelCase :Optional[int] = 0 UpperCamelCase :str = 1 UpperCamelCase :Optional[int] = 7 while prime_candidate < max_prime: primes_count += is_prime(__magic_name__ ) cube_index += 1 prime_candidate += 6 * cube_index return primes_count if __name__ == "__main__": print(F'''{solution() = }''')
38
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase__ ( __lowercase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : NestedDataStructureLike[PathLike] , SCREAMING_SNAKE_CASE__ : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE__ : Optional[Features] = None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : str , ) -> Union[str, Any]: super().__init__( SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ , streaming=SCREAMING_SNAKE_CASE__ , num_proc=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = path_or_paths if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else {self.split: path_or_paths} __lowerCamelCase = Text( cache_dir=SCREAMING_SNAKE_CASE__ , data_files=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : int ) -> Dict: # Build iterable dataset if self.streaming: __lowerCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE__ , download_mode=SCREAMING_SNAKE_CASE__ , verification_mode=SCREAMING_SNAKE_CASE__ , base_path=SCREAMING_SNAKE_CASE__ , num_proc=self.num_proc , ) __lowerCamelCase = self.builder.as_dataset( split=self.split , verification_mode=SCREAMING_SNAKE_CASE__ , in_memory=self.keep_in_memory ) return dataset
270
0
import random from typing import Any def __A ( __lowerCAmelCase )-> list[Any]: """simple docstring""" for _ in range(len(__lowerCAmelCase ) ): _UpperCAmelCase = random.randint(0 , len(__lowerCAmelCase ) - 1 ) _UpperCAmelCase = random.randint(0 , len(__lowerCAmelCase ) - 1 ) _UpperCAmelCase , _UpperCAmelCase = data[b], data[a] return data if __name__ == "__main__": _a = [0, 1, 2, 3, 4, 5, 6, 7] _a = ['''python''', '''says''', '''hello''', '''!'''] print('''Fisher-Yates Shuffle:''') print('''List''', integers, strings) print('''FY Shuffle''', fisher_yates_shuffle(integers), fisher_yates_shuffle(strings))
39
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
270
0
"""simple docstring""" import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XGLMTokenizer, XGLMTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin __lowercase = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _A ( _a ,unittest.TestCase ): """simple docstring""" UpperCAmelCase : str = XGLMTokenizer UpperCAmelCase : Dict = XGLMTokenizerFast UpperCAmelCase : Optional[Any] = True UpperCAmelCase : Any = True def __snake_case ( self : int): super().setUp() # We have a SentencePiece fixture for testing a : Optional[int] = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase) tokenizer.save_pretrained(self.tmpdirname) def __snake_case ( self : str): a : str = "<pad>" a : str = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__UpperCAmelCase) , __UpperCAmelCase) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__UpperCAmelCase) , __UpperCAmelCase) def __snake_case ( self : List[str]): a : int = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , "<s>") self.assertEqual(vocab_keys[1] , "<pad>") self.assertEqual(len(__UpperCAmelCase) , 1008) def __snake_case ( self : int): self.assertEqual(self.get_tokenizer().vocab_size , 1008) def __snake_case ( self : Union[str, Any]): a : Optional[int] = XGLMTokenizer(__UpperCAmelCase , keep_accents=__UpperCAmelCase) a : Optional[int] = tokenizer.tokenize("This is a test") self.assertListEqual(__UpperCAmelCase , ["▁This", "▁is", "▁a", "▁t", "est"]) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCAmelCase) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) a : str = tokenizer.tokenize("I was born in 92000, and this is falsé.") self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) a : int = tokenizer.convert_tokens_to_ids(__UpperCAmelCase) self.assertListEqual( __UpperCAmelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) a : int = tokenizer.convert_ids_to_tokens(__UpperCAmelCase) self.assertListEqual( __UpperCAmelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def __snake_case ( self : str): return XGLMTokenizer.from_pretrained("facebook/xglm-564M") def __snake_case ( self : Optional[Any]): with tempfile.NamedTemporaryFile() as f: shutil.copyfile(__UpperCAmelCase , f.name) a : List[str] = XGLMTokenizer(f.name , keep_accents=__UpperCAmelCase) a : str = pickle.dumps(__UpperCAmelCase) pickle.loads(__UpperCAmelCase) def __snake_case ( self : List[str]): if not self.test_rust_tokenizer: return a : Dict = self.get_tokenizer() a : Any = self.get_rust_tokenizer() a : Optional[Any] = "I was born in 92000, and this is falsé." a : Any = tokenizer.tokenize(__UpperCAmelCase) a : Optional[Any] = rust_tokenizer.tokenize(__UpperCAmelCase) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase) a : Optional[int] = tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase) a : Optional[Any] = rust_tokenizer.encode(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase) a : str = self.get_rust_tokenizer() a : int = tokenizer.encode(__UpperCAmelCase) a : str = rust_tokenizer.encode(__UpperCAmelCase) self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase) @slow def __snake_case ( self : Optional[int]): a : Tuple = "Hello World!" a : Union[str, Any] = [2, 31227, 4447, 35] self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase)) @slow def __snake_case ( self : Any): a : Optional[Any] = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to unk, such as saoneuhaoesuth" ) # fmt: off a : str = [2, 1018, 67, 11, 1988, 2617, 5631, 278, 11, 3407, 48, 71630, 28085, 4, 3234, 157, 13, 6, 5, 6, 4, 3526, 768, 15, 659, 57, 298, 3983, 864, 129, 21, 6, 5, 13675, 377, 652, 7580, 10341, 155, 2817, 422, 1666, 7, 1674, 53, 113, 202277, 17892, 33, 60, 87, 4, 3234, 157, 61, 2667, 52376, 19, 88, 23, 735] # fmt: on self.assertListEqual(__UpperCAmelCase , self.big_tokenizer.encode(__UpperCAmelCase)) @slow def __snake_case ( self : Optional[Any]): # fmt: off a : List[Any] = { "input_ids": [[2, 108825, 1163, 15, 88010, 473, 15898, 157, 13672, 1857, 312, 8, 238021, 1163, 53, 13672, 1857, 312, 8, 53283, 182396, 8, 18566, 16, 36733, 4101, 8, 230, 244017, 122553, 7, 15, 132597, 4, 293, 12511, 7610, 4, 3414, 132597, 9, 4, 32361, 362, 4, 734, 28512, 32569, 18, 4, 32361, 26096, 14982, 73, 18715, 21433, 235261, 15, 492, 12427, 16, 53, 18715, 21433, 65454, 15, 23659, 563, 16, 278, 597, 2843, 595, 7931, 182396, 64186, 22, 886, 595, 132981, 53, 25540, 3449, 43982, 39901, 5951, 878, 330, 4, 27694, 80269, 312, 53, 6517, 11780, 611, 20408, 5], [2, 6, 132597, 67, 42897, 33, 592, 8, 163729, 25540, 361, 136997, 109514, 173230, 7, 501, 60, 102913, 196, 5631, 235, 63243, 473, 6, 231757, 74, 5277, 7905, 53, 3095, 37317, 22, 454, 183874, 5], [2, 268, 31298, 46530, 6, 132935, 43831, 7, 597, 32, 24, 3688, 9865, 5]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] } # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__UpperCAmelCase , model_name="facebook/xglm-564M" , padding=__UpperCAmelCase , )
40
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ : int = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : Dict ) -> Tuple: if version.parse(scb.__version__ ) < version.parse('''1.4.12''' ): raise ImportWarning( '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n''' '''You can install it with `pip install "sacrebleu>=1.4.12"`.''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf'''] , reference_urls=[ '''https://github.com/m-popovic/chrF''', ] , ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int = CHRF.CHAR_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.WORD_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.BETA , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Optional[Any]: __lowerCamelCase = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) __lowerCamelCase = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase = CHRF(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sb_chrf.corpus_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
270
0
'''simple docstring''' import argparse import requests import torch from PIL import Image from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> Tuple: lowerCamelCase__ : Tuple = SwinConfig(image_size=192 ) if "base" in model_name: lowerCamelCase__ : Union[str, Any] = 6 lowerCamelCase__ : Dict = 128 lowerCamelCase__ : Any = (2, 2, 18, 2) lowerCamelCase__ : Tuple = (4, 8, 16, 32) elif "large" in model_name: lowerCamelCase__ : Any = 12 lowerCamelCase__ : Tuple = 192 lowerCamelCase__ : List[str] = (2, 2, 18, 2) lowerCamelCase__ : Union[str, Any] = (6, 12, 24, 48) else: raise ValueError("""Model not supported, only supports base and large variants""" ) lowerCamelCase__ : str = window_size lowerCamelCase__ : Dict = embed_dim lowerCamelCase__ : Tuple = depths lowerCamelCase__ : str = num_heads return config def SCREAMING_SNAKE_CASE_ (UpperCamelCase ) -> int: if "encoder.mask_token" in name: lowerCamelCase__ : Any = name.replace("""encoder.mask_token""" , """embeddings.mask_token""" ) if "encoder.patch_embed.proj" in name: lowerCamelCase__ : List[Any] = name.replace("""encoder.patch_embed.proj""" , """embeddings.patch_embeddings.projection""" ) if "encoder.patch_embed.norm" in name: lowerCamelCase__ : str = name.replace("""encoder.patch_embed.norm""" , """embeddings.norm""" ) if "attn.proj" in name: lowerCamelCase__ : List[Any] = name.replace("""attn.proj""" , """attention.output.dense""" ) if "attn" in name: lowerCamelCase__ : List[Any] = name.replace("""attn""" , """attention.self""" ) if "norm1" in name: lowerCamelCase__ : Tuple = name.replace("""norm1""" , """layernorm_before""" ) if "norm2" in name: lowerCamelCase__ : int = name.replace("""norm2""" , """layernorm_after""" ) if "mlp.fc1" in name: lowerCamelCase__ : Optional[Any] = name.replace("""mlp.fc1""" , """intermediate.dense""" ) if "mlp.fc2" in name: lowerCamelCase__ : Optional[Any] = name.replace("""mlp.fc2""" , """output.dense""" ) if name == "encoder.norm.weight": lowerCamelCase__ : Optional[int] = """layernorm.weight""" if name == "encoder.norm.bias": lowerCamelCase__ : str = """layernorm.bias""" if "decoder" in name: pass else: lowerCamelCase__ : Tuple = """swin.""" + name return name def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase ) -> Optional[int]: for key in orig_state_dict.copy().keys(): lowerCamelCase__ : Tuple = orig_state_dict.pop(UpperCamelCase ) if "attn_mask" in key: pass elif "qkv" in key: lowerCamelCase__ : Union[str, Any] = key.split(""".""" ) lowerCamelCase__ : Optional[Any] = int(key_split[2] ) lowerCamelCase__ : Any = int(key_split[4] ) lowerCamelCase__ : List[str] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: lowerCamelCase__ : Union[str, Any] = val[:dim, :] lowerCamelCase__ : Tuple = val[ dim : dim * 2, : ] lowerCamelCase__ : Union[str, Any] = val[-dim:, :] else: lowerCamelCase__ : Union[str, Any] = val[ :dim ] lowerCamelCase__ : int = val[ dim : dim * 2 ] lowerCamelCase__ : List[str] = val[ -dim: ] else: lowerCamelCase__ : Union[str, Any] = val return orig_state_dict def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Optional[Any]: lowerCamelCase__ : Optional[int] = torch.load(UpperCamelCase , map_location="""cpu""" )["""model"""] lowerCamelCase__ : List[str] = get_swin_config(UpperCamelCase ) lowerCamelCase__ : str = SwinForMaskedImageModeling(UpperCamelCase ) model.eval() lowerCamelCase__ : List[Any] = convert_state_dict(UpperCamelCase , UpperCamelCase ) model.load_state_dict(UpperCamelCase ) lowerCamelCase__ : int = """http://images.cocodataset.org/val2017/000000039769.jpg""" lowerCamelCase__ : Dict = ViTImageProcessor(size={"""height""": 192, """width""": 192} ) lowerCamelCase__ : Dict = Image.open(requests.get(UpperCamelCase , stream=UpperCamelCase ).raw ) lowerCamelCase__ : Union[str, Any] = image_processor(images=UpperCamelCase , return_tensors="""pt""" ) with torch.no_grad(): lowerCamelCase__ : List[Any] = model(**UpperCamelCase ).logits print(outputs.keys() ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(UpperCamelCase ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(UpperCamelCase ) if push_to_hub: print(f'''Pushing model and image processor for {model_name} to hub''' ) model.push_to_hub(f'''microsoft/{model_name}''' ) image_processor.push_to_hub(f'''microsoft/{model_name}''' ) if __name__ == "__main__": _A : Union[str, Any] =argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default='''swin-base-simmim-window6-192''', type=str, choices=['''swin-base-simmim-window6-192''', '''swin-large-simmim-window12-192'''], help='''Name of the Swin SimMIM model you\'d like to convert.''', ) parser.add_argument( '''--checkpoint_path''', default='''/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth''', type=str, help='''Path to the original PyTorch checkpoint (.pth file).''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) parser.add_argument( '''--push_to_hub''', action='''store_true''', help='''Whether or not to push the converted model to the 🤗 hub.''' ) _A : int =parser.parse_args() convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
41
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
270
0
'''simple docstring''' import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device lowercase : Optional[Any] = False class __UpperCAmelCase ( unittest.TestCase ): pass @nightly @require_torch_gpu class __UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase ( self ): """simple docstring""" _snake_case = VersatileDiffusionTextToImagePipeline.from_pretrained('shi-labs/versatile-diffusion' ) # remove text_unet pipe.remove_unused_weights() pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = 'A painting of a squirrel eating a burger ' _snake_case = torch.manual_seed(0 ) _snake_case = pipe( prompt=lowerCAmelCase_ , generator=lowerCAmelCase_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowerCAmelCase_ ) _snake_case = VersatileDiffusionTextToImagePipeline.from_pretrained(lowerCAmelCase_ ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = generator.manual_seed(0 ) _snake_case = pipe( prompt=lowerCAmelCase_ , generator=lowerCAmelCase_ , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def lowerCamelCase ( self ): """simple docstring""" _snake_case = VersatileDiffusionTextToImagePipeline.from_pretrained( 'shi-labs/versatile-diffusion' , torch_dtype=torch.floataa ) pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) _snake_case = 'A painting of a squirrel eating a burger ' _snake_case = torch.manual_seed(0 ) _snake_case = pipe( prompt=lowerCAmelCase_ , generator=lowerCAmelCase_ , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' ).images _snake_case = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) _snake_case = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
42
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : str = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Tuple=18 , SCREAMING_SNAKE_CASE__ : int=30 , SCREAMING_SNAKE_CASE__ : Any=4_00 , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , ) -> Union[str, Any]: __lowerCamelCase = size if size is not None else {'''height''': 20, '''width''': 20} __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = num_channels __lowerCamelCase = image_size __lowerCamelCase = min_resolution __lowerCamelCase = max_resolution __lowerCamelCase = size __lowerCamelCase = do_normalize __lowerCamelCase = do_convert_rgb __lowerCamelCase = [5_12, 10_24, 20_48, 40_96] __lowerCamelCase = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def __A ( self : Union[str, Any] ) -> Union[str, Any]: return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __A ( self : int ) -> Any: __lowerCamelCase = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' __lowerCamelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Dict = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Optional[Any] ) -> List[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self ) @property def __A ( self : Optional[int] ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> Dict: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : int ) -> str: __lowerCamelCase = self.image_processor_tester.prepare_dummy_image() __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) __lowerCamelCase = 20_48 __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __A ( self : Union[str, Any] ) -> Dict: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Dict ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 __lowerCamelCase = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches __lowerCamelCase = '''Hello''' __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : List[str] ) -> Any: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Tuple ) -> List[str]: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Any = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self , num_channels=4 ) __lowerCamelCase = 3 @property def __A ( self : List[Any] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : Optional[int] ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
270
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __lowercase = {'''configuration_xglm''': ['''XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XGLMConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = ['''XGLMTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = ['''XGLMTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ '''XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XGLMForCausalLM''', '''XGLMModel''', '''XGLMPreTrainedModel''', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ '''FlaxXGLMForCausalLM''', '''FlaxXGLMModel''', '''FlaxXGLMPreTrainedModel''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ '''TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFXGLMForCausalLM''', '''TFXGLMModel''', '''TFXGLMPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys __lowercase = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
43
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class lowerCAmelCase__ ( __lowercase ): def __init__( self : int ) -> Optional[int]: __lowerCamelCase = [] def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: self.events.append('''on_init_end''' ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: self.events.append('''on_train_begin''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Any: self.events.append('''on_train_end''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: self.events.append('''on_epoch_begin''' ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: self.events.append('''on_epoch_end''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.events.append('''on_step_begin''' ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: self.events.append('''on_step_end''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: self.events.append('''on_evaluate''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : str ) -> str: self.events.append('''on_predict''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: self.events.append('''on_save''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: self.events.append('''on_log''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: self.events.append('''on_prediction_step''' ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = tempfile.mkdtemp() def __A ( self : int ) -> List[str]: shutil.rmtree(self.output_dir ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Any=0 , SCREAMING_SNAKE_CASE__ : List[str]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[int]=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionModelConfig(a=SCREAMING_SNAKE_CASE__ , b=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionPreTrainedModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = TrainingArguments(self.output_dir , disable_tqdm=SCREAMING_SNAKE_CASE__ , report_to=[] , **SCREAMING_SNAKE_CASE__ ) return Trainer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , callbacks=SCREAMING_SNAKE_CASE__ , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) # Order doesn't matter __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) for cba, cba in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , cba.__class__ ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(cba.__class__ , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: __lowerCamelCase = ['''on_init_end''', '''on_train_begin'''] __lowerCamelCase = 0 __lowerCamelCase = len(trainer.get_eval_dataloader() ) __lowerCamelCase = ['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append('''on_epoch_begin''' ) for _ in range(SCREAMING_SNAKE_CASE__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('''on_log''' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('''on_save''' ) expected_events.append('''on_epoch_end''' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = self.get_trainer() __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # Callbacks passed at init are added to the default callbacks __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback __lowerCamelCase = self.get_trainer(disable_tqdm=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> str: __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] __lowerCamelCase = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(cb.__class__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # We can also add, pop, or remove by instance __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> Any: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='''ignore''' , category=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # Independent log/save/eval __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='''steps''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='''epoch''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # A bit of everything __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy='''steps''' , ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # warning should be emitted for duplicated callbacks with patch('''transformers.trainer_callback.logger.warning''' ) as warn_mock: __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(SCREAMING_SNAKE_CASE__ ) in warn_mock.call_args[0][0]
270
0
"""simple docstring""" import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class __A : def __init__( self , a__ , a__=13 , a__=30 , a__=2 , a__=3 , a__=True , a__=True , a__=32 , a__=5 , a__=4 , a__=37 , a__="gelu" , a__=0.1 , a__=0.1 , a__=10 , a__=0.0_2 , a__=None , a__=2 , ): _lowerCAmelCase : List[Any] = parent _lowerCAmelCase : int = batch_size _lowerCAmelCase : Tuple = image_size _lowerCAmelCase : Optional[Any] = patch_size _lowerCAmelCase : int = num_channels _lowerCAmelCase : List[str] = is_training _lowerCAmelCase : Tuple = use_labels _lowerCAmelCase : Any = hidden_size _lowerCAmelCase : List[Any] = num_hidden_layers _lowerCAmelCase : List[str] = num_attention_heads _lowerCAmelCase : Optional[Any] = intermediate_size _lowerCAmelCase : Any = hidden_act _lowerCAmelCase : Tuple = hidden_dropout_prob _lowerCAmelCase : Optional[Any] = attention_probs_dropout_prob _lowerCAmelCase : Any = type_sequence_label_size _lowerCAmelCase : int = initializer_range _lowerCAmelCase : Any = scope _lowerCAmelCase : Union[str, Any] = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) _lowerCAmelCase : int = (image_size // patch_size) ** 2 _lowerCAmelCase : Optional[Any] = num_patches + 1 def __A ( self ): _lowerCAmelCase : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _lowerCAmelCase : Optional[int] = None if self.use_labels: _lowerCAmelCase : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCAmelCase : Dict = self.get_config() return config, pixel_values, labels def __A ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a__ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : str = ViTModel(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Optional[int] = model(a__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : Any = ViTForMaskedImageModeling(config=a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[str] = model(a__ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images _lowerCAmelCase : Union[str, Any] = 1 _lowerCAmelCase : Union[str, Any] = ViTForMaskedImageModeling(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : Any = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _lowerCAmelCase : Dict = model(a__ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __A ( self , a__ , a__ , a__ ): _lowerCAmelCase : Optional[int] = self.type_sequence_label_size _lowerCAmelCase : Dict = ViTForImageClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : int = model(a__ , labels=a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images _lowerCAmelCase : int = 1 _lowerCAmelCase : Dict = ViTForImageClassification(a__ ) model.to(a__ ) model.eval() _lowerCAmelCase : List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) _lowerCAmelCase : Tuple = model(a__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __A ( self ): _lowerCAmelCase : Dict = self.prepare_config_and_inputs() ( ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ( _lowerCAmelCase ) , ) : List[str] = config_and_inputs _lowerCAmelCase : Optional[Any] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_torch class __A ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): _UpperCamelCase : int = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) _UpperCamelCase : Tuple = ( {"feature-extraction": ViTModel, "image-classification": ViTForImageClassification} if is_torch_available() else {} ) _UpperCamelCase : Dict = True _UpperCamelCase : str = False _UpperCamelCase : Optional[Any] = False _UpperCamelCase : List[str] = False def __A ( self ): _lowerCAmelCase : Dict = ViTModelTester(self ) _lowerCAmelCase : Any = ConfigTester(self , config_class=a__ , has_text_modality=a__ , hidden_size=37 ) def __A ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="""ViT does not use inputs_embeds""" ) def __A ( self ): pass def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : List[str] = model_class(a__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) _lowerCAmelCase : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a__ , nn.Linear ) ) def __A ( self ): _lowerCAmelCase , _lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowerCAmelCase : Optional[Any] = model_class(a__ ) _lowerCAmelCase : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowerCAmelCase : List[str] = [*signature.parameters.keys()] _lowerCAmelCase : List[str] = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , a__ ) def __A ( self ): _lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a__ ) def __A ( self ): _lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a__ ) def __A ( self ): _lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a__ ) @slow def __A ( self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCAmelCase : List[str] = ViTModel.from_pretrained(a__ ) self.assertIsNotNone(a__ ) def SCREAMING_SNAKE_CASE ( ) -> List[str]: _lowerCAmelCase : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_torch @require_vision class __A ( unittest.TestCase ): @cached_property def __A ( self ): return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224""" ) if is_vision_available() else None @slow def __A ( self ): _lowerCAmelCase : Dict = ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224""" ).to(a__ ) _lowerCAmelCase : str = self.default_image_processor _lowerCAmelCase : str = prepare_img() _lowerCAmelCase : Tuple = image_processor(images=a__ , return_tensors="""pt""" ).to(a__ ) # forward pass with torch.no_grad(): _lowerCAmelCase : Optional[int] = model(**a__ ) # verify the logits _lowerCAmelCase : str = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a__ ) _lowerCAmelCase : List[Any] = torch.tensor([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6] ).to(a__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1e-4 ) ) @slow def __A ( self ): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. _lowerCAmelCase : Optional[Any] = ViTModel.from_pretrained("""facebook/dino-vits8""" ).to(a__ ) _lowerCAmelCase : str = ViTImageProcessor.from_pretrained("""facebook/dino-vits8""" , size=480 ) _lowerCAmelCase : Any = prepare_img() _lowerCAmelCase : Dict = image_processor(images=a__ , return_tensors="""pt""" ) _lowerCAmelCase : Optional[Any] = inputs.pixel_values.to(a__ ) # forward pass with torch.no_grad(): _lowerCAmelCase : str = model(a__ , interpolate_pos_encoding=a__ ) # verify the logits _lowerCAmelCase : str = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , a__ ) _lowerCAmelCase : Union[str, Any] = torch.tensor( [[4.2_3_4_0, 4.3_9_0_6, -6.6_6_9_2], [4.5_4_6_3, 1.8_9_2_8, -6.7_2_5_7], [4.4_4_2_9, 0.8_4_9_6, -5.8_5_8_5]] ).to(a__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , a__ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __A ( self ): _lowerCAmelCase : Optional[int] = ViTModel.from_pretrained("""facebook/dino-vits8""" , torch_dtype=torch.floataa , device_map="""auto""" ) _lowerCAmelCase : Union[str, Any] = self.default_image_processor _lowerCAmelCase : Dict = prepare_img() _lowerCAmelCase : List[str] = image_processor(images=a__ , return_tensors="""pt""" ) _lowerCAmelCase : Any = inputs.pixel_values.to(a__ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): _lowerCAmelCase : Optional[int] = model(a__ )
44
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowerCAmelCase__ : def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) __lowerCamelCase = img __lowerCamelCase = img.shape[1] __lowerCamelCase = img.shape[0] __lowerCamelCase = dst_width __lowerCamelCase = dst_height __lowerCamelCase = self.src_w / self.dst_w __lowerCamelCase = self.src_h / self.dst_h __lowerCamelCase = __lowerCamelCase = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def __A ( self : List[Any] ) -> str: for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase = self.img[self.get_y(SCREAMING_SNAKE_CASE__ )][self.get_x(SCREAMING_SNAKE_CASE__ )] def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_x * x ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_y * y ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = 800, 600 SCREAMING_SNAKE_CASE__ : int = imread("image_data/lena.jpg", 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
270
0
"""simple docstring""" import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler lowercase_ = 1_6 lowercase_ = 3_2 def lowercase ( lowerCAmelCase__ : Accelerator , lowerCAmelCase__ : int = 16 , lowerCAmelCase__ : str = "bert-base-cased" ) -> List[str]: __a = AutoTokenizer.from_pretrained(lowerCAmelCase__ ) __a = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(lowerCAmelCase__ : Any ): # max_length=None => use the model max length (it's actually the default) __a = 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 = 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 = 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 = DataLoader( tokenized_datasets['''train'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) __a = DataLoader( tokenized_datasets['''validation'''] , shuffle=lowerCAmelCase__ , collate_fn=lowerCAmelCase__ , batch_size=lowerCAmelCase__ ) return train_dataloader, eval_dataloader def lowercase ( lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any ) -> List[str]: # Initialize accelerator __a = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs __a = config['''lr'''] __a = int(config['''num_epochs'''] ) __a = int(config['''seed'''] ) __a = int(config['''batch_size'''] ) __a = args.model_name_or_path set_seed(lowerCAmelCase__ ) __a , __a = get_dataloaders(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) __a = AutoModelForSequenceClassification.from_pretrained(lowerCAmelCase__ , return_dict=lowerCAmelCase__ ) # Instantiate optimizer __a = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) __a = optimizer_cls(params=model.parameters() , lr=lowerCAmelCase__ ) if accelerator.state.deepspeed_plugin is not None: __a = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: __a = 1 __a = (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 = get_linear_schedule_with_warmup( optimizer=lowerCAmelCase__ , num_warmup_steps=0 , num_training_steps=lowerCAmelCase__ , ) else: __a = 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 = accelerator.prepare( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) # We need to keep track of how many total steps we have iterated over __a = 0 # We also need to keep track of the stating epoch so files are named properly __a = 0 # Now we train the model __a = evaluate.load('''glue''' , '''mrpc''' ) __a = 0 __a = {} for epoch in range(lowerCAmelCase__ , lowerCAmelCase__ ): model.train() for step, batch in enumerate(lowerCAmelCase__ ): __a = model(**lowerCAmelCase__ ) __a = outputs.loss __a = loss / gradient_accumulation_steps accelerator.backward(lowerCAmelCase__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 model.eval() __a = 0 for step, batch in enumerate(lowerCAmelCase__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): __a = model(**lowerCAmelCase__ ) __a = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times __a , __a = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(lowerCAmelCase__ ) - 1: __a = predictions[: len(eval_dataloader.dataset ) - samples_seen] __a = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=lowerCAmelCase__ , references=lowerCAmelCase__ , ) __a = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f'''epoch {epoch}:''' , lowerCAmelCase__ ) __a = eval_metric['''accuracy'''] if best_performance < eval_metric["accuracy"]: __a = eval_metric['''accuracy'''] if args.performance_lower_bound is not None: assert ( args.performance_lower_bound <= best_performance ), f'''Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}''' accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , '''all_results.json''' ) , '''w''' ) as f: json.dump(lowerCAmelCase__ , lowerCAmelCase__ ) def lowercase ( ) -> int: __a = 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( '''--performance_lower_bound''' , type=lowerCAmelCase__ , default=lowerCAmelCase__ , help='''Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.''' , ) parser.add_argument( '''--num_epochs''' , type=lowerCAmelCase__ , default=3 , help='''Number of train epochs.''' , ) __a = parser.parse_args() __a = {'''lr''': 2e-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(lowerCAmelCase__ , lowerCAmelCase__ ) if __name__ == "__main__": main()
45
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( __lowerCAmelCase : dict , __lowerCAmelCase : str , __lowerCAmelCase : set , __lowerCAmelCase : set , __lowerCAmelCase : dict , __lowerCAmelCase : dict , __lowerCAmelCase : PriorityQueue , __lowerCAmelCase : dict , __lowerCAmelCase : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCamelCase = cst_fwd.get(__lowerCAmelCase , np.inf ) __lowerCamelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCamelCase = new_cost_f __lowerCamelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCamelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : dict , __lowerCAmelCase : dict ) -> int: __lowerCamelCase = -1 __lowerCamelCase = set() __lowerCamelCase = set() __lowerCamelCase = {source: 0} __lowerCamelCase = {destination: 0} __lowerCamelCase = {source: None} __lowerCamelCase = {destination: None} __lowerCamelCase = PriorityQueue() __lowerCamelCase = PriorityQueue() __lowerCamelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCamelCase , __lowerCamelCase = queue_forward.get() visited_forward.add(__lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = queue_backward.get() visited_backward.add(__lowerCAmelCase ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCamelCase = shortest_distance return shortest_path_distance SCREAMING_SNAKE_CASE__ : List[Any] = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } SCREAMING_SNAKE_CASE__ : Optional[int] = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
270
0
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import CLIPTokenizer, CLIPTokenizerFast from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import CLIPImageProcessor, CLIPProcessor @require_vision class lowercase ( unittest.TestCase ): def _snake_case ( self ) -> int: lowerCAmelCase = tempfile.mkdtemp() # fmt: off lowerCAmelCase = ["""l""", """o""", """w""", """e""", """r""", """s""", """t""", """i""", """d""", """n""", """lo""", """l</w>""", """w</w>""", """r</w>""", """t</w>""", """low</w>""", """er</w>""", """lowest</w>""", """newer</w>""", """wider""", """<unk>""", """<|startoftext|>""", """<|endoftext|>"""] # fmt: on lowerCAmelCase = dict(zip(lowercase , range(len(lowercase ) ) ) ) lowerCAmelCase = ["""#version: 0.2""", """l o""", """lo w</w>""", """e r</w>""", """"""] lowerCAmelCase = {"""unk_token""": """<unk>"""} lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""merges_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as fp: fp.write(json.dumps(lowercase ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(lowercase ) ) lowerCAmelCase = { """do_resize""": True, """size""": 20, """do_center_crop""": True, """crop_size""": 18, """do_normalize""": True, """image_mean""": [0.48_145_466, 0.4_578_275, 0.40_821_073], """image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711], } lowerCAmelCase = os.path.join(self.tmpdirname , lowercase ) with open(self.image_processor_file , """w""" , encoding="""utf-8""" ) as fp: json.dump(lowercase , lowercase ) def _snake_case ( self , **lowercase ) -> Dict: return CLIPTokenizer.from_pretrained(self.tmpdirname , **lowercase ) def _snake_case ( self , **lowercase ) -> List[str]: return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **lowercase ) def _snake_case ( self , **lowercase ) -> int: return CLIPImageProcessor.from_pretrained(self.tmpdirname , **lowercase ) def _snake_case ( self ) -> Optional[int]: shutil.rmtree(self.tmpdirname ) def _snake_case ( self ) -> Optional[int]: lowerCAmelCase = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] lowerCAmelCase = [Image.fromarray(np.moveaxis(lowercase , 0 , -1 ) ) for x in image_inputs] return image_inputs def _snake_case ( self ) -> Union[str, Any]: lowerCAmelCase = self.get_tokenizer() lowerCAmelCase = self.get_rust_tokenizer() lowerCAmelCase = self.get_image_processor() lowerCAmelCase = CLIPProcessor(tokenizer=lowercase , image_processor=lowercase ) processor_slow.save_pretrained(self.tmpdirname ) lowerCAmelCase = CLIPProcessor.from_pretrained(self.tmpdirname , use_fast=lowercase ) lowerCAmelCase = CLIPProcessor(tokenizer=lowercase , image_processor=lowercase ) processor_fast.save_pretrained(self.tmpdirname ) lowerCAmelCase = CLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , lowercase ) self.assertIsInstance(processor_fast.tokenizer , lowercase ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , lowercase ) self.assertIsInstance(processor_fast.image_processor , lowercase ) def _snake_case ( self ) -> Any: lowerCAmelCase = CLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) lowerCAmelCase = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) lowerCAmelCase = self.get_image_processor(do_normalize=lowercase , padding_value=1.0 ) lowerCAmelCase = CLIPProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=lowercase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , lowercase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , lowercase ) def _snake_case ( self ) -> int: lowerCAmelCase = self.get_image_processor() lowerCAmelCase = self.get_tokenizer() lowerCAmelCase = CLIPProcessor(tokenizer=lowercase , image_processor=lowercase ) lowerCAmelCase = self.prepare_image_inputs() lowerCAmelCase = image_processor(lowercase , return_tensors="""np""" ) lowerCAmelCase = processor(images=lowercase , return_tensors="""np""" ) for key in input_image_proc.keys(): self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 ) def _snake_case ( self ) -> List[Any]: lowerCAmelCase = self.get_image_processor() lowerCAmelCase = self.get_tokenizer() lowerCAmelCase = CLIPProcessor(tokenizer=lowercase , image_processor=lowercase ) lowerCAmelCase = """lower newer""" lowerCAmelCase = processor(text=lowercase ) lowerCAmelCase = tokenizer(lowercase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def _snake_case ( self ) -> List[Any]: lowerCAmelCase = self.get_image_processor() lowerCAmelCase = self.get_tokenizer() lowerCAmelCase = CLIPProcessor(tokenizer=lowercase , image_processor=lowercase ) lowerCAmelCase = """lower newer""" lowerCAmelCase = self.prepare_image_inputs() lowerCAmelCase = processor(text=lowercase , images=lowercase ) self.assertListEqual(list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """pixel_values"""] ) # test if it raises when no input is passed with pytest.raises(lowercase ): processor() def _snake_case ( self ) -> int: lowerCAmelCase = self.get_image_processor() lowerCAmelCase = self.get_tokenizer() lowerCAmelCase = CLIPProcessor(tokenizer=lowercase , image_processor=lowercase ) lowerCAmelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] lowerCAmelCase = processor.batch_decode(lowercase ) lowerCAmelCase = tokenizer.batch_decode(lowercase ) self.assertListEqual(lowercase , lowercase ) def _snake_case ( self ) -> str: lowerCAmelCase = self.get_image_processor() lowerCAmelCase = self.get_tokenizer() lowerCAmelCase = CLIPProcessor(tokenizer=lowercase , image_processor=lowercase ) lowerCAmelCase = """lower newer""" lowerCAmelCase = self.prepare_image_inputs() lowerCAmelCase = processor(text=lowercase , images=lowercase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
46
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : List[Any] = TypeVar("T") def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (position - 1) // 2 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 1 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 2 class lowerCAmelCase__ ( Generic[T] ): def __init__( self : List[str] ) -> None: __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 def __len__( self : Optional[int] ) -> int: return self.elements def __repr__( self : Optional[int] ) -> str: return str(self.heap ) def __A ( self : Union[str, Any] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def __A ( self : str , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __lowerCamelCase = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __lowerCamelCase , __lowerCamelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowerCamelCase , __lowerCamelCase = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Update the weight of the given key __lowerCamelCase = self.position_map[elem] __lowerCamelCase = (elem, weight) if position > 0: __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __lowerCamelCase = self.position_map[elem] if curr_pos == 0: return None __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __lowerCamelCase = self.position_map[elem] __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: # Swap the nodes at the given positions __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase , __lowerCamelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowerCamelCase = nodea_pos __lowerCamelCase = nodea_pos class lowerCAmelCase__ ( Generic[T] ): def __init__( self : Tuple ) -> None: __lowerCamelCase = {} __lowerCamelCase = 0 def __repr__( self : Optional[int] ) -> str: return str(self.connections ) def __len__( self : List[str] ) -> int: return self.nodes def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __lowerCamelCase = {} self.nodes += 1 def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = weight __lowerCamelCase = weight def __magic_name__ ( __lowerCAmelCase : GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: __lowerCamelCase = {node: maxsize for node in graph.connections} __lowerCamelCase = {node: None for node in graph.connections} __lowerCamelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__lowerCAmelCase , __lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization __lowerCamelCase = priority_queue.extract_min() __lowerCamelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node # running prim's algorithm while not priority_queue.is_empty(): __lowerCamelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node return dist, parent
270
0
'''simple docstring''' import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets lowerCamelCase : List[Any] = "\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n" lowerCamelCase : Optional[Any] = "\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n" lowerCamelCase : int = "\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for 'cvit-mkb-clsr' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for 'cvit-mkb-clsr' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"precision\": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'precision@10': 1.0}\n\n" def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Tuple ) -> List[Any]: """simple docstring""" return float((preds == labels).mean() ) def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Any ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =simple_accuracy(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =float(fa_score(y_true=_UpperCamelCase , y_pred=_UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def _lowerCAmelCase ( _UpperCamelCase : Any , _UpperCamelCase : int ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =en_sentvecs.shape[0] # mean centering _SCREAMING_SNAKE_CASE =en_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =in_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =cdist(_UpperCamelCase , _UpperCamelCase , 'cosine' ) _SCREAMING_SNAKE_CASE =np.array(range(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =sim.argsort(axis=1 )[:, :10] _SCREAMING_SNAKE_CASE =np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Any ) -> List[str]: '''simple docstring''' if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), 'references': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), } ) , codebase_urls=[] , reference_urls=[] , format='numpy' if self.config_name != 'cvit-mkb-clsr' else None , ) def A ( self : List[str] , _a : Tuple , _a : Optional[int] ) -> int: '''simple docstring''' if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(_a , _a )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(_a , _a ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(_a , _a )} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' )
47
from __future__ import annotations from statistics import mean def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> list[int]: __lowerCamelCase = [0] * no_of_processes __lowerCamelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] __lowerCamelCase = [] __lowerCamelCase = 0 __lowerCamelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCamelCase = [] __lowerCamelCase = -1 for i in range(__lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: __lowerCamelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCamelCase = i total_time += burst_time[target_process] completed += 1 __lowerCamelCase = 0 __lowerCamelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : int , __lowerCAmelCase : list[int] ) -> list[int]: __lowerCamelCase = [0] * no_of_processes for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") SCREAMING_SNAKE_CASE__ : Tuple = 4 SCREAMING_SNAKE_CASE__ : Optional[int] = [2, 5, 3, 7] SCREAMING_SNAKE_CASE__ : List[str] = [0, 0, 0, 0] SCREAMING_SNAKE_CASE__ : str = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( F'{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t' F'{waiting_time[i]}\t\t\t\t{turn_around_time[i]}' ) print(F'\nAverage waiting time = {mean(waiting_time):.5f}') print(F'Average turnaround time = {mean(turn_around_time):.5f}')
270
0
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class UpperCamelCase__ (lowerCAmelCase__ , unittest.TestCase ): '''simple docstring''' lowerCamelCase_ : str = XLMRobertaTokenizer lowerCamelCase_ : str = XLMRobertaTokenizerFast lowerCamelCase_ : int = True lowerCamelCase_ : List[Any] = True def _lowercase ( self ) -> Optional[int]: super().setUp() # We have a SentencePiece fixture for testing lowerCamelCase : Any = XLMRobertaTokenizer(UpperCamelCase__ , keep_accents=UpperCamelCase__ ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase ( self ) -> List[str]: lowerCamelCase : Optional[int] = "<pad>" lowerCamelCase : Union[str, Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase__ ) , UpperCamelCase__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase__ ) , UpperCamelCase__ ) def _lowercase ( self ) -> Union[str, Any]: lowerCamelCase : str = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "<mask>" ) self.assertEqual(len(UpperCamelCase__ ) , 1002 ) def _lowercase ( self ) -> Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1002 ) def _lowercase ( self ) -> Any: lowerCamelCase : List[str] = XLMRobertaTokenizer(UpperCamelCase__ , keep_accents=UpperCamelCase__ ) lowerCamelCase : str = tokenizer.tokenize("This is a test" ) self.assertListEqual(UpperCamelCase__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) lowerCamelCase : int = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( UpperCamelCase__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowerCamelCase : Optional[int] = tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) self.assertListEqual( UpperCamelCase__ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) lowerCamelCase : Any = tokenizer.convert_ids_to_tokens(UpperCamelCase__ ) self.assertListEqual( UpperCamelCase__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def _lowercase ( self ) -> Any: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return lowerCamelCase : Dict = (self.rust_tokenizer_class, "hf-internal-testing/tiny-xlm-roberta", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): lowerCamelCase : str = self.rust_tokenizer_class.from_pretrained(UpperCamelCase__ , **UpperCamelCase__ ) lowerCamelCase : Any = self.tokenizer_class.from_pretrained(UpperCamelCase__ , **UpperCamelCase__ ) lowerCamelCase : Optional[Any] = tempfile.mkdtemp() lowerCamelCase : Dict = tokenizer_r.save_pretrained(UpperCamelCase__ ) lowerCamelCase : Tuple = tokenizer_p.save_pretrained(UpperCamelCase__ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) lowerCamelCase : Any = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(UpperCamelCase__ , UpperCamelCase__ ) # Checks everything loads correctly in the same way lowerCamelCase : int = tokenizer_r.from_pretrained(UpperCamelCase__ ) lowerCamelCase : Any = tokenizer_p.from_pretrained(UpperCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCamelCase__ , UpperCamelCase__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(UpperCamelCase__ ) # Save tokenizer rust, legacy_format=True lowerCamelCase : str = tempfile.mkdtemp() lowerCamelCase : int = tokenizer_r.save_pretrained(UpperCamelCase__ , legacy_format=UpperCamelCase__ ) lowerCamelCase : List[str] = tokenizer_p.save_pretrained(UpperCamelCase__ ) # Checks it save with the same files self.assertSequenceEqual(UpperCamelCase__ , UpperCamelCase__ ) # Checks everything loads correctly in the same way lowerCamelCase : Optional[int] = tokenizer_r.from_pretrained(UpperCamelCase__ ) lowerCamelCase : Any = tokenizer_p.from_pretrained(UpperCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCamelCase__ , UpperCamelCase__ ) ) shutil.rmtree(UpperCamelCase__ ) # Save tokenizer rust, legacy_format=False lowerCamelCase : List[str] = tempfile.mkdtemp() lowerCamelCase : Any = tokenizer_r.save_pretrained(UpperCamelCase__ , legacy_format=UpperCamelCase__ ) lowerCamelCase : int = tokenizer_p.save_pretrained(UpperCamelCase__ ) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way lowerCamelCase : List[str] = tokenizer_r.from_pretrained(UpperCamelCase__ ) lowerCamelCase : Optional[Any] = tokenizer_p.from_pretrained(UpperCamelCase__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(UpperCamelCase__ , UpperCamelCase__ ) ) shutil.rmtree(UpperCamelCase__ ) @cached_property def _lowercase ( self ) -> List[str]: return XLMRobertaTokenizer.from_pretrained("xlm-roberta-base" ) def _lowercase ( self ) -> List[Any]: with tempfile.NamedTemporaryFile() as f: shutil.copyfile(UpperCamelCase__ , f.name ) lowerCamelCase : Optional[Any] = XLMRobertaTokenizer(f.name , keep_accents=UpperCamelCase__ ) lowerCamelCase : Optional[Any] = pickle.dumps(UpperCamelCase__ ) pickle.loads(UpperCamelCase__ ) def _lowercase ( self ) -> int: if not self.test_rust_tokenizer: return lowerCamelCase : Dict = self.get_tokenizer() lowerCamelCase : Optional[Any] = self.get_rust_tokenizer() lowerCamelCase : int = "I was born in 92000, and this is falsé." lowerCamelCase : List[str] = tokenizer.tokenize(UpperCamelCase__ ) lowerCamelCase : List[Any] = rust_tokenizer.tokenize(UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : str = tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) lowerCamelCase : Union[str, Any] = rust_tokenizer.encode(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) lowerCamelCase : Optional[Any] = self.get_rust_tokenizer() lowerCamelCase : List[str] = tokenizer.encode(UpperCamelCase__ ) lowerCamelCase : int = rust_tokenizer.encode(UpperCamelCase__ ) self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ ) @slow def _lowercase ( self ) -> Dict: lowerCamelCase : str = "Hello World!" lowerCamelCase : Optional[Any] = [0, 3_5378, 6661, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(UpperCamelCase__ , self.big_tokenizer.encode(UpperCamelCase__ ) ) @slow def _lowercase ( self ) -> int: lowerCamelCase : List[str] = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) lowerCamelCase : Union[str, Any] = [ 0, 3293, 83, 10, 4552, 4989, 7986, 678, 10, 5915, 111, 17_9459, 12_4850, 4, 6044, 237, 12, 6, 5, 6, 4, 6780, 705, 15, 1388, 44, 378, 1_0114, 711, 152, 20, 6, 5, 2_2376, 642, 1221, 1_5190, 3_4153, 450, 5608, 959, 1119, 5_7702, 136, 186, 47, 1098, 2_9367, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 6044, 237, 6284, 5_0901, 528, 31, 90, 34, 927, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(UpperCamelCase__ , self.big_tokenizer.encode(UpperCamelCase__ ) ) @slow def _lowercase ( self ) -> Any: # fmt: off lowerCamelCase : int = {"input_ids": [[0, 1_1062, 8_2772, 7, 15, 8_2772, 538, 5_1529, 237, 1_7198, 1290, 206, 9, 21_5175, 1314, 136, 1_7198, 1290, 206, 9, 5_6359, 42, 12_2009, 9, 1_6466, 16, 8_7344, 4537, 9, 4717, 7_8381, 6, 15_9958, 7, 15, 2_4480, 618, 4, 527, 2_2693, 5428, 4, 2777, 2_4480, 9874, 4, 4_3523, 594, 4, 803, 1_8392, 3_3189, 18, 4, 4_3523, 2_4447, 1_2399, 100, 2_4955, 8_3658, 9626, 14_4057, 15, 839, 2_2335, 16, 136, 2_4955, 8_3658, 8_3479, 15, 3_9102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 12_2009, 11_5774, 23, 805, 1328, 4_6876, 7, 136, 5_3894, 1940, 4_2227, 4_1159, 1_7721, 823, 425, 4, 2_7512, 9_8722, 206, 136, 5531, 4970, 919, 1_7336, 5, 2], [0, 2_0080, 618, 83, 8_2775, 47, 479, 9, 1517, 73, 5_3894, 333, 8_0581, 11_0117, 1_8811, 5256, 1295, 51, 15_2526, 297, 7986, 390, 12_4416, 538, 3_5431, 214, 98, 1_5044, 2_5737, 136, 7108, 4_3701, 23, 756, 13_5355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 581, 6_3773, 11_9455, 6, 14_7797, 8_8203, 7, 645, 70, 21, 3285, 1_0269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCamelCase__ , model_name="xlm-roberta-base" , revision="d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3" , )
48
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( __lowercase ): @staticmethod @abstractmethod def __A ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> str: raise NotImplementedError() @abstractmethod def __A ( self : Optional[int] ) -> Union[str, Any]: raise NotImplementedError()
270
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging __snake_case :int = logging.get_logger(__name__) __snake_case :List[Any] = { '''facebook/deit-base-distilled-patch16-224''': ( '''https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json''' ), # See all DeiT models at https://huggingface.co/models?filter=deit } class _A ( __UpperCAmelCase ): UpperCamelCase__ : Optional[int] = '''deit''' def __init__( self : Optional[int] , __SCREAMING_SNAKE_CASE : Any=768 , __SCREAMING_SNAKE_CASE : str=12 , __SCREAMING_SNAKE_CASE : Any=12 , __SCREAMING_SNAKE_CASE : int=3_072 , __SCREAMING_SNAKE_CASE : Any="gelu" , __SCREAMING_SNAKE_CASE : List[str]=0.0 , __SCREAMING_SNAKE_CASE : Optional[int]=0.0 , __SCREAMING_SNAKE_CASE : Optional[int]=0.02 , __SCREAMING_SNAKE_CASE : int=1E-12 , __SCREAMING_SNAKE_CASE : Optional[int]=224 , __SCREAMING_SNAKE_CASE : Optional[int]=16 , __SCREAMING_SNAKE_CASE : Optional[Any]=3 , __SCREAMING_SNAKE_CASE : Dict=True , __SCREAMING_SNAKE_CASE : Any=16 , **__SCREAMING_SNAKE_CASE : List[Any] , ): '''simple docstring''' super().__init__(**__SCREAMING_SNAKE_CASE) __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = qkv_bias __a = encoder_stride class _A ( __UpperCAmelCase ): UpperCamelCase__ : Optional[int] = version.parse('''1.11''' ) @property def _lowerCamelCase ( self : str): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ]) @property def _lowerCamelCase ( self : Union[str, Any]): '''simple docstring''' return 1E-4
49
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue_model_parallelism.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> List[Any]: if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=SCREAMING_SNAKE_CASE__ , ) assert hasattr(self , '''env''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: # configuration for running training on smdistributed Model Parallel __lowerCamelCase = { '''enabled''': True, '''processes_per_host''': 8, } __lowerCamelCase = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __lowerCamelCase = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __lowerCamelCase = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=SCREAMING_SNAKE_CASE__ , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE__ , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 5_00, } , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE__ , py_version='''py36''' , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: TrainingJobAnalytics(SCREAMING_SNAKE_CASE__ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: # create estimator __lowerCamelCase = self.create_estimator(SCREAMING_SNAKE_CASE__ ) # run training estimator.fit() # result dataframe __lowerCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # 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} , SCREAMING_SNAKE_CASE__ )
270
0
# NOTE: This file is deprecated and will be removed in a future version. # It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works from ...utils import deprecate from ..controlnet.multicontrolnet import MultiControlNetModel # noqa: F401 from ..controlnet.pipeline_controlnet import StableDiffusionControlNetPipeline # noqa: F401 deprecate( """stable diffusion controlnet""", """0.22.0""", """Importing `StableDiffusionControlNetPipeline` or `MultiControlNetModel` from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet is deprecated. Please import `from diffusers import StableDiffusionControlNetPipeline` instead.""", standard_warn=False, stacklevel=3, )
50
from __future__ import annotations from fractions import Fraction def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def __magic_name__ ( __lowerCAmelCase : int ) -> list[str]: __lowerCamelCase = [] __lowerCamelCase = 11 __lowerCamelCase = int('''1''' + '''0''' * digit_len ) for num in range(__lowerCAmelCase , __lowerCAmelCase ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(__lowerCAmelCase , __lowerCAmelCase ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 __lowerCamelCase = 10 return solutions def __magic_name__ ( __lowerCAmelCase : int = 2 ) -> int: __lowerCamelCase = 1.0 for fraction in fraction_list(__lowerCAmelCase ): __lowerCamelCase = Fraction(__lowerCAmelCase ) result *= frac.denominator / frac.numerator return int(__lowerCAmelCase ) if __name__ == "__main__": print(solution())
270
0
import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class __snake_case ( a , unittest.TestCase ): UpperCAmelCase__ : Dict = BarthezTokenizer UpperCAmelCase__ : Optional[Any] = BarthezTokenizerFast UpperCAmelCase__ : Union[str, Any] = True UpperCAmelCase__ : Optional[Any] = True def lowerCamelCase ( self : Optional[int]): """simple docstring""" super().setUp() UpperCAmelCase_ = BarthezTokenizerFast.from_pretrained('''moussaKam/mbarthez''') tokenizer.save_pretrained(self.tmpdirname) tokenizer.save_pretrained(self.tmpdirname , legacy_format=_snake_case) UpperCAmelCase_ = tokenizer def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ = '''<pad>''' UpperCAmelCase_ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_snake_case) , _snake_case) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_snake_case) , _snake_case) def lowerCamelCase ( self : Any): """simple docstring""" UpperCAmelCase_ = list(self.get_tokenizer().get_vocab().keys()) self.assertEqual(vocab_keys[0] , '''<s>''') self.assertEqual(vocab_keys[1] , '''<pad>''') self.assertEqual(vocab_keys[-1] , '''<mask>''') self.assertEqual(len(_snake_case) , 101122) def lowerCamelCase ( self : Union[str, Any]): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 101122) @require_torch def lowerCamelCase ( self : Optional[Any]): """simple docstring""" UpperCAmelCase_ = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] UpperCAmelCase_ = [0, 57, 3018, 70307, 91, 2] UpperCAmelCase_ = self.tokenizer( _snake_case , max_length=len(_snake_case) , padding=_snake_case , truncation=_snake_case , return_tensors='''pt''') self.assertIsInstance(_snake_case , _snake_case) self.assertEqual((2, 6) , batch.input_ids.shape) self.assertEqual((2, 6) , batch.attention_mask.shape) UpperCAmelCase_ = batch.input_ids.tolist()[0] self.assertListEqual(_snake_case , _snake_case) def lowerCamelCase ( self : Optional[Any]): """simple docstring""" if not self.test_rust_tokenizer: return UpperCAmelCase_ = self.get_tokenizer() UpperCAmelCase_ = self.get_rust_tokenizer() UpperCAmelCase_ = '''I was born in 92000, and this is falsé.''' UpperCAmelCase_ = tokenizer.tokenize(_snake_case) UpperCAmelCase_ = rust_tokenizer.tokenize(_snake_case) self.assertListEqual(_snake_case , _snake_case) UpperCAmelCase_ = tokenizer.encode(_snake_case , add_special_tokens=_snake_case) UpperCAmelCase_ = rust_tokenizer.encode(_snake_case , add_special_tokens=_snake_case) self.assertListEqual(_snake_case , _snake_case) UpperCAmelCase_ = self.get_rust_tokenizer() UpperCAmelCase_ = tokenizer.encode(_snake_case) UpperCAmelCase_ = rust_tokenizer.encode(_snake_case) self.assertListEqual(_snake_case , _snake_case) @slow def lowerCamelCase ( self : List[str]): """simple docstring""" UpperCAmelCase_ = {'''input_ids''': [[0, 490, 14328, 4507, 354, 47, 43669, 95, 25, 78117, 20215, 19779, 190, 22, 400, 4, 35343, 80310, 603, 86, 24937, 105, 33438, 94762, 196, 39642, 7, 15, 15933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 10534, 87, 25, 66, 3358, 196, 55289, 8, 82961, 81, 2204, 75203, 7, 15, 763, 12956, 216, 178, 14328, 9595, 1377, 69693, 7, 448, 71021, 196, 18106, 1437, 13974, 108, 9083, 4, 49315, 7, 39, 86, 1326, 2793, 46333, 4, 448, 196, 74588, 7, 49315, 7, 39, 21, 822, 38470, 74, 21, 66723, 62480, 8, 22050, 5, 2]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. UpperCAmelCase_ = [ '''Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ''' '''utilisé principalement dans le domaine du traitement automatique des langues (TAL).''', '''À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ''' '''pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ''' '''telles que la traduction et la synthèse de texte.''', ] self.tokenizer_integration_test_util( expected_encoding=_snake_case , model_name='''moussaKam/mbarthez''' , revision='''c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6''' , sequences=_snake_case , )
51
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipTextConfig", "BlipVisionConfig", ], "processing_blip": ["BlipProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = ["BlipImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipModel", "BlipPreTrainedModel", "BlipForConditionalGeneration", "BlipForQuestionAnswering", "BlipVisionModel", "BlipTextModel", "BlipForImageTextRetrieval", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBlipModel", "TFBlipPreTrainedModel", "TFBlipForConditionalGeneration", "TFBlipForQuestionAnswering", "TFBlipVisionModel", "TFBlipTextModel", "TFBlipForImageTextRetrieval", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCamelCase : Union[str, Any] = { """configuration_tapas""": ["""TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TapasConfig"""], """tokenization_tapas""": ["""TapasTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Optional[Any] = [ """TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST""", """TapasForMaskedLM""", """TapasForQuestionAnswering""", """TapasForSequenceClassification""", """TapasModel""", """TapasPreTrainedModel""", """load_tf_weights_in_tapas""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : Union[str, Any] = [ """TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFTapasForMaskedLM""", """TFTapasForQuestionAnswering""", """TFTapasForSequenceClassification""", """TFTapasModel""", """TFTapasPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys __lowerCamelCase : Any = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
'''simple docstring''' from collections import defaultdict from pathlib import Path import pandas as pd from rouge_cli import calculate_rouge_path from utils import calculate_rouge a__ : str =[ '''Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of the''' ''' final seconds on board Flight 9525. The Germanwings co-pilot says he had a "previous episode of severe''' ''' depression\" German airline confirms it knew of Andreas Lubitz\'s depression years before he took control.''', '''The Palestinian Authority officially becomes the 123rd member of the International Criminal Court. The formal''' ''' accession was marked with a ceremony at The Hague, in the Netherlands. The Palestinians signed the ICC\'s''' ''' founding Rome Statute in January. Israel and the United States opposed the Palestinians\' efforts to join the''' ''' body.''', '''Amnesty International releases its annual report on the death penalty. The report catalogs the use of''' ''' state-sanctioned killing as a punitive measure across the globe. At least 607 people were executed around the''' ''' world in 2014, compared to 778 in 2013. The U.S. remains one of the worst offenders for imposing capital''' ''' punishment.''', ] a__ : List[str] =[ '''Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .''' ''' Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz''' ''' had informed his Lufthansa training school of an episode of severe depression, airline says .''', '''Membership gives the ICC jurisdiction over alleged crimes committed in Palestinian territories since last June .''' ''' Israel and the United States opposed the move, which could open the door to war crimes investigations against''' ''' Israelis .''', '''Amnesty\'s annual death penalty report catalogs encouraging signs, but setbacks in numbers of those sentenced to''' ''' death . Organization claims that governments around the world are using the threat of terrorism to advance''' ''' executions . The number of executions worldwide has gone down by almost 22% compared with 2013, but death''' ''' sentences up by 28% .''', ] def lowercase__ ( ) -> List[str]: """simple docstring""" __UpperCamelCase = calculate_rouge(__lowercase , __lowercase , bootstrap_aggregation=__lowercase , rouge_keys=['rouge2', 'rougeL'] ) assert isinstance(__lowercase , __lowercase ) __UpperCamelCase = calculate_rouge(__lowercase , __lowercase , bootstrap_aggregation=__lowercase , rouge_keys=['rouge2'] ) assert ( pd.DataFrame(no_aggregation['rouge2'] ).fmeasure.mean() == pd.DataFrame(no_aggregation_just_ra['rouge2'] ).fmeasure.mean() ) def lowercase__ ( ) -> str: """simple docstring""" __UpperCamelCase = 'rougeLsum' __UpperCamelCase = calculate_rouge(__lowercase , __lowercase , newline_sep=__lowercase , rouge_keys=[k] )[k] __UpperCamelCase = calculate_rouge(__lowercase , __lowercase , newline_sep=__lowercase , rouge_keys=[k] )[k] assert score > score_no_sep def lowercase__ ( ) -> Optional[int]: """simple docstring""" __UpperCamelCase = ['rouge1', 'rouge2', 'rougeL'] __UpperCamelCase = calculate_rouge(__lowercase , __lowercase , newline_sep=__lowercase , rouge_keys=__lowercase ) __UpperCamelCase = calculate_rouge(__lowercase , __lowercase , newline_sep=__lowercase , rouge_keys=__lowercase ) assert score_sep == score_no_sep def lowercase__ ( ) -> Optional[int]: """simple docstring""" __UpperCamelCase = [ 'Her older sister, Margot Frank, died in 1945, a month earlier than previously thought.', 'Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports .', ] __UpperCamelCase = [ 'Margot Frank, died in 1945, a month earlier than previously thought.', 'Prosecutor: "No videos were used in the crash investigation" German papers say they saw a cell phone video of' ' the final seconds on board Flight 9525.', ] assert calculate_rouge(__lowercase , __lowercase , newline_sep=__lowercase ) == calculate_rouge(__lowercase , __lowercase , newline_sep=__lowercase ) def lowercase__ ( ) -> int: """simple docstring""" __UpperCamelCase = [ '" "a person who has such a video needs to immediately give it to the investigators," prosecutor says .<n> "it is a very disturbing scene," editor-in-chief of bild online tells "erin burnett: outfront" ' ] __UpperCamelCase = [ ' Marseille prosecutor says "so far no videos were used in the crash investigation" despite media reports . Journalists at Bild and Paris Match are "very confident" the video clip is real, an editor says . Andreas Lubitz had informed his Lufthansa training school of an episode of severe depression, airline says .' ] __UpperCamelCase = calculate_rouge(__lowercase , __lowercase , rouge_keys=['rougeLsum'] , newline_sep=__lowercase )['rougeLsum'] __UpperCamelCase = calculate_rouge(__lowercase , __lowercase , rouge_keys=['rougeLsum'] )['rougeLsum'] assert new_score > prev_score def lowercase__ ( ) -> str: """simple docstring""" __UpperCamelCase = Path('examples/seq2seq/test_data/wmt_en_ro' ) __UpperCamelCase = calculate_rouge_path(data_dir.joinpath('test.source' ) , data_dir.joinpath('test.target' ) ) assert isinstance(__lowercase , __lowercase ) __UpperCamelCase = calculate_rouge_path( data_dir.joinpath('test.source' ) , data_dir.joinpath('test.target' ) , bootstrap_aggregation=__lowercase ) assert isinstance(__lowercase , __lowercase )
53
import pprint import requests SCREAMING_SNAKE_CASE__ : str = "https://zenquotes.io/api" def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = random_quotes() pprint.pprint(response)
270
0
"""simple docstring""" from __future__ import annotations def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None ): '''simple docstring''' if start is None: __SCREAMING_SNAKE_CASE = 0 if end is None: __SCREAMING_SNAKE_CASE = len(lowerCAmelCase_ ) - 1 if start >= end: return __SCREAMING_SNAKE_CASE = (start + end) // 2 slowsort(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) slowsort(lowerCAmelCase_ , mid + 1 , lowerCAmelCase_ ) if sequence[end] < sequence[mid]: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = sequence[mid], sequence[end] slowsort(lowerCAmelCase_ , lowerCAmelCase_ , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
54
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __magic_name__ ( __lowerCAmelCase : int ) -> int: __lowerCamelCase = prime_factors(__lowerCAmelCase ) if is_square_free(__lowerCAmelCase ): return -1 if len(__lowerCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
270
0
'''simple docstring''' from abc import ABC, abstractmethod from typing import List, Optional class snake_case ( lowercase ): """simple docstring""" def __init__( self ): """simple docstring""" # test for the above condition self.test() def snake_case ( self ): """simple docstring""" lowerCamelCase_ = 0 lowerCamelCase_ = False while not completed: if counter == 1: self.reset() lowerCamelCase_ = self.advance() if not self.does_advance(UpperCamelCase ): raise Exception( "Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true." ) lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = self.update(UpperCamelCase ) counter += 1 if counter > 1_0000: raise Exception("update() does not fulfill the constraint." ) if self.remaining() != 0: raise Exception("Custom Constraint is not defined correctly." ) @abstractmethod def snake_case ( self ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def snake_case ( self , UpperCamelCase ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def snake_case ( self , UpperCamelCase ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def snake_case ( self ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def snake_case ( self ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) @abstractmethod def snake_case ( self , UpperCamelCase=False ): """simple docstring""" raise NotImplementedError( f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class snake_case ( lowercase ): """simple docstring""" def __init__( self , UpperCamelCase ): """simple docstring""" super(UpperCamelCase , self ).__init__() if not isinstance(UpperCamelCase , UpperCamelCase ) or len(UpperCamelCase ) == 0: raise ValueError(f'''`token_ids` has to be a non-empty list, but is {token_ids}.''' ) if any((not isinstance(UpperCamelCase , UpperCamelCase ) or token_id < 0) for token_id in token_ids ): raise ValueError(f'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''' ) lowerCamelCase_ = token_ids lowerCamelCase_ = len(self.token_ids ) lowerCamelCase_ = -1 # the index of the currently fulfilled step lowerCamelCase_ = False def snake_case ( self ): """simple docstring""" if self.completed: return None return self.token_ids[self.fulfilled_idx + 1] def snake_case ( self , UpperCamelCase ): """simple docstring""" if not isinstance(UpperCamelCase , UpperCamelCase ): raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(UpperCamelCase )}''' ) if self.completed: return False return token_id == self.token_ids[self.fulfilled_idx + 1] def snake_case ( self , UpperCamelCase ): """simple docstring""" if not isinstance(UpperCamelCase , UpperCamelCase ): raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(UpperCamelCase )}''' ) lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False if self.does_advance(UpperCamelCase ): self.fulfilled_idx += 1 lowerCamelCase_ = True if self.fulfilled_idx == (self.seqlen - 1): lowerCamelCase_ = True lowerCamelCase_ = completed else: # failed to make progress. lowerCamelCase_ = True self.reset() return stepped, completed, reset def snake_case ( self ): """simple docstring""" lowerCamelCase_ = False lowerCamelCase_ = 0 def snake_case ( self ): """simple docstring""" return self.seqlen - (self.fulfilled_idx + 1) def snake_case ( self , UpperCamelCase=False ): """simple docstring""" lowerCamelCase_ = PhrasalConstraint(self.token_ids ) if stateful: lowerCamelCase_ = self.seqlen lowerCamelCase_ = self.fulfilled_idx lowerCamelCase_ = self.completed return new_constraint class snake_case : """simple docstring""" def __init__( self , UpperCamelCase , UpperCamelCase=True ): """simple docstring""" lowerCamelCase_ = max([len(UpperCamelCase ) for one in nested_token_ids] ) lowerCamelCase_ = {} for token_ids in nested_token_ids: lowerCamelCase_ = root for tidx, token_id in enumerate(UpperCamelCase ): if token_id not in level: lowerCamelCase_ = {} lowerCamelCase_ = level[token_id] if no_subsets and self.has_subsets(UpperCamelCase , UpperCamelCase ): raise ValueError( "Each list in `nested_token_ids` can't be a complete subset of another list, but is" f''' {nested_token_ids}.''' ) lowerCamelCase_ = root def snake_case ( self , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = self.trie for current_token in current_seq: lowerCamelCase_ = start[current_token] lowerCamelCase_ = list(start.keys() ) return next_tokens def snake_case ( self , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = self.next_tokens(UpperCamelCase ) return len(UpperCamelCase ) == 0 def snake_case ( self , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = list(root.values() ) if len(UpperCamelCase ) == 0: return 1 else: return sum([self.count_leaves(UpperCamelCase ) for nn in next_nodes] ) def snake_case ( self , UpperCamelCase , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = self.count_leaves(UpperCamelCase ) return len(UpperCamelCase ) != leaf_count class snake_case ( lowercase ): """simple docstring""" def __init__( self , UpperCamelCase ): """simple docstring""" super(UpperCamelCase , self ).__init__() if not isinstance(UpperCamelCase , UpperCamelCase ) or len(UpperCamelCase ) == 0: raise ValueError(f'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' ) if any(not isinstance(UpperCamelCase , UpperCamelCase ) for token_ids in nested_token_ids ): raise ValueError(f'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''' ) if any( any((not isinstance(UpperCamelCase , UpperCamelCase ) or token_id < 0) for token_id in token_ids ) for token_ids in nested_token_ids ): raise ValueError( f'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''' ) lowerCamelCase_ = DisjunctiveTrie(UpperCamelCase ) lowerCamelCase_ = nested_token_ids lowerCamelCase_ = self.trie.max_height lowerCamelCase_ = [] lowerCamelCase_ = False def snake_case ( self ): """simple docstring""" lowerCamelCase_ = self.trie.next_tokens(self.current_seq ) if len(UpperCamelCase ) == 0: return None else: return token_list def snake_case ( self , UpperCamelCase ): """simple docstring""" if not isinstance(UpperCamelCase , UpperCamelCase ): raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(UpperCamelCase )}''' ) lowerCamelCase_ = self.trie.next_tokens(self.current_seq ) return token_id in next_tokens def snake_case ( self , UpperCamelCase ): """simple docstring""" if not isinstance(UpperCamelCase , UpperCamelCase ): raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(UpperCamelCase )}''' ) lowerCamelCase_ = False lowerCamelCase_ = False lowerCamelCase_ = False if self.does_advance(UpperCamelCase ): self.current_seq.append(UpperCamelCase ) lowerCamelCase_ = True else: lowerCamelCase_ = True self.reset() lowerCamelCase_ = self.trie.reached_leaf(self.current_seq ) lowerCamelCase_ = completed return stepped, completed, reset def snake_case ( self ): """simple docstring""" lowerCamelCase_ = False lowerCamelCase_ = [] def snake_case ( self ): """simple docstring""" if self.completed: # since this can be completed without reaching max height return 0 else: return self.seqlen - len(self.current_seq ) def snake_case ( self , UpperCamelCase=False ): """simple docstring""" lowerCamelCase_ = DisjunctiveConstraint(self.token_ids ) if stateful: lowerCamelCase_ = self.seqlen lowerCamelCase_ = self.current_seq lowerCamelCase_ = self.completed return new_constraint class snake_case : """simple docstring""" def __init__( self , UpperCamelCase ): """simple docstring""" lowerCamelCase_ = constraints # max # of steps required to fulfill a given constraint lowerCamelCase_ = max([c.seqlen for c in constraints] ) lowerCamelCase_ = len(UpperCamelCase ) lowerCamelCase_ = False self.init_state() def snake_case ( self ): """simple docstring""" lowerCamelCase_ = [] lowerCamelCase_ = None lowerCamelCase_ = [constraint.copy(stateful=UpperCamelCase ) for constraint in self.constraints] def snake_case ( self ): """simple docstring""" lowerCamelCase_ = 0 if self.inprogress_constraint: # extra points for having a constraint mid-fulfilled add += self.max_seqlen - self.inprogress_constraint.remaining() return (len(self.complete_constraints ) * self.max_seqlen) + add def snake_case ( self ): """simple docstring""" lowerCamelCase_ = [] if self.inprogress_constraint is None: for constraint in self.pending_constraints: # "pending" == "unfulfilled yet" lowerCamelCase_ = constraint.advance() if isinstance(UpperCamelCase , UpperCamelCase ): token_list.append(UpperCamelCase ) elif isinstance(UpperCamelCase , UpperCamelCase ): token_list.extend(UpperCamelCase ) else: lowerCamelCase_ = self.inprogress_constraint.advance() if isinstance(UpperCamelCase , UpperCamelCase ): token_list.append(UpperCamelCase ) elif isinstance(UpperCamelCase , UpperCamelCase ): token_list.extend(UpperCamelCase ) if len(UpperCamelCase ) == 0: return None else: return token_list def snake_case ( self , UpperCamelCase ): """simple docstring""" self.init_state() if token_ids is not None: for token in token_ids: # completes or steps **one** constraint lowerCamelCase_ ,lowerCamelCase_ = self.add(UpperCamelCase ) # the entire list of constraints are fulfilled if self.completed: break def snake_case ( self , UpperCamelCase ): """simple docstring""" if not isinstance(UpperCamelCase , UpperCamelCase ): raise ValueError(f'''`token_id` should be an `int`, but is `{token_id}`.''' ) lowerCamelCase_ ,lowerCamelCase_ = False, False if self.completed: lowerCamelCase_ = True lowerCamelCase_ = False return complete, stepped if self.inprogress_constraint is not None: # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current # job, simply update the state lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = self.inprogress_constraint.update(UpperCamelCase ) if reset: # 1. If the next token breaks the progress, then we must restart. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books". # But that doesn't mean we self.init_state(), since we only reset the state for this particular # constraint, not the full list of constraints. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=UpperCamelCase ) ) lowerCamelCase_ = None if complete: # 2. If the next token completes the constraint, move it to completed list, set # inprogress to None. If there are no pending constraints either, then this full list of constraints # is complete. self.complete_constraints.append(self.inprogress_constraint ) lowerCamelCase_ = None if len(self.pending_constraints ) == 0: # we're done! lowerCamelCase_ = True else: # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list # of constraints? for cidx, pending_constraint in enumerate(self.pending_constraints ): if pending_constraint.does_advance(UpperCamelCase ): lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = pending_constraint.update(UpperCamelCase ) if not stepped: raise Exception( "`constraint.update(token_id)` is not yielding incremental progress, " "even though `constraint.does_advance(token_id)` is true." ) if complete: self.complete_constraints.append(UpperCamelCase ) lowerCamelCase_ = None if not complete and stepped: lowerCamelCase_ = pending_constraint if complete or stepped: # If we made any progress at all, then it's at least not a "pending constraint". lowerCamelCase_ = ( self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :] ) if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None: # If there's no longer any pending after this and no inprogress either, then we must be # complete. lowerCamelCase_ = True break # prevent accidentally stepping through multiple constraints with just one token. return complete, stepped def snake_case ( self , UpperCamelCase=True ): """simple docstring""" lowerCamelCase_ = ConstraintListState(self.constraints ) # we actually never though self.constraints objects # throughout this process. So it's at initialization state. if stateful: lowerCamelCase_ = [ constraint.copy(stateful=UpperCamelCase ) for constraint in self.complete_constraints ] if self.inprogress_constraint is not None: lowerCamelCase_ = self.inprogress_constraint.copy(stateful=UpperCamelCase ) lowerCamelCase_ = [constraint.copy() for constraint in self.pending_constraints] return new_state
55
import argparse import collections import json import os import re import string import sys import numpy as np SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"\b(a|an|the)\b", re.UNICODE) SCREAMING_SNAKE_CASE__ : int = None def __magic_name__ ( ) -> str: __lowerCamelCase = argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.''' ) parser.add_argument('''data_file''' , metavar='''data.json''' , help='''Input data JSON file.''' ) parser.add_argument('''pred_file''' , metavar='''pred.json''' , help='''Model predictions.''' ) parser.add_argument( '''--out-file''' , '''-o''' , metavar='''eval.json''' , help='''Write accuracy metrics to file (default is stdout).''' ) parser.add_argument( '''--na-prob-file''' , '''-n''' , metavar='''na_prob.json''' , help='''Model estimates of probability of no answer.''' ) parser.add_argument( '''--na-prob-thresh''' , '''-t''' , type=__lowerCAmelCase , default=1.0 , help='''Predict "" if no-answer probability exceeds this (default = 1.0).''' , ) parser.add_argument( '''--out-image-dir''' , '''-p''' , metavar='''out_images''' , default=__lowerCAmelCase , help='''Save precision-recall curves to directory.''' ) parser.add_argument('''--verbose''' , '''-v''' , action='''store_true''' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = bool(qa['''answers''']['''text'''] ) return qid_to_has_ans def __magic_name__ ( __lowerCAmelCase : Dict ) -> Optional[Any]: def remove_articles(__lowerCAmelCase : Optional[int] ): return ARTICLES_REGEX.sub(''' ''' , __lowerCAmelCase ) def white_space_fix(__lowerCAmelCase : Optional[int] ): return " ".join(text.split() ) def remove_punc(__lowerCAmelCase : Union[str, Any] ): __lowerCamelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__lowerCAmelCase : Dict ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__lowerCAmelCase ) ) ) ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Optional[int]: if not s: return [] return normalize_answer(__lowerCAmelCase ).split() def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple ) -> int: return int(normalize_answer(__lowerCAmelCase ) == normalize_answer(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple ) -> str: __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = collections.Counter(__lowerCAmelCase ) & collections.Counter(__lowerCAmelCase ) __lowerCamelCase = sum(common.values() ) if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = (2 * precision * recall) / (precision + recall) return fa def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] ) -> Optional[Any]: __lowerCamelCase = {} __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = qa['''id'''] __lowerCamelCase = [t for t in qa['''answers''']['''text'''] if normalize_answer(__lowerCAmelCase )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __lowerCamelCase = [''''''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue __lowerCamelCase = preds[qid] # Take max over all gold answers __lowerCamelCase = max(compute_exact(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) __lowerCamelCase = max(compute_fa(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) return exact_scores, fa_scores def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ) -> List[str]: __lowerCamelCase = {} for qid, s in scores.items(): __lowerCamelCase = na_probs[qid] > na_prob_thresh if pred_na: __lowerCamelCase = float(not qid_to_has_ans[qid] ) else: __lowerCamelCase = s return new_scores def __magic_name__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=None ) -> Union[str, Any]: if not qid_list: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores.values() ) / total), ('''f1''', 100.0 * sum(fa_scores.values() ) / total), ('''total''', total), ] ) else: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('''f1''', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('''total''', total), ] ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ) -> int: for k in new_eval: __lowerCamelCase = new_eval[k] def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ) -> Optional[Any]: plt.step(__lowerCAmelCase , __lowerCAmelCase , color='''b''' , alpha=0.2 , where='''post''' ) plt.fill_between(__lowerCAmelCase , __lowerCAmelCase , step='''post''' , alpha=0.2 , color='''b''' ) plt.xlabel('''Recall''' ) plt.ylabel('''Precision''' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__lowerCAmelCase ) plt.savefig(__lowerCAmelCase ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Tuple=None ) -> int: __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) __lowerCamelCase = 0.0 __lowerCamelCase = 1.0 __lowerCamelCase = 0.0 __lowerCamelCase = [1.0] __lowerCamelCase = [0.0] __lowerCamelCase = 0.0 for i, qid in enumerate(__lowerCAmelCase ): if qid_to_has_ans[qid]: true_pos += scores[qid] __lowerCamelCase = true_pos / float(i + 1 ) __lowerCamelCase = true_pos / float(__lowerCAmelCase ) if i == len(__lowerCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__lowerCAmelCase ) recalls.append(__lowerCAmelCase ) if out_image: plot_pr_curve(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return {"ap": 100.0 * avg_prec} def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] ) -> List[Any]: if out_image_dir and not os.path.exists(__lowerCAmelCase ): os.makedirs(__lowerCAmelCase ) __lowerCamelCase = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_exact.png''' ) , title='''Precision-Recall curve for Exact Match score''' , ) __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_f1.png''' ) , title='''Precision-Recall curve for F1 score''' , ) __lowerCamelCase = {k: float(__lowerCAmelCase ) for k, v in qid_to_has_ans.items()} __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_oracle.png''' ) , title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)''' , ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_exact''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_f1''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_oracle''' ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> Optional[Any]: if not qid_list: return __lowerCamelCase = [na_probs[k] for k in qid_list] __lowerCamelCase = np.ones_like(__lowerCAmelCase ) / float(len(__lowerCAmelCase ) ) plt.hist(__lowerCAmelCase , weights=__lowerCAmelCase , bins=20 , range=(0.0, 1.0) ) plt.xlabel('''Model probability of no-answer''' ) plt.ylabel('''Proportion of dataset''' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__lowerCAmelCase , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ) -> Optional[int]: __lowerCamelCase = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __lowerCamelCase = num_no_ans __lowerCamelCase = cur_score __lowerCamelCase = 0.0 __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) for i, qid in enumerate(__lowerCAmelCase ): if qid not in scores: continue if qid_to_has_ans[qid]: __lowerCamelCase = scores[qid] else: if preds[qid]: __lowerCamelCase = -1 else: __lowerCamelCase = 0 cur_score += diff if cur_score > best_score: __lowerCamelCase = cur_score __lowerCamelCase = na_probs[qid] return 100.0 * best_score / len(__lowerCAmelCase ), best_thresh def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] ) -> int: __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = best_exact __lowerCamelCase = exact_thresh __lowerCamelCase = best_fa __lowerCamelCase = fa_thresh def __magic_name__ ( ) -> Optional[int]: with open(OPTS.data_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) __lowerCamelCase = dataset_json['''data'''] with open(OPTS.pred_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) else: __lowerCamelCase = {k: 0.0 for k in preds} __lowerCamelCase = make_qid_to_has_ans(__lowerCAmelCase ) # maps qid to True/False __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if v] __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if not v] __lowerCamelCase , __lowerCamelCase = get_raw_scores(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase ) if has_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''HasAns''' ) if no_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''NoAns''' ) if OPTS.na_prob_file: find_all_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''hasAns''' ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''noAns''' ) if OPTS.out_file: with open(OPTS.out_file , '''w''' ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) else: print(json.dumps(__lowerCAmelCase , indent=2 ) ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
270
0
'''simple docstring''' from __future__ import annotations import math def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) -> int: '''simple docstring''' if depth < 0: raise ValueError('''Depth cannot be less than 0''' ) if len(__UpperCAmelCase ) == 0: raise ValueError('''Scores cannot be empty''' ) if depth == height: return scores[node_index] if is_max: return max( minimax(depth + 1, node_index * 2, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ), minimax(depth + 1, node_index * 2 + 1, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ), ) return min( minimax(depth + 1, node_index * 2, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ), minimax(depth + 1, node_index * 2 + 1, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ), ) def __magic_name__ ( ) -> None: '''simple docstring''' snake_case_ = [90, 23, 6, 33, 21, 65, 123, 3_4423] snake_case_ = math.log(len(__UpperCAmelCase ), 2 ) print('''Optimal value : ''', end='''''' ) print(minimax(0, 0, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
56
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F'{bindir}/../../examples/pytorch/translation'): from run_translation import main # noqa set_seed(42) SCREAMING_SNAKE_CASE__ : Any = "sshleifer/student_marian_en_ro_6_1" SCREAMING_SNAKE_CASE__ : Tuple = "sshleifer/tiny-mbart" @require_torch class lowerCAmelCase__ ( __lowercase ): def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , ) -> Optional[int]: __lowerCamelCase = self.run_trainer( eval_steps=1 , max_len=12 , model_name=SCREAMING_SNAKE_CASE__ , num_train_epochs=1 , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , predict_with_generate=SCREAMING_SNAKE_CASE__ , do_train=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history if not do_eval: return __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats __lowerCamelCase = eval_metrics[-1] assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) assert not math.isnan(float(last_step_stats['''eval_loss'''] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def __A ( self : Optional[int] ) -> int: self.run_seqaseq_quick() @require_torch_multi_gpu def __A ( self : int ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @require_torch_multi_gpu def __A ( self : Optional[Any] ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Optional[int] ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple --fp16''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Tuple ) -> Any: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick( distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2 --fp16''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @require_apex @require_torch_gpu def __A ( self : Union[str, Any] ) -> List[str]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) @parameterized.expand(['''base''', '''low''', '''high''', '''mixed'''] ) @require_torch_multi_gpu def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout __lowerCamelCase = { # test with the default log_level - should be info and thus log info once '''base''': {'''extra_args_str''': '''''', '''n_matches''': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes '''low''': {'''extra_args_str''': '''--log_level debug --log_level_replica debug''', '''n_matches''': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica '''high''': {'''extra_args_str''': '''--log_level error --log_level_replica debug''', '''n_matches''': 1}, # test with high log_level and log_level_replica - should be quiet on all processes '''mixed''': {'''extra_args_str''': '''--log_level error --log_level_replica error''', '''n_matches''': 0}, } __lowerCamelCase = experiments[experiment_id] __lowerCamelCase = {'''distributed''': True, '''predict_with_generate''': False, '''do_eval''': False, '''do_predict''': False} __lowerCamelCase = '''Running training''' with CaptureStderr() as cl: self.run_seqaseq_quick(**SCREAMING_SNAKE_CASE__ , extra_args_str=data['''extra_args_str'''] ) __lowerCamelCase = len(re.findall(SCREAMING_SNAKE_CASE__ , cl.err ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ , data['''n_matches'''] ) @slow def __A ( self : Any ) -> Optional[Any]: __lowerCamelCase = self.run_trainer( eval_steps=2 , max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=10 , distributed=SCREAMING_SNAKE_CASE__ , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] __lowerCamelCase = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) # test if do_predict saves generations and metrics __lowerCamelCase = os.listdir(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {os.path.basename(SCREAMING_SNAKE_CASE__ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def __A ( self : Optional[int] ) -> str: from transformers.training_args import OptimizerNames def train_and_return_metrics(SCREAMING_SNAKE_CASE__ : str ) -> Tuple[int, float]: __lowerCamelCase = '''--skip_memory_metrics 0''' __lowerCamelCase = self.run_trainer( max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=1 , optim=SCREAMING_SNAKE_CASE__ , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , n_gpus_to_use=1 , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(Path(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = int(logs[0]['''train_mem_gpu_peaked_delta'''] / 2**20 ) __lowerCamelCase = int(logs[0]['''train_mem_gpu_alloc_delta'''] / 2**20 ) __lowerCamelCase = logs[0]['''train_loss'''] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) __lowerCamelCase = gpu_alloc_mem_orig - gpu_alloc_mem_bnb __lowerCamelCase = gpu_peak_mem_orig + gpu_alloc_mem_orig __lowerCamelCase = gpu_peak_mem_bnb + gpu_alloc_mem_bnb __lowerCamelCase = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings __lowerCamelCase = 1_20 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and''' f''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , ) self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less total gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and''' f''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , ) self.assertEqual( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , f'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = 3e-3 , SCREAMING_SNAKE_CASE__ : str = "adafactor" , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : int = None , ) -> List[Any]: __lowerCamelCase = self.test_file_dir / '''../fixtures/tests_samples/wmt_en_ro''' __lowerCamelCase = self.get_auto_remove_tmp_dir() __lowerCamelCase = f''' --model_name_or_path {model_name} --train_file {data_dir}/train.json --validation_file {data_dir}/val.json --test_file {data_dir}/test.json --output_dir {output_dir} --overwrite_output_dir --max_train_samples 8 --max_source_length {max_len} --max_target_length {max_len} --do_train --num_train_epochs {str(SCREAMING_SNAKE_CASE__ )} --per_device_train_batch_size 4 --learning_rate {learning_rate} --warmup_steps 8 --logging_steps 0 --logging_strategy no --save_steps {str(SCREAMING_SNAKE_CASE__ )} --group_by_length --label_smoothing_factor 0.1 --target_lang ro_RO --source_lang en_XX '''.split() __lowerCamelCase = f''' --do_eval --per_device_eval_batch_size 4 --max_eval_samples 8 --val_max_target_length {max_len} --evaluation_strategy steps --eval_steps {str(SCREAMING_SNAKE_CASE__ )} '''.split() __lowerCamelCase = ''' --do_predict '''.split() __lowerCamelCase = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f'''--optim {optim}'''.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: __lowerCamelCase = get_gpu_count() __lowerCamelCase = get_torch_dist_unique_port() __lowerCamelCase = f''' -m torch.distributed.run --nproc_per_node={n_gpus_to_use} --master_port={master_port} {self.examples_dir_str}/pytorch/translation/run_translation.py '''.split() __lowerCamelCase = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) else: __lowerCamelCase = ['''run_translation.py'''] + args with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): main() return output_dir
270
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_flava import FlavaImageProcessor A : int = logging.get_logger(__name__) class _UpperCamelCase ( lowerCAmelCase__ ): '''simple docstring''' def __init__( self , *__a , **__a ): warnings.warn( "The class FlavaFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use FlavaImageProcessor instead." , __a , ) super().__init__(*__a , **__a )
57
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__ : Dict = { "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__ : int = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowercase ): a__ : Any = """mask2former""" a__ : Dict = ["""swin"""] a__ : Any = {"""hidden_size""": """hidden_dim"""} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 20_48 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_55 , SCREAMING_SNAKE_CASE__ : int = 1_00 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_25_44 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 16, 32] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> str: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.''' ) __lowerCamelCase = CONFIG_MAPPING['''swin''']( image_size=2_24 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = backbone_config.pop('''model_type''' ) __lowerCamelCase = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # 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 )}''' ) __lowerCamelCase = backbone_config __lowerCamelCase = feature_size __lowerCamelCase = mask_feature_size __lowerCamelCase = hidden_dim __lowerCamelCase = encoder_feedforward_dim __lowerCamelCase = activation_function __lowerCamelCase = encoder_layers __lowerCamelCase = decoder_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = dropout __lowerCamelCase = dim_feedforward __lowerCamelCase = pre_norm __lowerCamelCase = enforce_input_projection __lowerCamelCase = common_stride __lowerCamelCase = ignore_value __lowerCamelCase = num_queries __lowerCamelCase = no_object_weight __lowerCamelCase = class_weight __lowerCamelCase = mask_weight __lowerCamelCase = dice_weight __lowerCamelCase = train_num_points __lowerCamelCase = oversample_ratio __lowerCamelCase = importance_sample_ratio __lowerCamelCase = init_std __lowerCamelCase = init_xavier_std __lowerCamelCase = use_auxiliary_loss __lowerCamelCase = feature_strides __lowerCamelCase = output_auxiliary_logits __lowerCamelCase = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def __A ( cls : Any , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Any ) -> Dict[str, any]: __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.backbone_config.to_dict() __lowerCamelCase = self.__class__.model_type return output
270
0
'''simple docstring''' def lowerCamelCase ( __lowerCamelCase : int = 400_0000 ) ->int: _SCREAMING_SNAKE_CASE = [0, 1] _SCREAMING_SNAKE_CASE = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 _SCREAMING_SNAKE_CASE = 0 for j in range(len(__lowerCamelCase ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f"""{solution() = }""")
58
import os def __magic_name__ ( ) -> str: __lowerCamelCase = os.path.join(os.path.dirname(__lowerCAmelCase ) , '''num.txt''' ) with open(__lowerCAmelCase ) as file_hand: return str(sum(int(__lowerCAmelCase ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
270
0
import argparse from collections import defaultdict import yaml __lowerCamelCase = """docs/source/en/_toctree.yml""" def UpperCamelCase ( __lowerCamelCase : Optional[Any] ): snake_case : Any = defaultdict(__lowerCamelCase ) snake_case : List[Any] = [] snake_case : List[str] = [] for doc in doc_list: if "local" in doc: counts[doc["local"]] += 1 if doc["title"].lower() == "overview": overview_doc.append({"local": doc["local"], "title": doc["title"]} ) else: new_doc_list.append(__lowerCamelCase ) snake_case : List[str] = new_doc_list snake_case : Optional[int] = [key for key, value in counts.items() if value > 1] snake_case : Any = [] for duplicate_key in duplicates: snake_case : List[str] = list({doc["title"] for doc in doc_list if doc["local"] == duplicate_key} ) if len(__lowerCamelCase ) > 1: raise ValueError( f"""{duplicate_key} is present several times in the documentation table of content at """ "`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the " "others." ) # Only add this once new_doc.append({"local": duplicate_key, "title": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in doc_list if "local" not in counts or counts[doc["local"]] == 1] ) snake_case : Union[str, Any] = sorted(__lowerCamelCase , key=lambda __lowerCamelCase : s["title"].lower() ) # "overview" gets special treatment and is always first if len(__lowerCamelCase ) > 1: raise ValueError("{doc_list} has two 'overview' docs which is not allowed." ) overview_doc.extend(__lowerCamelCase ) # Sort return overview_doc def UpperCamelCase ( __lowerCamelCase : Any=False ): with open(__lowerCamelCase , encoding="utf-8" ) as f: snake_case : Optional[Any] = yaml.safe_load(f.read() ) # Get to the API doc snake_case : List[str] = 0 while content[api_idx]["title"] != "API": api_idx += 1 snake_case : str = content[api_idx]["sections"] # Then to the model doc snake_case : Optional[int] = 0 while api_doc[scheduler_idx]["title"] != "Schedulers": scheduler_idx += 1 snake_case : Dict = api_doc[scheduler_idx]["sections"] snake_case : Any = clean_doc_toc(__lowerCamelCase ) snake_case : str = False if new_scheduler_doc != scheduler_doc: snake_case : Dict = True if overwrite: snake_case : int = new_scheduler_doc if diff: if overwrite: snake_case : Dict = api_doc with open(__lowerCamelCase , "w" , encoding="utf-8" ) as f: f.write(yaml.dump(__lowerCamelCase , allow_unicode=__lowerCamelCase ) ) else: raise ValueError( "The model doc part of the table of content is not properly sorted, run `make style` to fix this." ) def UpperCamelCase ( __lowerCamelCase : int=False ): with open(__lowerCamelCase , encoding="utf-8" ) as f: snake_case : str = yaml.safe_load(f.read() ) # Get to the API doc snake_case : str = 0 while content[api_idx]["title"] != "API": api_idx += 1 snake_case : List[Any] = content[api_idx]["sections"] # Then to the model doc snake_case : Tuple = 0 while api_doc[pipeline_idx]["title"] != "Pipelines": pipeline_idx += 1 snake_case : int = False snake_case : Optional[int] = api_doc[pipeline_idx]["sections"] snake_case : Any = [] # sort sub pipeline docs for pipeline_doc in pipeline_docs: if "section" in pipeline_doc: snake_case : str = pipeline_doc["section"] snake_case : Optional[int] = clean_doc_toc(__lowerCamelCase ) if overwrite: snake_case : Any = new_sub_pipeline_doc new_pipeline_docs.append(__lowerCamelCase ) # sort overall pipeline doc snake_case : Tuple = clean_doc_toc(__lowerCamelCase ) if new_pipeline_docs != pipeline_docs: snake_case : Optional[int] = True if overwrite: snake_case : Optional[int] = new_pipeline_docs if diff: if overwrite: snake_case : int = api_doc with open(__lowerCamelCase , "w" , encoding="utf-8" ) as f: f.write(yaml.dump(__lowerCamelCase , allow_unicode=__lowerCamelCase ) ) else: raise ValueError( "The model doc part of the table of content is not properly sorted, run `make style` to fix this." ) if __name__ == "__main__": __lowerCamelCase = argparse.ArgumentParser() parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""") __lowerCamelCase = parser.parse_args() check_scheduler_doc(args.fix_and_overwrite) check_pipeline_doc(args.fix_and_overwrite)
59
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str a__ : List[str] a__ : Optional[List[str]] @dataclass class lowerCAmelCase__ : a__ : List[int] a__ : List[int] a__ : Optional[List[int]] = None a__ : Optional[List[int]] = None class lowerCAmelCase__ ( __lowercase ): a__ : Optional[Any] = """train""" a__ : Optional[int] = """dev""" a__ : Dict = """test""" class lowerCAmelCase__ : @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[Split, str] ) -> List[InputExample]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : str ) -> List[str]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : List[InputExample] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]="[CLS]" , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str="[SEP]" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : str=-1_00 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[Any]=True , ) -> List[InputFeatures]: __lowerCamelCase = {label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} __lowerCamelCase = [] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE__ ): if ex_index % 1_00_00 == 0: logger.info('''Writing example %d of %d''' , SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [] __lowerCamelCase = [] for word, label in zip(example.words , example.labels ): __lowerCamelCase = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE__ ) > 0: tokens.extend(SCREAMING_SNAKE_CASE__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __lowerCamelCase = tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE__ ) > max_seq_length - special_tokens_count: __lowerCamelCase = tokens[: (max_seq_length - special_tokens_count)] __lowerCamelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __lowerCamelCase = [sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __lowerCamelCase = [cls_token] + tokens __lowerCamelCase = [pad_token_label_id] + label_ids __lowerCamelCase = [cls_token_segment_id] + segment_ids __lowerCamelCase = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __lowerCamelCase = [1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE__ ) # Zero-pad up to the sequence length. __lowerCamelCase = max_seq_length - len(SCREAMING_SNAKE_CASE__ ) if pad_on_left: __lowerCamelCase = ([pad_token] * padding_length) + input_ids __lowerCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __lowerCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids __lowerCamelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , label_ids=SCREAMING_SNAKE_CASE__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowerCAmelCase__ ( __lowercase ): a__ : List[InputFeatures] a__ : int = nn.CrossEntropyLoss().ignore_index def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> Union[str, Any]: # Load data features from cache or dataset file __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __lowerCamelCase = cached_features_file + '''.lock''' with FileLock(SCREAMING_SNAKE_CASE__ ): if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) __lowerCamelCase = torch.load(SCREAMING_SNAKE_CASE__ ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , SCREAMING_SNAKE_CASE__ ) def __len__( self : Dict ) -> str: return len(self.features ) def __getitem__( self : Any , SCREAMING_SNAKE_CASE__ : Dict ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowerCAmelCase__ : a__ : List[InputFeatures] a__ : int = -100 def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> List[Any]: __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : List[Any] ) -> Any: return len(self.features ) def __getitem__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> InputFeatures: return self.features[i]
270
0
"""simple docstring""" import inspect import unittest from transformers import DPTConfig from transformers.file_utils import is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DPTImageProcessor class snake_case_: def __init__( self : List[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Any=2 , UpperCamelCase_ : Union[str, Any]=3_2 , UpperCamelCase_ : int=1_6 , UpperCamelCase_ : str=3 , UpperCamelCase_ : Dict=True , UpperCamelCase_ : Dict=True , UpperCamelCase_ : Optional[Any]=3_2 , UpperCamelCase_ : Optional[int]=4 , UpperCamelCase_ : Tuple=[0, 1, 2, 3] , UpperCamelCase_ : Dict=4 , UpperCamelCase_ : Union[str, Any]=3_7 , UpperCamelCase_ : Optional[Any]="gelu" , UpperCamelCase_ : Dict=0.1 , UpperCamelCase_ : Tuple=0.1 , UpperCamelCase_ : Optional[Any]=0.02 , UpperCamelCase_ : List[str]=3 , UpperCamelCase_ : Any=[1, 3_8_4, 2_4, 2_4] , UpperCamelCase_ : Union[str, Any]=True , UpperCamelCase_ : Tuple=None , ): lowerCAmelCase : Optional[Any] = parent lowerCAmelCase : Dict = batch_size lowerCAmelCase : Any = image_size lowerCAmelCase : List[Any] = patch_size lowerCAmelCase : Dict = num_channels lowerCAmelCase : Optional[Any] = is_training lowerCAmelCase : List[Any] = use_labels lowerCAmelCase : List[Any] = hidden_size lowerCAmelCase : Any = num_hidden_layers lowerCAmelCase : Optional[Any] = backbone_out_indices lowerCAmelCase : Union[str, Any] = num_attention_heads lowerCAmelCase : Optional[int] = intermediate_size lowerCAmelCase : List[Any] = hidden_act lowerCAmelCase : List[Any] = hidden_dropout_prob lowerCAmelCase : Dict = attention_probs_dropout_prob lowerCAmelCase : List[str] = initializer_range lowerCAmelCase : Tuple = num_labels lowerCAmelCase : Any = backbone_featmap_shape lowerCAmelCase : List[str] = scope lowerCAmelCase : List[Any] = is_hybrid # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token) lowerCAmelCase : Any = (image_size // patch_size) ** 2 lowerCAmelCase : List[str] = num_patches + 1 def lowerCamelCase__ ( self : str ): lowerCAmelCase : str = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase : List[Any] = None if self.use_labels: lowerCAmelCase : Tuple = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowerCAmelCase : Tuple = self.get_config() return config, pixel_values, labels def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : str = { '''global_padding''': '''same''', '''layer_type''': '''bottleneck''', '''depths''': [3, 4, 9], '''out_features''': ['''stage1''', '''stage2''', '''stage3'''], '''embedding_dynamic_padding''': True, '''hidden_sizes''': [9_6, 1_9_2, 3_8_4, 7_6_8], '''num_groups''': 2, } return DPTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , backbone_out_indices=self.backbone_out_indices , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=UpperCamelCase_ , initializer_range=self.initializer_range , is_hybrid=self.is_hybrid , backbone_config=UpperCamelCase_ , backbone_featmap_shape=self.backbone_featmap_shape , ) def lowerCamelCase__ ( self : str , UpperCamelCase_ : int , UpperCamelCase_ : Tuple , UpperCamelCase_ : Dict ): lowerCAmelCase : Optional[Any] = DPTModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : Dict = model(UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : List[str] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : List[str] ): lowerCAmelCase : Dict = self.num_labels lowerCAmelCase : List[Any] = DPTForDepthEstimation(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : int = model(UpperCamelCase_ ) self.parent.assertEqual(result.predicted_depth.shape , (self.batch_size, self.image_size, self.image_size) ) def lowerCamelCase__ ( self : List[Any] , UpperCamelCase_ : str , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Optional[Any] ): lowerCAmelCase : Optional[int] = self.num_labels lowerCAmelCase : Optional[int] = DPTForSemanticSegmentation(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : int = model(UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : str = self.prepare_config_and_inputs() lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : int = config_and_inputs lowerCAmelCase : Any = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class snake_case_( a__ , a__ , unittest.TestCase ): __UpperCamelCase = (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else () __UpperCamelCase = ( { '''depth-estimation''': DPTForDepthEstimation, '''feature-extraction''': DPTModel, '''image-segmentation''': DPTForSemanticSegmentation, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase : Any = DPTModelTester(self ) lowerCAmelCase : str = ConfigTester(self , config_class=UpperCamelCase_ , has_text_modality=UpperCamelCase_ , hidden_size=3_7 ) def lowerCamelCase__ ( self : List[Any] ): self.config_tester.run_common_tests() @unittest.skip(reason='''DPT does not use inputs_embeds''' ) def lowerCamelCase__ ( self : int ): pass def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase, lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase : str = model_class(UpperCamelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase : Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase_ , nn.Linear ) ) def lowerCamelCase__ ( self : Dict ): lowerCAmelCase, lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase : List[str] = model_class(UpperCamelCase_ ) lowerCAmelCase : str = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase : Union[str, Any] = [*signature.parameters.keys()] lowerCAmelCase : List[str] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , UpperCamelCase_ ) def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase_ ) def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_depth_estimation(*UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase_ ) def lowerCamelCase__ ( self : List[str] ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue lowerCAmelCase, lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Optional[int] = True if model_class in get_values(UpperCamelCase_ ): continue lowerCAmelCase : List[str] = model_class(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.train() lowerCAmelCase : Dict = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ , return_labels=UpperCamelCase_ ) lowerCAmelCase : int = model(**UpperCamelCase_ ).loss loss.backward() def lowerCamelCase__ ( self : int ): for model_class in self.all_model_classes: if model_class.__name__ == "DPTForDepthEstimation": continue lowerCAmelCase, lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Optional[int] = False lowerCAmelCase : Optional[int] = True if model_class in get_values(UpperCamelCase_ ) or not model_class.supports_gradient_checkpointing: continue lowerCAmelCase : Union[str, Any] = model_class(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.gradient_checkpointing_enable() model.train() lowerCAmelCase : int = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ , return_labels=UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = model(**UpperCamelCase_ ).loss loss.backward() def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase, lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Dict = _config_zero_init(UpperCamelCase_ ) for model_class in self.all_model_classes: lowerCAmelCase : int = model_class(config=UpperCamelCase_ ) # Skip the check for the backbone lowerCAmelCase : Tuple = [] for name, module in model.named_modules(): if module.__class__.__name__ == "DPTViTHybridEmbeddings": lowerCAmelCase : Any = [F'''{name}.{key}''' for key in module.state_dict().keys()] break for name, param in model.named_parameters(): if param.requires_grad: if name in backbone_params: continue self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def lowerCamelCase__ ( self : List[str] ): pass @slow def lowerCamelCase__ ( self : List[str] ): for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]: lowerCAmelCase : Any = DPTModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) def lowerCamelCase__ ( self : Any ): # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type lowerCAmelCase, lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : List[Any] = '''add''' with self.assertRaises(UpperCamelCase_ ): lowerCAmelCase : Optional[int] = DPTForDepthEstimation(UpperCamelCase_ ) def _snake_case ( ): lowerCAmelCase : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision @slow class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : str ): lowerCAmelCase : Tuple = DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''' ) lowerCAmelCase : Optional[Any] = DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''' ).to(UpperCamelCase_ ) lowerCAmelCase : str = prepare_img() lowerCAmelCase : int = image_processor(images=UpperCamelCase_ , return_tensors='''pt''' ).to(UpperCamelCase_ ) # forward pass with torch.no_grad(): lowerCAmelCase : List[Any] = model(**UpperCamelCase_ ) lowerCAmelCase : Tuple = outputs.predicted_depth # verify the predicted depth lowerCAmelCase : List[Any] = torch.Size((1, 3_8_4, 3_8_4) ) self.assertEqual(predicted_depth.shape , UpperCamelCase_ ) lowerCAmelCase : Dict = torch.tensor( [[[5.6_437, 5.6_146, 5.6_511], [5.4_371, 5.5_649, 5.5_958], [5.5_215, 5.5_184, 5.5_293]]] ).to(UpperCamelCase_ ) self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 1_0_0 , UpperCamelCase_ , atol=1E-4 ) )
60
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase__ ( __lowercase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : NestedDataStructureLike[PathLike] , SCREAMING_SNAKE_CASE__ : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE__ : Optional[Features] = None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : str , ) -> Union[str, Any]: super().__init__( SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ , streaming=SCREAMING_SNAKE_CASE__ , num_proc=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = path_or_paths if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else {self.split: path_or_paths} __lowerCamelCase = Text( cache_dir=SCREAMING_SNAKE_CASE__ , data_files=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : int ) -> Dict: # Build iterable dataset if self.streaming: __lowerCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE__ , download_mode=SCREAMING_SNAKE_CASE__ , verification_mode=SCREAMING_SNAKE_CASE__ , base_path=SCREAMING_SNAKE_CASE__ , num_proc=self.num_proc , ) __lowerCamelCase = self.builder.as_dataset( split=self.split , verification_mode=SCREAMING_SNAKE_CASE__ , in_memory=self.keep_in_memory ) return dataset
270
0
"""simple docstring""" def __a ( __lowerCamelCase, __lowerCamelCase ): return price * (1 + tax_rate) if __name__ == "__main__": print(f"""{price_plus_tax(100, 0.25) = }""") print(f"""{price_plus_tax(125.50, 0.05) = }""")
61
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
270
0
import collections import gzip import os import urllib import numpy from tensorflow.python.framework import dtypes, random_seed from tensorflow.python.platform import gfile from tensorflow.python.util.deprecation import deprecated _A = collections.namedtuple('_Datasets', ['train', 'validation', 'test']) # CVDF mirror of http://yann.lecun.com/exdb/mnist/ _A = 'https://storage.googleapis.com/cvdf-datasets/mnist/' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : int ): __UpperCamelCase =numpy.dtype(numpy.uintaa ).newbyteorder('>' ) return numpy.frombuffer(bytestream.read(4 ) , dtype=SCREAMING_SNAKE_CASE__ )[0] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[Any] ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_51: raise ValueError( 'Invalid magic number %d in MNIST image file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(rows * cols * num_images ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) __UpperCamelCase =data.reshape(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 1 ) return data @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.one_hot on tensors.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] ): __UpperCamelCase =labels_dense.shape[0] __UpperCamelCase =numpy.arange(SCREAMING_SNAKE_CASE__ ) * num_classes __UpperCamelCase =numpy.zeros((num_labels, num_classes) ) __UpperCamelCase =1 return labels_one_hot @deprecated(SCREAMING_SNAKE_CASE__ , 'Please use tf.data to implement this functionality.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : Dict=False , SCREAMING_SNAKE_CASE__ : str=10 ): print('Extracting' , f.name ) with gzip.GzipFile(fileobj=SCREAMING_SNAKE_CASE__ ) as bytestream: __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) if magic != 20_49: raise ValueError( 'Invalid magic number %d in MNIST label file: %s' % (magic, f.name) ) __UpperCamelCase =_readaa(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =bytestream.read(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =numpy.frombuffer(SCREAMING_SNAKE_CASE__ , dtype=numpy.uinta ) if one_hot: return _dense_to_one_hot(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return labels class UpperCAmelCase__ : """simple docstring""" @deprecated( A_ , 'Please use alternatives such as official/mnist/_DataSet.py' ' from tensorflow/models.' , ) def __init__( self , A_ , A_ , A_=False , A_=False , A_=dtypes.floataa , A_=True , A_=None , ) -> Optional[int]: __UpperCamelCase , __UpperCamelCase =random_seed.get_seed(A_ ) # If op level seed is not set, use whatever graph level seed is returned numpy.random.seed(seeda if seed is None else seeda ) __UpperCamelCase =dtypes.as_dtype(A_ ).base_dtype if dtype not in (dtypes.uinta, dtypes.floataa): raise TypeError('Invalid image dtype %r, expected uint8 or float32' % dtype ) if fake_data: __UpperCamelCase =10000 __UpperCamelCase =one_hot else: assert ( images.shape[0] == labels.shape[0] ), f'images.shape: {images.shape} labels.shape: {labels.shape}' __UpperCamelCase =images.shape[0] # Convert shape from [num examples, rows, columns, depth] # to [num examples, rows*columns] (assuming depth == 1) if reshape: assert images.shape[3] == 1 __UpperCamelCase =images.reshape( images.shape[0] , images.shape[1] * images.shape[2] ) if dtype == dtypes.floataa: # Convert from [0, 255] -> [0.0, 1.0]. __UpperCamelCase =images.astype(numpy.floataa ) __UpperCamelCase =numpy.multiply(A_ , 1.0 / 255.0 ) __UpperCamelCase =images __UpperCamelCase =labels __UpperCamelCase =0 __UpperCamelCase =0 @property def _a ( self ) -> Tuple: return self._images @property def _a ( self ) -> Union[str, Any]: return self._labels @property def _a ( self ) -> Optional[Any]: return self._num_examples @property def _a ( self ) -> List[str]: return self._epochs_completed def _a ( self , A_ , A_=False , A_=True ) -> Optional[Any]: if fake_data: __UpperCamelCase =[1] * 784 __UpperCamelCase =[1] + [0] * 9 if self.one_hot else 0 return ( [fake_image for _ in range(A_ )], [fake_label for _ in range(A_ )], ) __UpperCamelCase =self._index_in_epoch # Shuffle for the first epoch if self._epochs_completed == 0 and start == 0 and shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perma] __UpperCamelCase =self.labels[perma] # Go to the next epoch if start + batch_size > self._num_examples: # Finished epoch self._epochs_completed += 1 # Get the rest examples in this epoch __UpperCamelCase =self._num_examples - start __UpperCamelCase =self._images[start : self._num_examples] __UpperCamelCase =self._labels[start : self._num_examples] # Shuffle the data if shuffle: __UpperCamelCase =numpy.arange(self._num_examples ) numpy.random.shuffle(A_ ) __UpperCamelCase =self.images[perm] __UpperCamelCase =self.labels[perm] # Start next epoch __UpperCamelCase =0 __UpperCamelCase =batch_size - rest_num_examples __UpperCamelCase =self._index_in_epoch __UpperCamelCase =self._images[start:end] __UpperCamelCase =self._labels[start:end] return ( numpy.concatenate((images_rest_part, images_new_part) , axis=0 ), numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ), ) else: self._index_in_epoch += batch_size __UpperCamelCase =self._index_in_epoch return self._images[start:end], self._labels[start:end] @deprecated(SCREAMING_SNAKE_CASE__ , 'Please write your own downloading logic.' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str ): if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): gfile.MakeDirs(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =os.path.join(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if not gfile.Exists(SCREAMING_SNAKE_CASE__ ): urllib.request.urlretrieve(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # noqa: S310 with gfile.GFile(SCREAMING_SNAKE_CASE__ ) as f: __UpperCamelCase =f.size() print('Successfully downloaded' , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , 'bytes.' ) return filepath @deprecated( SCREAMING_SNAKE_CASE__ , 'Please use alternatives such as:' ' tensorflow_datasets.load(\'mnist\')' ) def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : int=False , SCREAMING_SNAKE_CASE__ : str=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=dtypes.floataa , SCREAMING_SNAKE_CASE__ : Optional[int]=True , SCREAMING_SNAKE_CASE__ : str=50_00 , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : str=DEFAULT_SOURCE_URL , ): if fake_data: def fake(): return _DataSet( [] , [] , fake_data=SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =fake() __UpperCamelCase =fake() __UpperCamelCase =fake() return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ ) if not source_url: # empty string check __UpperCamelCase =DEFAULT_SOURCE_URL __UpperCamelCase ='train-images-idx3-ubyte.gz' __UpperCamelCase ='train-labels-idx1-ubyte.gz' __UpperCamelCase ='t10k-images-idx3-ubyte.gz' __UpperCamelCase ='t10k-labels-idx1-ubyte.gz' __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + train_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_images_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_images(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_maybe_download( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , source_url + test_labels_file ) with gfile.Open(SCREAMING_SNAKE_CASE__ , 'rb' ) as f: __UpperCamelCase =_extract_labels(SCREAMING_SNAKE_CASE__ , one_hot=SCREAMING_SNAKE_CASE__ ) if not 0 <= validation_size <= len(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =( 'Validation size should be between 0 and ' F'{len(SCREAMING_SNAKE_CASE__ )}. Received: {validation_size}.' ) raise ValueError(SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =train_images[:validation_size] __UpperCamelCase =train_labels[:validation_size] __UpperCamelCase =train_images[validation_size:] __UpperCamelCase =train_labels[validation_size:] __UpperCamelCase ={'dtype': dtype, 'reshape': reshape, 'seed': seed} __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) __UpperCamelCase =_DataSet(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return _Datasets(train=SCREAMING_SNAKE_CASE__ , validation=SCREAMING_SNAKE_CASE__ , test=SCREAMING_SNAKE_CASE__ )
62
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ : int = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : Dict ) -> Tuple: if version.parse(scb.__version__ ) < version.parse('''1.4.12''' ): raise ImportWarning( '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n''' '''You can install it with `pip install "sacrebleu>=1.4.12"`.''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf'''] , reference_urls=[ '''https://github.com/m-popovic/chrF''', ] , ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int = CHRF.CHAR_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.WORD_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.BETA , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Optional[Any]: __lowerCamelCase = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) __lowerCamelCase = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase = CHRF(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sb_chrf.corpus_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
270
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple import torch from torch import nn from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel from transformers.utils import ModelOutput @dataclass class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =None __a =None __a =None __a =None class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" def __init__( self : Tuple , __a : Tuple=1 , __a : List[Any]=0 , __a : Any=2 , __a : Any=5_12 , __a : Optional[Any]="cls" , __a : List[Any]=False , __a : Tuple=True , **__a : Tuple , ): super().__init__(pad_token_id=__a , bos_token_id=__a , eos_token_id=__a , **__a ) _a = project_dim _a = pooler_fn _a = learn_encoder _a = use_attention_mask class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =[r'pooler', r'logit_scale'] __a =[r'position_ids', r'predictions.decoder.bias'] __a ='roberta' __a =RobertaSeriesConfig def __init__( self : Optional[int] , __a : List[Any] ): super().__init__(__a ) _a = XLMRobertaModel(__a ) _a = nn.Linear(config.hidden_size , config.project_dim ) _a = getattr(__a , "has_pre_transformation" , __a ) if self.has_pre_transformation: _a = nn.Linear(config.hidden_size , config.project_dim ) _a = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps ) self.post_init() def UpperCamelCase__ ( self : Any , __a : Optional[torch.Tensor] = None , __a : Optional[torch.Tensor] = None , __a : Optional[torch.Tensor] = None , __a : Optional[torch.Tensor] = None , __a : Optional[torch.Tensor] = None , __a : Optional[torch.Tensor] = None , __a : Optional[torch.Tensor] = None , __a : Optional[torch.Tensor] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , ): _a = return_dict if return_dict is not None else self.config.use_return_dict _a = self.base_model( input_ids=__a , attention_mask=__a , token_type_ids=__a , position_ids=__a , head_mask=__a , inputs_embeds=__a , encoder_hidden_states=__a , encoder_attention_mask=__a , output_attentions=__a , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=__a , ) if self.has_pre_transformation: _a = outputs["hidden_states"][-2] _a = self.pre_LN(__a ) _a = self.transformation_pre(__a ) return TransformationModelOutput( projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , ) else: _a = self.transformation(outputs.last_hidden_state ) return TransformationModelOutput( projection_state=__a , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
63
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
270
0
"""simple docstring""" # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ = { '''configuration_xmod''': [ '''XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XmodConfig''', '''XmodOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ = [ '''XMOD_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XmodForCausalLM''', '''XmodForMaskedLM''', '''XmodForMultipleChoice''', '''XmodForQuestionAnswering''', '''XmodForSequenceClassification''', '''XmodForTokenClassification''', '''XmodModel''', '''XmodPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xmod import ( XMOD_PRETRAINED_MODEL_ARCHIVE_LIST, XmodForCausalLM, XmodForMaskedLM, XmodForMultipleChoice, XmodForQuestionAnswering, XmodForSequenceClassification, XmodForTokenClassification, XmodModel, XmodPreTrainedModel, ) else: import sys A_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
64
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : str = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Tuple=18 , SCREAMING_SNAKE_CASE__ : int=30 , SCREAMING_SNAKE_CASE__ : Any=4_00 , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , ) -> Union[str, Any]: __lowerCamelCase = size if size is not None else {'''height''': 20, '''width''': 20} __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = num_channels __lowerCamelCase = image_size __lowerCamelCase = min_resolution __lowerCamelCase = max_resolution __lowerCamelCase = size __lowerCamelCase = do_normalize __lowerCamelCase = do_convert_rgb __lowerCamelCase = [5_12, 10_24, 20_48, 40_96] __lowerCamelCase = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def __A ( self : Union[str, Any] ) -> Union[str, Any]: return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __A ( self : int ) -> Any: __lowerCamelCase = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' __lowerCamelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Dict = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Optional[Any] ) -> List[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self ) @property def __A ( self : Optional[int] ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> Dict: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : int ) -> str: __lowerCamelCase = self.image_processor_tester.prepare_dummy_image() __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) __lowerCamelCase = 20_48 __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __A ( self : Union[str, Any] ) -> Dict: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Dict ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 __lowerCamelCase = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches __lowerCamelCase = '''Hello''' __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : List[str] ) -> Any: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Tuple ) -> List[str]: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Any = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self , num_channels=4 ) __lowerCamelCase = 3 @property def __A ( self : List[Any] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : Optional[int] ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
270
0
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () UpperCamelCase__ = np.linspace(start=0, stop=7_5, num=7_5, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). UpperCamelCase__ = [0, 2_5, 5_0] UpperCamelCase__ = [2_5, 5_0, 7_5] UpperCamelCase__ = fuzz.membership.trimf(X, abca) UpperCamelCase__ = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. UpperCamelCase__ = np.ones(7_5) UpperCamelCase__ = np.zeros((7_5,)) # 1. Union = max(µA(x), µB(x)) UpperCamelCase__ = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) UpperCamelCase__ = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) UpperCamelCase__ = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) UpperCamelCase__ = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] UpperCamelCase__ = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) UpperCamelCase__ = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] UpperCamelCase__ = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] UpperCamelCase__ = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('Young') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('Middle aged') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('union') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('intersection') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('complement_a') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('difference a/b') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('alg_sum') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('alg_product') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('bdd_sum') plt.grid(True) plt.subplot(4, 3, 1_0) plt.plot(X, bdd_difference) plt.title('bdd_difference') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
65
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class lowerCAmelCase__ ( __lowercase ): def __init__( self : int ) -> Optional[int]: __lowerCamelCase = [] def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: self.events.append('''on_init_end''' ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: self.events.append('''on_train_begin''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Any: self.events.append('''on_train_end''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: self.events.append('''on_epoch_begin''' ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: self.events.append('''on_epoch_end''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.events.append('''on_step_begin''' ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: self.events.append('''on_step_end''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: self.events.append('''on_evaluate''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : str ) -> str: self.events.append('''on_predict''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: self.events.append('''on_save''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: self.events.append('''on_log''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: self.events.append('''on_prediction_step''' ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = tempfile.mkdtemp() def __A ( self : int ) -> List[str]: shutil.rmtree(self.output_dir ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Any=0 , SCREAMING_SNAKE_CASE__ : List[str]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[int]=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionModelConfig(a=SCREAMING_SNAKE_CASE__ , b=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionPreTrainedModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = TrainingArguments(self.output_dir , disable_tqdm=SCREAMING_SNAKE_CASE__ , report_to=[] , **SCREAMING_SNAKE_CASE__ ) return Trainer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , callbacks=SCREAMING_SNAKE_CASE__ , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) # Order doesn't matter __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) for cba, cba in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , cba.__class__ ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(cba.__class__ , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: __lowerCamelCase = ['''on_init_end''', '''on_train_begin'''] __lowerCamelCase = 0 __lowerCamelCase = len(trainer.get_eval_dataloader() ) __lowerCamelCase = ['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append('''on_epoch_begin''' ) for _ in range(SCREAMING_SNAKE_CASE__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('''on_log''' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('''on_save''' ) expected_events.append('''on_epoch_end''' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = self.get_trainer() __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # Callbacks passed at init are added to the default callbacks __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback __lowerCamelCase = self.get_trainer(disable_tqdm=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> str: __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] __lowerCamelCase = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(cb.__class__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # We can also add, pop, or remove by instance __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> Any: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='''ignore''' , category=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # Independent log/save/eval __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='''steps''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='''epoch''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # A bit of everything __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy='''steps''' , ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # warning should be emitted for duplicated callbacks with patch('''transformers.trainer_callback.logger.warning''' ) as warn_mock: __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(SCREAMING_SNAKE_CASE__ ) in warn_mock.call_args[0][0]
270
0
"""simple docstring""" from __future__ import annotations import copy import inspect import json import math import os import tempfile import unittest from importlib import import_module import numpy as np from transformers import ViTMAEConfig from transformers.file_utils import cached_property, is_tf_available, is_vision_available from transformers.testing_utils import require_tf, require_vision, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFViTMAEForPreTraining, TFViTMAEModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowerCamelCase : '''simple docstring''' def __init__( self: List[Any] , snake_case: Optional[int] , snake_case: Optional[int]=13 , snake_case: str=30 , snake_case: Dict=2 , snake_case: Tuple=3 , snake_case: Optional[Any]=True , snake_case: Optional[Any]=True , snake_case: str=32 , snake_case: List[str]=2 , snake_case: Union[str, Any]=4 , snake_case: Union[str, Any]=37 , snake_case: Union[str, Any]="gelu" , snake_case: Optional[int]=0.1 , snake_case: str=0.1 , snake_case: Dict=10 , snake_case: Union[str, Any]=0.0_2 , snake_case: Union[str, Any]=3 , snake_case: int=0.6 , snake_case: List[Any]=None , ) -> List[str]: snake_case_ :Optional[int] = parent snake_case_ :Dict = batch_size snake_case_ :Union[str, Any] = image_size snake_case_ :Tuple = patch_size snake_case_ :Union[str, Any] = num_channels snake_case_ :Optional[Any] = is_training snake_case_ :Optional[Any] = use_labels snake_case_ :List[str] = hidden_size snake_case_ :Tuple = num_hidden_layers snake_case_ :Optional[int] = num_attention_heads snake_case_ :Optional[int] = intermediate_size snake_case_ :str = hidden_act snake_case_ :Dict = hidden_dropout_prob snake_case_ :Union[str, Any] = attention_probs_dropout_prob snake_case_ :Any = type_sequence_label_size snake_case_ :Any = initializer_range snake_case_ :Any = mask_ratio snake_case_ :int = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) snake_case_ :Optional[Any] = (image_size // patch_size) ** 2 snake_case_ :Optional[int] = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def lowerCAmelCase_ ( self: Optional[Any] ) -> List[Any]: snake_case_ :Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case_ :Tuple = None if self.use_labels: snake_case_ :List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) snake_case_ :Optional[Any] = self.get_config() return config, pixel_values, labels def lowerCAmelCase_ ( self: str ) -> Tuple: return ViTMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , decoder_hidden_size=self.hidden_size , decoder_num_hidden_layers=self.num_hidden_layers , decoder_num_attention_heads=self.num_attention_heads , decoder_intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=snake_case , initializer_range=self.initializer_range , mask_ratio=self.mask_ratio , ) def lowerCAmelCase_ ( self: Tuple , snake_case: Optional[int] , snake_case: List[str] , snake_case: List[str] ) -> Optional[Any]: snake_case_ :str = TFViTMAEModel(config=snake_case ) snake_case_ :Any = model(snake_case , training=snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCAmelCase_ ( self: List[Any] , snake_case: Union[str, Any] , snake_case: Optional[int] , snake_case: Optional[int] ) -> List[Any]: snake_case_ :str = TFViTMAEForPreTraining(snake_case ) snake_case_ :Union[str, Any] = model(snake_case , training=snake_case ) # expected sequence length = num_patches snake_case_ :Union[str, Any] = (self.image_size // self.patch_size) ** 2 snake_case_ :Any = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) # test greyscale images snake_case_ :List[Any] = 1 snake_case_ :List[str] = TFViTMAEForPreTraining(snake_case ) snake_case_ :int = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case_ :Union[str, Any] = model(snake_case , training=snake_case ) snake_case_ :str = self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_patches, expected_num_channels) ) def lowerCAmelCase_ ( self: Optional[int] ) -> Tuple: snake_case_ :Union[str, Any] = self.prepare_config_and_inputs() ((snake_case_), (snake_case_), (snake_case_)) :List[str] = config_and_inputs snake_case_ :List[str] = {"""pixel_values""": pixel_values} return config, inputs_dict @require_tf class lowerCamelCase ( _lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ): '''simple docstring''' _A : int = (TFViTMAEModel, TFViTMAEForPreTraining) if is_tf_available() else () _A : Optional[int] = {"""feature-extraction""": TFViTMAEModel} if is_tf_available() else {} _A : int = False _A : Any = False _A : List[str] = False _A : Optional[int] = False def lowerCAmelCase_ ( self: str ) -> Tuple: snake_case_ :str = TFViTMAEModelTester(self ) snake_case_ :str = ConfigTester(self , config_class=snake_case , has_text_modality=snake_case , hidden_size=37 ) def lowerCAmelCase_ ( self: Any ) -> str: self.config_tester.run_common_tests() @unittest.skip(reason="""ViTMAE does not use inputs_embeds""" ) def lowerCAmelCase_ ( self: Optional[int] ) -> str: pass def lowerCAmelCase_ ( self: List[Any] ) -> int: snake_case_, snake_case_ :List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ :Optional[int] = model_class(snake_case ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) snake_case_ :Dict = model.get_output_embeddings() self.assertTrue(x is None or isinstance(snake_case , tf.keras.layers.Layer ) ) def lowerCAmelCase_ ( self: Tuple ) -> str: snake_case_, snake_case_ :Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ :Dict = model_class(snake_case ) snake_case_ :Union[str, Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ :List[Any] = [*signature.parameters.keys()] snake_case_ :Any = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , snake_case ) def lowerCAmelCase_ ( self: Dict ) -> Tuple: snake_case_ :List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*snake_case ) def lowerCAmelCase_ ( self: Dict ) -> Optional[Any]: snake_case_ :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*snake_case ) def lowerCAmelCase_ ( self: int ) -> Any: # make the mask reproducible np.random.seed(2 ) snake_case_, snake_case_ :Tuple = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ :int = int((config.image_size // config.patch_size) ** 2 ) snake_case_ :List[str] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: snake_case_ :Optional[Any] = model_class(snake_case ) snake_case_ :Optional[int] = self._prepare_for_class(snake_case , snake_case ) snake_case_ :Union[str, Any] = model(snake_case , noise=snake_case ) snake_case_ :Union[str, Any] = copy.deepcopy(self._prepare_for_class(snake_case , snake_case ) ) snake_case_ :int = model(**snake_case , noise=snake_case ) snake_case_ :Any = outputs_dict[0].numpy() snake_case_ :Tuple = outputs_keywords[0].numpy() self.assertLess(np.sum(np.abs(output_dict - output_keywords ) ) , 1E-6 ) def lowerCAmelCase_ ( self: List[str] ) -> Union[str, Any]: # make the mask reproducible np.random.seed(2 ) snake_case_, snake_case_ :Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ :str = int((config.image_size // config.patch_size) ** 2 ) snake_case_ :Dict = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) def prepare_numpy_arrays(snake_case: str ): snake_case_ :List[Any] = {} for k, v in inputs_dict.items(): if tf.is_tensor(snake_case ): snake_case_ :Tuple = v.numpy() else: snake_case_ :Optional[Any] = np.array(snake_case ) return inputs_np_dict for model_class in self.all_model_classes: snake_case_ :str = model_class(snake_case ) snake_case_ :Dict = self._prepare_for_class(snake_case , snake_case ) snake_case_ :Any = prepare_numpy_arrays(snake_case ) snake_case_ :Any = model(snake_case , noise=snake_case ) snake_case_ :List[str] = model(**snake_case , noise=snake_case ) self.assert_outputs_same(snake_case , snake_case ) def lowerCAmelCase_ ( self: List[str] , snake_case: Optional[int] , snake_case: Optional[Any] , snake_case: Any ) -> Union[str, Any]: # make masks reproducible np.random.seed(2 ) snake_case_ :List[str] = int((tf_model.config.image_size // tf_model.config.patch_size) ** 2 ) snake_case_ :Any = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) snake_case_ :Optional[int] = tf.constant(snake_case ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument snake_case_ :Tuple = tf_noise super().check_pt_tf_models(snake_case , snake_case , snake_case ) def lowerCAmelCase_ ( self: str ) -> List[str]: # make mask reproducible np.random.seed(2 ) snake_case_, snake_case_ :List[str] = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ :Tuple = { module_member for model_class in self.all_model_classes for module in (import_module(model_class.__module__ ),) for module_member_name in dir(snake_case ) if module_member_name.endswith("""MainLayer""" ) # This condition is required, since `modeling_tf_clip.py` has 3 classes whose names end with `MainLayer`. and module_member_name[: -len("""MainLayer""" )] == model_class.__name__[: -len("""Model""" )] for module_member in (getattr(snake_case , snake_case ),) if isinstance(snake_case , snake_case ) and tf.keras.layers.Layer in module_member.__bases__ and getattr(snake_case , """_keras_serializable""" , snake_case ) } snake_case_ :str = int((config.image_size // config.patch_size) ** 2 ) snake_case_ :Dict = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) snake_case_ :int = tf.convert_to_tensor(snake_case ) inputs_dict.update({"""noise""": noise} ) for main_layer_class in tf_main_layer_classes: snake_case_ :List[str] = main_layer_class(snake_case ) snake_case_ :List[Any] = { name: tf.keras.Input(tensor.shape[1:] , dtype=tensor.dtype ) for name, tensor in inputs_dict.items() } snake_case_ :int = tf.keras.Model(snake_case , outputs=main_layer(snake_case ) ) snake_case_ :int = model(snake_case ) with tempfile.TemporaryDirectory() as tmpdirname: snake_case_ :List[Any] = os.path.join(snake_case , """keras_model.h5""" ) model.save(snake_case ) snake_case_ :List[str] = tf.keras.models.load_model( snake_case , custom_objects={main_layer_class.__name__: main_layer_class} ) assert isinstance(snake_case , tf.keras.Model ) snake_case_ :int = model(snake_case ) self.assert_outputs_same(snake_case , snake_case ) @slow def lowerCAmelCase_ ( self: Tuple ) -> Tuple: # make mask reproducible np.random.seed(2 ) snake_case_, snake_case_ :Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ :Tuple = int((config.image_size // config.patch_size) ** 2 ) snake_case_ :Optional[int] = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: snake_case_ :Optional[int] = model_class(snake_case ) snake_case_ :Any = self._prepare_for_class(snake_case , snake_case ) snake_case_ :Tuple = model(snake_case , noise=snake_case ) if model_class.__name__ == "TFViTMAEModel": snake_case_ :Any = outputs.last_hidden_state.numpy() snake_case_ :Dict = 0 else: snake_case_ :int = outputs.logits.numpy() snake_case_ :str = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(snake_case , saved_model=snake_case ) snake_case_ :int = model_class.from_pretrained(snake_case ) snake_case_ :Dict = model(snake_case , noise=snake_case ) if model_class.__name__ == "TFViTMAEModel": snake_case_ :Optional[Any] = after_outputs["""last_hidden_state"""].numpy() snake_case_ :Dict = 0 else: snake_case_ :Dict = after_outputs["""logits"""].numpy() snake_case_ :Union[str, Any] = 0 snake_case_ :Any = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(snake_case , 1E-5 ) def lowerCAmelCase_ ( self: List[str] ) -> List[str]: # make mask reproducible np.random.seed(2 ) snake_case_, snake_case_ :Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case_ :str = int((config.image_size // config.patch_size) ** 2 ) snake_case_ :Tuple = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) for model_class in self.all_model_classes: snake_case_ :Dict = model_class(snake_case ) snake_case_ :Dict = self._prepare_for_class(snake_case , snake_case ) snake_case_ :Union[str, Any] = model(snake_case , noise=snake_case ) snake_case_ :Optional[int] = model.get_config() # make sure that returned config is jsonifiable, which is required by keras json.dumps(snake_case ) snake_case_ :Optional[Any] = model_class.from_config(model.get_config() ) # make sure it also accepts a normal config snake_case_ :Optional[int] = model_class.from_config(model.config ) snake_case_ :Any = new_model(snake_case ) # Build model new_model.set_weights(model.get_weights() ) snake_case_ :Union[str, Any] = new_model(snake_case , noise=snake_case ) self.assert_outputs_same(snake_case , snake_case ) @unittest.skip( reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.""" ) def lowerCAmelCase_ ( self: Tuple ) -> str: pass @unittest.skip(reason="""ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load""" ) def lowerCAmelCase_ ( self: Optional[Any] ) -> Dict: pass @slow def lowerCAmelCase_ ( self: int ) -> Union[str, Any]: snake_case_ :Optional[Any] = TFViTMAEModel.from_pretrained("""google/vit-base-patch16-224""" ) self.assertIsNotNone(snake_case ) def A_ ( ): '''simple docstring''' snake_case_ :Optional[Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_tf @require_vision class lowerCamelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def lowerCAmelCase_ ( self: List[str] ) -> List[str]: return ViTImageProcessor.from_pretrained("""facebook/vit-mae-base""" ) if is_vision_available() else None @slow def lowerCAmelCase_ ( self: Optional[Any] ) -> Dict: # make random mask reproducible across the PT and TF model np.random.seed(2 ) snake_case_ :Any = TFViTMAEForPreTraining.from_pretrained("""facebook/vit-mae-base""" ) snake_case_ :str = self.default_image_processor snake_case_ :Optional[int] = prepare_img() snake_case_ :int = image_processor(images=snake_case , return_tensors="""tf""" ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) snake_case_ :Optional[Any] = ViTMAEConfig() snake_case_ :List[str] = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) snake_case_ :Union[str, Any] = np.random.uniform(size=(1, num_patches) ) # forward pass snake_case_ :Tuple = model(**snake_case , noise=snake_case ) # verify the logits snake_case_ :int = tf.convert_to_tensor([1, 196, 768] ) self.assertEqual(outputs.logits.shape , snake_case ) snake_case_ :Union[str, Any] = tf.convert_to_tensor( [[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]] ) tf.debugging.assert_near(outputs.logits[0, :3, :3] , snake_case , atol=1E-4 )
66
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowerCAmelCase__ : def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) __lowerCamelCase = img __lowerCamelCase = img.shape[1] __lowerCamelCase = img.shape[0] __lowerCamelCase = dst_width __lowerCamelCase = dst_height __lowerCamelCase = self.src_w / self.dst_w __lowerCamelCase = self.src_h / self.dst_h __lowerCamelCase = __lowerCamelCase = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def __A ( self : List[Any] ) -> str: for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase = self.img[self.get_y(SCREAMING_SNAKE_CASE__ )][self.get_x(SCREAMING_SNAKE_CASE__ )] def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_x * x ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_y * y ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = 800, 600 SCREAMING_SNAKE_CASE__ : int = imread("image_data/lena.jpg", 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
270
0
'''simple docstring''' import os __UpperCAmelCase ={"I": 1, "V": 5, "X": 1_0, "L": 5_0, "C": 1_0_0, "D": 5_0_0, "M": 1_0_0_0} def __lowerCAmelCase ( UpperCamelCase__ ) -> int: __lowerCamelCase = 0 __lowerCamelCase = 0 while index < len(UpperCamelCase__ ) - 1: __lowerCamelCase = SYMBOLS[numerals[index]] __lowerCamelCase = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def __lowerCAmelCase ( UpperCamelCase__ ) -> str: __lowerCamelCase = '''''' __lowerCamelCase = num // 10_00 numerals += m_count * "M" num %= 10_00 __lowerCamelCase = num // 1_00 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 %= 1_00 __lowerCamelCase = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def __lowerCAmelCase ( UpperCamelCase__ = "/p089_roman.txt" ) -> int: __lowerCamelCase = 0 with open(os.path.dirname(UpperCamelCase__ ) + roman_numerals_filename ) as filea: __lowerCamelCase = filea.readlines() for line in lines: __lowerCamelCase = line.strip() __lowerCamelCase = parse_roman_numerals(UpperCamelCase__ ) __lowerCamelCase = generate_roman_numerals(UpperCamelCase__ ) savings += len(UpperCamelCase__ ) - len(UpperCamelCase__ ) return savings if __name__ == "__main__": print(f'{solution() = }')
67
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( __lowerCAmelCase : dict , __lowerCAmelCase : str , __lowerCAmelCase : set , __lowerCAmelCase : set , __lowerCAmelCase : dict , __lowerCAmelCase : dict , __lowerCAmelCase : PriorityQueue , __lowerCAmelCase : dict , __lowerCAmelCase : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCamelCase = cst_fwd.get(__lowerCAmelCase , np.inf ) __lowerCamelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCamelCase = new_cost_f __lowerCamelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCamelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : dict , __lowerCAmelCase : dict ) -> int: __lowerCamelCase = -1 __lowerCamelCase = set() __lowerCamelCase = set() __lowerCamelCase = {source: 0} __lowerCamelCase = {destination: 0} __lowerCamelCase = {source: None} __lowerCamelCase = {destination: None} __lowerCamelCase = PriorityQueue() __lowerCamelCase = PriorityQueue() __lowerCamelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCamelCase , __lowerCamelCase = queue_forward.get() visited_forward.add(__lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = queue_backward.get() visited_backward.add(__lowerCAmelCase ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCamelCase = shortest_distance return shortest_path_distance SCREAMING_SNAKE_CASE__ : List[Any] = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } SCREAMING_SNAKE_CASE__ : Optional[int] = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
270
0
import json import os import shutil import tempfile import unittest from transformers import BatchEncoding, CanineTokenizer from transformers.testing_utils import require_tokenizers, require_torch from transformers.tokenization_utils import AddedToken from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin class a__ ( snake_case , unittest.TestCase ): """simple docstring""" __lowerCamelCase = CanineTokenizer __lowerCamelCase = False def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' super().setUp() A__ = CanineTokenizer() tokenizer.save_pretrained(self.tmpdirname ) @cached_property def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' return CanineTokenizer.from_pretrained("google/canine-s" ) def UpperCamelCase ( self , **lowercase ) -> CanineTokenizer: '''simple docstring''' A__ = self.tokenizer_class.from_pretrained(self.tmpdirname , **lowercase ) A__ = 1024 return tokenizer @require_torch def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' A__ = self.canine_tokenizer A__ = ["Life is like a box of chocolates.", "You never know what you're gonna get."] # fmt: off A__ = [57344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 57345, 0, 0, 0, 0] # fmt: on A__ = tokenizer(lowercase , padding=lowercase , return_tensors="pt" ) self.assertIsInstance(lowercase , lowercase ) A__ = list(batch.input_ids.numpy()[0] ) self.assertListEqual(lowercase , lowercase ) self.assertEqual((2, 39) , batch.input_ids.shape ) self.assertEqual((2, 39) , batch.attention_mask.shape ) @require_torch def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' A__ = self.canine_tokenizer A__ = ["Once there was a man.", "He wrote a test in HuggingFace Tranformers."] A__ = tokenizer(lowercase , padding=lowercase , return_tensors="pt" ) # check if input_ids, attention_mask and token_type_ids are returned self.assertIn("input_ids" , lowercase ) self.assertIn("attention_mask" , lowercase ) self.assertIn("token_type_ids" , lowercase ) @require_torch def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.canine_tokenizer A__ = [ "What's the weater?", "It's about 25 degrees.", ] A__ = tokenizer( text_target=lowercase , max_length=32 , padding="max_length" , truncation=lowercase , return_tensors="pt" ) self.assertEqual(32 , targets["input_ids"].shape[1] ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): self.assertNotEqual(tokenizer.model_max_length , 42 ) # Now let's start the test A__ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc A__ = tempfile.mkdtemp() A__ = " He is very happy, UNwant\u00E9d,running" A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) tokenizer.save_pretrained(lowercase ) A__ = tokenizer.__class__.from_pretrained(lowercase ) A__ = after_tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertListEqual(lowercase , lowercase ) shutil.rmtree(lowercase ) A__ = self.get_tokenizers(model_max_length=42 ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # Isolate this from the other tests because we save additional tokens/etc A__ = tempfile.mkdtemp() A__ = " He is very happy, UNwant\u00E9d,running" A__ = tokenizer.additional_special_tokens # We can add a new special token for Canine as follows: A__ = chr(0XE_0_0_7 ) additional_special_tokens.append(lowercase ) tokenizer.add_special_tokens({"additional_special_tokens": additional_special_tokens} ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) tokenizer.save_pretrained(lowercase ) A__ = tokenizer.__class__.from_pretrained(lowercase ) A__ = after_tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertListEqual(lowercase , lowercase ) self.assertIn(lowercase , after_tokenizer.additional_special_tokens ) self.assertEqual(after_tokenizer.model_max_length , 42 ) A__ = tokenizer.__class__.from_pretrained(lowercase , model_max_length=43 ) self.assertEqual(tokenizer.model_max_length , 43 ) shutil.rmtree(lowercase ) def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ , A__ = self.get_clean_sequence(lowercase ) # a special token for Canine can be defined as follows: A__ = 0XE_0_0_5 A__ = chr(lowercase ) tokenizer.add_special_tokens({"cls_token": special_token} ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertEqual(len(lowercase ) , 1 ) A__ = tokenizer.decode(ids + encoded_special_token , clean_up_tokenization_spaces=lowercase ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) self.assertEqual(lowercase , input_encoded + special_token_id ) A__ = tokenizer.decode(lowercase , skip_special_tokens=lowercase ) self.assertTrue(special_token not in decoded ) def UpperCamelCase ( self ) -> List[Any]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ = chr(0XE_0_0_5 ) A__ = chr(0XE_0_0_6 ) # `add_tokens` method stores special tokens only in `tokenizer.unique_no_split_tokens`. (in tokenization_utils.py) tokenizer.add_tokens([SPECIAL_TOKEN_1] , special_tokens=lowercase ) # `add_special_tokens` method stores special tokens in `tokenizer.additional_special_tokens`, # which also occur in `tokenizer.all_special_tokens`. (in tokenization_utils_base.py) tokenizer.add_special_tokens({"additional_special_tokens": [SPECIAL_TOKEN_2]} ) A__ = tokenizer.tokenize(lowercase ) A__ = tokenizer.tokenize(lowercase ) self.assertEqual(len(lowercase ) , 1 ) self.assertEqual(len(lowercase ) , 1 ) self.assertEqual(token_a[0] , lowercase ) self.assertEqual(token_a[0] , lowercase ) @require_tokenizers def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): # a special token for Canine can be defined as follows: A__ = 0XE_0_0_6 A__ = chr(lowercase ) A__ = AddedToken(lowercase , lstrip=lowercase ) tokenizer.add_special_tokens({"additional_special_tokens": [new_token]} ) with tempfile.TemporaryDirectory() as tmp_dir_name: tokenizer.save_pretrained(lowercase ) tokenizer.from_pretrained(lowercase ) def UpperCamelCase ( self ) -> int: '''simple docstring''' A__ = [] if self.test_slow_tokenizer: tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()) ) if self.test_rust_tokenizer: tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()) ) for tokenizer_class, tokenizer_utils in tokenizer_list: with tempfile.TemporaryDirectory() as tmp_dir: tokenizer_utils.save_pretrained(lowercase ) with open(os.path.join(lowercase , "special_tokens_map.json" ) , encoding="utf-8" ) as json_file: A__ = json.load(lowercase ) with open(os.path.join(lowercase , "tokenizer_config.json" ) , encoding="utf-8" ) as json_file: A__ = json.load(lowercase ) # a special token for Canine can be defined as follows: A__ = 0XE_0_0_6 A__ = chr(lowercase ) A__ = [new_token_a] A__ = [new_token_a] with open(os.path.join(lowercase , "special_tokens_map.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(lowercase , lowercase ) with open(os.path.join(lowercase , "tokenizer_config.json" ) , "w" , encoding="utf-8" ) as outfile: json.dump(lowercase , lowercase ) # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and # "special_tokens_map.json" files A__ = tokenizer_class.from_pretrained(lowercase , extra_ids=0 ) self.assertIn(lowercase , tokenizer_without_change_in_init.additional_special_tokens ) # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer_without_change_in_init.convert_ids_to_tokens( tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_a] ) ) , ) A__ = 0XE_0_0_7 A__ = chr(lowercase ) # Now we test that we can change the value of additional_special_tokens in the from_pretrained A__ = [AddedToken(lowercase , lstrip=lowercase )] A__ = tokenizer_class.from_pretrained( lowercase , additional_special_tokens=lowercase , extra_ids=0 ) self.assertIn(lowercase , tokenizer.additional_special_tokens ) # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab self.assertEqual( [new_token_a] , tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_a] ) ) ) @require_tokenizers def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' A__ = self.get_tokenizers(do_lower_case=lowercase ) for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ = "hello world" if self.space_between_special_tokens: A__ = "[CLS] hello world [SEP]" else: A__ = input A__ = tokenizer.encode(lowercase , add_special_tokens=lowercase ) A__ = tokenizer.decode(lowercase , spaces_between_special_tokens=self.space_between_special_tokens ) self.assertIn(lowercase , [output, output.lower()] ) def UpperCamelCase ( self ) -> Dict: '''simple docstring''' A__ = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F'{tokenizer.__class__.__name__}' ): A__ = [ "bos_token", "eos_token", "unk_token", "sep_token", "pad_token", "cls_token", "mask_token", ] A__ = "a" A__ = ord(lowercase ) for attr in attributes_list: setattr(lowercase , attr + "_id" , lowercase ) self.assertEqual(getattr(lowercase , lowercase ) , lowercase ) self.assertEqual(getattr(lowercase , attr + "_id" ) , lowercase ) setattr(lowercase , attr + "_id" , lowercase ) self.assertEqual(getattr(lowercase , lowercase ) , lowercase ) self.assertEqual(getattr(lowercase , attr + "_id" ) , lowercase ) setattr(lowercase , "additional_special_tokens_ids" , [] ) self.assertListEqual(getattr(lowercase , "additional_special_tokens" ) , [] ) self.assertListEqual(getattr(lowercase , "additional_special_tokens_ids" ) , [] ) A__ = 0XE_0_0_6 A__ = chr(lowercase ) setattr(lowercase , "additional_special_tokens_ids" , [additional_special_token_id] ) self.assertListEqual(getattr(lowercase , "additional_special_tokens" ) , [additional_special_token] ) self.assertListEqual(getattr(lowercase , "additional_special_tokens_ids" ) , [additional_special_token_id] ) def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' pass def UpperCamelCase ( self ) -> Optional[int]: '''simple docstring''' pass def UpperCamelCase ( self ) -> Tuple: '''simple docstring''' pass def UpperCamelCase ( self ) -> Union[str, Any]: '''simple docstring''' pass def UpperCamelCase ( self ) -> List[str]: '''simple docstring''' pass def UpperCamelCase ( self ) -> Any: '''simple docstring''' pass def UpperCamelCase ( self ) -> Optional[Any]: '''simple docstring''' pass
68
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : List[Any] = TypeVar("T") def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (position - 1) // 2 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 1 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 2 class lowerCAmelCase__ ( Generic[T] ): def __init__( self : List[str] ) -> None: __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 def __len__( self : Optional[int] ) -> int: return self.elements def __repr__( self : Optional[int] ) -> str: return str(self.heap ) def __A ( self : Union[str, Any] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def __A ( self : str , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __lowerCamelCase = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __lowerCamelCase , __lowerCamelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowerCamelCase , __lowerCamelCase = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Update the weight of the given key __lowerCamelCase = self.position_map[elem] __lowerCamelCase = (elem, weight) if position > 0: __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __lowerCamelCase = self.position_map[elem] if curr_pos == 0: return None __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __lowerCamelCase = self.position_map[elem] __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: # Swap the nodes at the given positions __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase , __lowerCamelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowerCamelCase = nodea_pos __lowerCamelCase = nodea_pos class lowerCAmelCase__ ( Generic[T] ): def __init__( self : Tuple ) -> None: __lowerCamelCase = {} __lowerCamelCase = 0 def __repr__( self : Optional[int] ) -> str: return str(self.connections ) def __len__( self : List[str] ) -> int: return self.nodes def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __lowerCamelCase = {} self.nodes += 1 def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = weight __lowerCamelCase = weight def __magic_name__ ( __lowerCAmelCase : GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: __lowerCamelCase = {node: maxsize for node in graph.connections} __lowerCamelCase = {node: None for node in graph.connections} __lowerCamelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__lowerCAmelCase , __lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization __lowerCamelCase = priority_queue.extract_min() __lowerCamelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node # running prim's algorithm while not priority_queue.is_empty(): __lowerCamelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node return dist, parent
270
0
"""simple docstring""" from __future__ import annotations class UpperCamelCase : def __init__( self, lowerCAmelCase__, lowerCAmelCase__) -> str: snake_case_ , snake_case_ = text, pattern snake_case_ , snake_case_ = len(lowerCAmelCase__), len(lowerCAmelCase__) def a_ ( self, lowerCAmelCase__) -> int: for i in range(self.patLen - 1, -1, -1): if char == self.pattern[i]: return i return -1 def a_ ( self, lowerCAmelCase__) -> int: for i in range(self.patLen - 1, -1, -1): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def a_ ( self) -> list[int]: # searches pattern in text and returns index positions snake_case_ = [] for i in range(self.textLen - self.patLen + 1): snake_case_ = self.mismatch_in_text(lowerCAmelCase__) if mismatch_index == -1: positions.append(lowerCAmelCase__) else: snake_case_ = self.match_in_pattern(self.text[mismatch_index]) snake_case_ = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions __UpperCamelCase = '''ABAABA''' __UpperCamelCase = '''AB''' __UpperCamelCase = BoyerMooreSearch(text, pattern) __UpperCamelCase = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
69
from __future__ import annotations from statistics import mean def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> list[int]: __lowerCamelCase = [0] * no_of_processes __lowerCamelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] __lowerCamelCase = [] __lowerCamelCase = 0 __lowerCamelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCamelCase = [] __lowerCamelCase = -1 for i in range(__lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: __lowerCamelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCamelCase = i total_time += burst_time[target_process] completed += 1 __lowerCamelCase = 0 __lowerCamelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : int , __lowerCAmelCase : list[int] ) -> list[int]: __lowerCamelCase = [0] * no_of_processes for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") SCREAMING_SNAKE_CASE__ : Tuple = 4 SCREAMING_SNAKE_CASE__ : Optional[int] = [2, 5, 3, 7] SCREAMING_SNAKE_CASE__ : List[str] = [0, 0, 0, 0] SCREAMING_SNAKE_CASE__ : str = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( F'{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t' F'{waiting_time[i]}\t\t\t\t{turn_around_time[i]}' ) print(F'\nAverage waiting time = {mean(waiting_time):.5f}') print(F'Average turnaround time = {mean(turn_around_time):.5f}')
270
0
'''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 A__ : Dict =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(42) A__ : Optional[int] ={'''base''': '''patrickvonplaten/wav2vec2_tiny_random''', '''robust''': '''patrickvonplaten/wav2vec2_tiny_random_robust'''} A__ : List[str] ='''zero2''' A__ : List[Any] ='''zero3''' A__ : str =[ZEROa, ZEROa] def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase = 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 A__ : Any =list(itertools.product(stages, models.keys())) @slow @require_deepspeed @require_torch_gpu class UpperCAmelCase ( snake_case_ ): @parameterized.expand(__snake_case , name_func=__snake_case ) def lowercase__ ( self : List[str] , __snake_case : Tuple , __snake_case : Optional[int] ) -> List[str]: self.run_and_check( stage=__snake_case , model=__snake_case , distributed=__snake_case , fpaa=__snake_case , ) @require_torch_multi_gpu @parameterized.expand(__snake_case , name_func=__snake_case ) def lowercase__ ( self : List[Any] , __snake_case : Union[str, Any] , __snake_case : int ) -> int: self.run_and_check( stage=__snake_case , model=__snake_case , distributed=__snake_case , fpaa=__snake_case , ) @parameterized.expand(__snake_case , name_func=__snake_case ) def lowercase__ ( self : Any , __snake_case : Optional[int] , __snake_case : Dict ) -> Tuple: self.run_and_check( stage=__snake_case , model=__snake_case , distributed=__snake_case , fpaa=__snake_case , ) @require_torch_multi_gpu @parameterized.expand(__snake_case , name_func=__snake_case ) def lowercase__ ( self : Tuple , __snake_case : Optional[int] , __snake_case : Dict ) -> Union[str, Any]: self.run_and_check( stage=__snake_case , model=__snake_case , distributed=__snake_case , fpaa=__snake_case , ) def lowercase__ ( self : Optional[Any] , __snake_case : Union[str, Any] ) -> Union[str, Any]: # XXX: run_asr is premature and doesn't save any results # so all we check for now is that the process didn't fail pass def lowercase__ ( self : Dict , __snake_case : str , __snake_case : str , __snake_case : int = 10 , __snake_case : bool = True , __snake_case : bool = True , __snake_case : bool = True , ) -> Optional[int]: _lowerCAmelCase = models[model] _lowerCAmelCase = self.run_trainer( stage=__snake_case , model_name=__snake_case , eval_steps=__snake_case , num_train_epochs=1 , distributed=__snake_case , fpaa=__snake_case , ) self.do_checks(__snake_case ) return output_dir def lowercase__ ( self : Optional[int] , __snake_case : str , __snake_case : str , __snake_case : int = 10 , __snake_case : int = 1 , __snake_case : bool = True , __snake_case : bool = True , ) -> Optional[Any]: _lowerCAmelCase = self.get_auto_remove_tmp_dir("""./xxx""" , after=__snake_case ) _lowerCAmelCase = 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(__snake_case )}\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 _lowerCAmelCase = f"--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json".split() _lowerCAmelCase = [f"{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"] _lowerCAmelCase = self.get_launcher(__snake_case ) _lowerCAmelCase = launcher + script + args + ds_args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(__snake_case , env=self.get_env() ) return output_dir def lowercase__ ( self : Tuple , __snake_case : List[Any]=False ) -> List[Any]: # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup # - it won't be able to handle that # 2. for now testing with just 2 gpus max (since some quality tests may give different # results with mode gpus because we use very little data) _lowerCAmelCase = min(2 , get_gpu_count() ) if distributed else 1 return f"deepspeed --num_nodes 1 --num_gpus {num_gpus}".split()
70
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( __lowercase ): @staticmethod @abstractmethod def __A ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> str: raise NotImplementedError() @abstractmethod def __A ( self : Optional[int] ) -> Union[str, Any]: raise NotImplementedError()
270
0
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class __A ( a , a , a , unittest.TestCase ): """simple docstring""" UpperCamelCase__ : Dict =StableUnCLIPImgaImgPipeline UpperCamelCase__ : Optional[int] =TEXT_GUIDED_IMAGE_VARIATION_PARAMS UpperCamelCase__ : int =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase__ : Tuple =frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess UpperCamelCase__ : Optional[Any] =frozenset([] ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[int] =32 __UpperCamelCase : Optional[int] =embedder_hidden_size # image encoding components __UpperCamelCase : Optional[int] =CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) __UpperCamelCase : List[str] =CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=lowerCamelCase__ , projection_dim=lowerCamelCase__ , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) __UpperCamelCase : Any =StableUnCLIPImageNormalizer(embedding_dim=lowerCamelCase__ ) __UpperCamelCase : Any =DDPMScheduler(beta_schedule='squaredcos_cap_v2' ) torch.manual_seed(0 ) __UpperCamelCase : Optional[Any] =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) __UpperCamelCase : Union[str, Any] =CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=lowerCamelCase__ , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) __UpperCamelCase : int =UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=lowerCamelCase__ , layers_per_block=1 , upcast_attention=lowerCamelCase__ , use_linear_projection=lowerCamelCase__ , ) torch.manual_seed(0 ) __UpperCamelCase : int =DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.00_085 , beta_end=0.012 , prediction_type='v_prediction' , set_alpha_to_one=lowerCamelCase__ , steps_offset=1 , ) torch.manual_seed(0 ) __UpperCamelCase : int =AutoencoderKL() __UpperCamelCase : int ={ # image encoding components 'feature_extractor': feature_extractor, 'image_encoder': image_encoder.eval(), # image noising components 'image_normalizer': image_normalizer.eval(), 'image_noising_scheduler': image_noising_scheduler, # regular denoising components 'tokenizer': tokenizer, 'text_encoder': text_encoder.eval(), 'unet': unet.eval(), 'scheduler': scheduler, 'vae': vae.eval(), } return components def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__=0 , lowerCamelCase__=True ): """simple docstring""" if str(lowerCamelCase__ ).startswith('mps' ): __UpperCamelCase : Union[str, Any] =torch.manual_seed(lowerCamelCase__ ) else: __UpperCamelCase : Optional[Any] =torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) __UpperCamelCase : int =floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) if pil_image: __UpperCamelCase : Union[str, Any] =input_image * 0.5 + 0.5 __UpperCamelCase : List[Any] =input_image.clamp(0 , 1 ) __UpperCamelCase : Optional[int] =input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __UpperCamelCase : Dict =DiffusionPipeline.numpy_to_pil(lowerCamelCase__ )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[int] ='cpu' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase : List[str] =self.get_dummy_components() __UpperCamelCase : Union[str, Any] =StableUnCLIPImgaImgPipeline(**lowerCamelCase__ ) __UpperCamelCase : Tuple =sd_pipe.to(lowerCamelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __UpperCamelCase : Tuple =self.get_dummy_inputs(lowerCamelCase__ ) inputs.update({'image_embeds': None} ) __UpperCamelCase : Optional[int] =sd_pipe(**lowerCamelCase__ ).images __UpperCamelCase : int =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCamelCase : Union[str, Any] =np.array([0.3_872, 0.7_224, 0.5_601, 0.4_741, 0.6_872, 0.5_814, 0.4_636, 0.3_867, 0.5_078] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[Any] =torch_device in ['cpu', 'mps'] self._test_attention_slicing_forward_pass(test_max_difference=lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Tuple =torch_device in ['cpu', 'mps'] self._test_inference_batch_single_identical(test_max_difference=lowerCamelCase__ ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def __lowercase ( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_max_difference=lowerCamelCase__ ) @slow @require_torch_gpu class __A ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Union[str, Any] =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) __UpperCamelCase : List[str] =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy' ) __UpperCamelCase : str =StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-l-img2img' , torch_dtype=torch.floataa ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __UpperCamelCase : Optional[Any] =torch.Generator(device='cpu' ).manual_seed(0 ) __UpperCamelCase : Union[str, Any] =pipe(lowerCamelCase__ , 'anime turle' , generator=lowerCamelCase__ , output_type='np' ) __UpperCamelCase : Union[str, Any] =output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowerCamelCase__ , lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Union[str, Any] =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) __UpperCamelCase : int =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy' ) __UpperCamelCase : Union[str, Any] =StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __UpperCamelCase : int =torch.Generator(device='cpu' ).manual_seed(0 ) __UpperCamelCase : Union[str, Any] =pipe(lowerCamelCase__ , 'anime turle' , generator=lowerCamelCase__ , output_type='np' ) __UpperCamelCase : Dict =output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowerCamelCase__ , lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[int] =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __UpperCamelCase : int =StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) __UpperCamelCase : Dict =pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __UpperCamelCase : Tuple =pipe( lowerCamelCase__ , 'anime turtle' , num_inference_steps=2 , output_type='np' , ) __UpperCamelCase : List[Any] =torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
71
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue_model_parallelism.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> List[Any]: if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=SCREAMING_SNAKE_CASE__ , ) assert hasattr(self , '''env''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: # configuration for running training on smdistributed Model Parallel __lowerCamelCase = { '''enabled''': True, '''processes_per_host''': 8, } __lowerCamelCase = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __lowerCamelCase = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __lowerCamelCase = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=SCREAMING_SNAKE_CASE__ , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE__ , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 5_00, } , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE__ , py_version='''py36''' , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: TrainingJobAnalytics(SCREAMING_SNAKE_CASE__ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: # create estimator __lowerCamelCase = self.create_estimator(SCREAMING_SNAKE_CASE__ ) # run training estimator.fit() # result dataframe __lowerCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # 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} , SCREAMING_SNAKE_CASE__ )
270
0
"""simple docstring""" import unittest from transformers import XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_LIST class __snake_case : def __init__( self : int , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : str=1_3 , __lowerCAmelCase : Any=7 , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : Optional[int]=True , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : Any=True , __lowerCAmelCase : int=True , __lowerCAmelCase : Optional[int]=False , __lowerCAmelCase : Any=False , __lowerCAmelCase : Optional[int]=False , __lowerCAmelCase : List[str]=2 , __lowerCAmelCase : List[Any]=9_9 , __lowerCAmelCase : str=0 , __lowerCAmelCase : Any=3_2 , __lowerCAmelCase : List[Any]=5 , __lowerCAmelCase : Dict=4 , __lowerCAmelCase : Optional[int]=0.1 , __lowerCAmelCase : Any=0.1 , __lowerCAmelCase : List[str]=5_1_2 , __lowerCAmelCase : List[Any]=2 , __lowerCAmelCase : Optional[int]=0.02 , __lowerCAmelCase : Union[str, Any]=2 , __lowerCAmelCase : Any=4 , __lowerCAmelCase : List[Any]="last" , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : List[Any]=None , __lowerCAmelCase : str=0 , ): """simple docstring""" _lowerCamelCase : Optional[Any] = parent _lowerCamelCase : Any = batch_size _lowerCamelCase : Any = seq_length _lowerCamelCase : Tuple = is_training _lowerCamelCase : Tuple = use_input_lengths _lowerCamelCase : Optional[int] = use_token_type_ids _lowerCamelCase : Dict = use_labels _lowerCamelCase : Optional[Any] = gelu_activation _lowerCamelCase : List[Any] = sinusoidal_embeddings _lowerCamelCase : List[Any] = causal _lowerCamelCase : Any = asm _lowerCamelCase : int = n_langs _lowerCamelCase : Tuple = vocab_size _lowerCamelCase : str = n_special _lowerCamelCase : List[Any] = hidden_size _lowerCamelCase : List[str] = num_hidden_layers _lowerCamelCase : int = num_attention_heads _lowerCamelCase : int = hidden_dropout_prob _lowerCamelCase : List[str] = attention_probs_dropout_prob _lowerCamelCase : Dict = max_position_embeddings _lowerCamelCase : Tuple = type_sequence_label_size _lowerCamelCase : Any = initializer_range _lowerCamelCase : Optional[Any] = num_labels _lowerCamelCase : Dict = num_choices _lowerCamelCase : Tuple = summary_type _lowerCamelCase : List[Any] = use_proj _lowerCamelCase : Tuple = scope _lowerCamelCase : Union[str, Any] = bos_token_id def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : Any = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _lowerCamelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCamelCase : Dict = None if self.use_input_lengths: _lowerCamelCase : Tuple = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length _lowerCamelCase : Any = None if self.use_token_type_ids: _lowerCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) _lowerCamelCase : Union[str, Any] = None _lowerCamelCase : List[Any] = None _lowerCamelCase : Optional[int] = None if self.use_labels: _lowerCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _lowerCamelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _lowerCamelCase : Any = ids_tensor([self.batch_size] , 2 ).float() _lowerCamelCase : str = ids_tensor([self.batch_size] , self.num_choices ) _lowerCamelCase : Dict = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" return XLMConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , num_labels=self.num_labels , bos_token_id=self.bos_token_id , ) def SCREAMING_SNAKE_CASE ( self : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Dict , __lowerCAmelCase : Any , __lowerCAmelCase : int , __lowerCAmelCase : str , ): """simple docstring""" _lowerCamelCase : List[Any] = XLMModel(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[Any] = model(__lowerCAmelCase , lengths=__lowerCAmelCase , langs=__lowerCAmelCase ) _lowerCamelCase : List[Any] = model(__lowerCAmelCase , langs=__lowerCAmelCase ) _lowerCamelCase : List[Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[str] , __lowerCAmelCase : str , ): """simple docstring""" _lowerCamelCase : str = XLMWithLMHeadModel(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : List[str] = model(__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , ): """simple docstring""" _lowerCamelCase : Any = XLMForQuestionAnsweringSimple(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : List[str] = model(__lowerCAmelCase ) _lowerCamelCase : Optional[Any] = model(__lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase ) _lowerCamelCase : List[str] = outputs self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Any , ): """simple docstring""" _lowerCamelCase : Optional[Any] = XLMForQuestionAnswering(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Optional[Any] = model(__lowerCAmelCase ) _lowerCamelCase : Dict = model( __lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase , cls_index=__lowerCAmelCase , is_impossible=__lowerCAmelCase , p_mask=__lowerCAmelCase , ) _lowerCamelCase : Dict = model( __lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase , cls_index=__lowerCAmelCase , is_impossible=__lowerCAmelCase , ) ((_lowerCamelCase) , ) : List[str] = result_with_labels.to_tuple() _lowerCamelCase : str = model(__lowerCAmelCase , start_positions=__lowerCAmelCase , end_positions=__lowerCAmelCase ) ((_lowerCamelCase) , ) : Optional[int] = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape , () ) self.parent.assertEqual(result.start_top_log_probs.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual(result.start_top_index.shape , (self.batch_size, model.config.start_n_top) ) self.parent.assertEqual( result.end_top_log_probs.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape , (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape , (self.batch_size,) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Dict , __lowerCAmelCase : int , __lowerCAmelCase : str , __lowerCAmelCase : List[str] , __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , ): """simple docstring""" _lowerCamelCase : List[str] = XLMForSequenceClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Dict = model(__lowerCAmelCase ) _lowerCamelCase : str = model(__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Dict , ): """simple docstring""" _lowerCamelCase : str = self.num_labels _lowerCamelCase : int = XLMForTokenClassification(__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : str = model(__lowerCAmelCase , attention_mask=__lowerCAmelCase , labels=__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Any , ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.num_choices _lowerCamelCase : List[str] = XLMForMultipleChoice(config=__lowerCAmelCase ) model.to(__lowerCAmelCase ) model.eval() _lowerCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : List[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Dict = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _lowerCamelCase : Tuple = model( __lowerCAmelCase , attention_mask=__lowerCAmelCase , token_type_ids=__lowerCAmelCase , labels=__lowerCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ( _lowerCamelCase ) , ) : Optional[Any] = config_and_inputs _lowerCamelCase : Any = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''lengths''': input_lengths} return config, inputs_dict @require_torch class __snake_case ( _lowercase , _lowercase , _lowercase , unittest.TestCase): snake_case__ : Dict = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) snake_case__ : Tuple = ( (XLMWithLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable snake_case__ : Tuple = ( { "feature-extraction": XLMModel, "fill-mask": XLMWithLMHeadModel, "question-answering": XLMForQuestionAnsweringSimple, "text-classification": XLMForSequenceClassification, "text-generation": XLMWithLMHeadModel, "token-classification": XLMForTokenClassification, "zero-shot": XLMForSequenceClassification, } if is_torch_available() else {} ) def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : int , __lowerCAmelCase : Tuple , __lowerCAmelCase : int , __lowerCAmelCase : int ): """simple docstring""" if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('''Fast''' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : str=False ): """simple docstring""" _lowerCamelCase : int = super()._prepare_for_class(__lowerCAmelCase , __lowerCAmelCase , return_labels=__lowerCAmelCase ) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": _lowerCamelCase : Dict = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCAmelCase ) _lowerCamelCase : Any = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowerCAmelCase ) return inputs_dict def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): """simple docstring""" _lowerCamelCase : List[Any] = XLMModelTester(self ) _lowerCamelCase : List[Any] = ConfigTester(self , config_class=__lowerCAmelCase , emb_dim=3_7 ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): """simple docstring""" _lowerCamelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : List[str] ): """simple docstring""" _lowerCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Any ): """simple docstring""" _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*__lowerCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : Tuple=1 ): """simple docstring""" self.assertIsInstance(__lowerCAmelCase , __lowerCAmelCase ) self.assertListEqual( [isinstance(__lowerCAmelCase , __lowerCAmelCase ) for iter_attentions in attentions] , [True] * len(__lowerCAmelCase ) ) self.assertEqual(len(__lowerCAmelCase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_attentions in enumerate(__lowerCAmelCase ): # adds PAD dummy token _lowerCamelCase : Optional[Any] = min_length + idx + 1 _lowerCamelCase : Optional[Any] = min_length + idx + 1 _lowerCamelCase : Dict = ( batch_size * num_beam_groups, config.num_attention_heads, tgt_len, src_len, ) # check attn size self.assertListEqual( [layer_attention.shape for layer_attention in iter_attentions] , [expected_shape] * len(__lowerCAmelCase ) ) def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : int , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : str=False , __lowerCAmelCase : Tuple=1 ): """simple docstring""" self.assertIsInstance(__lowerCAmelCase , __lowerCAmelCase ) self.assertListEqual( [isinstance(__lowerCAmelCase , __lowerCAmelCase ) for iter_hidden_states in hidden_states] , [True] * len(__lowerCAmelCase ) , ) self.assertEqual(len(__lowerCAmelCase ) , (max_length - min_length) * num_beam_groups ) for idx, iter_hidden_states in enumerate(__lowerCAmelCase ): # adds PAD dummy token _lowerCamelCase : str = min_length + idx + 1 _lowerCamelCase : int = (batch_size * num_beam_groups, seq_len, config.hidden_size) # check hidden size self.assertListEqual( [layer_hidden_states.shape for layer_hidden_states in iter_hidden_states] , [expected_shape] * len(__lowerCAmelCase ) , ) pass @slow def SCREAMING_SNAKE_CASE ( self : int ): """simple docstring""" for model_name in XLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowerCamelCase : Dict = XLMModel.from_pretrained(__lowerCAmelCase ) self.assertIsNotNone(__lowerCAmelCase ) @require_torch class __snake_case ( unittest.TestCase): @slow def SCREAMING_SNAKE_CASE ( self : Dict ): """simple docstring""" _lowerCamelCase : Any = XLMWithLMHeadModel.from_pretrained('''xlm-mlm-en-2048''' ) model.to(__lowerCAmelCase ) _lowerCamelCase : Tuple = torch.tensor([[1_4, 4_4_7]] , dtype=torch.long , device=__lowerCAmelCase ) # the president _lowerCamelCase : List[Any] = [ 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, 1_4, 4_4_7, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference _lowerCamelCase : List[Any] = model.generate(__lowerCAmelCase , do_sample=__lowerCAmelCase ) self.assertListEqual(output_ids[0].cpu().numpy().tolist() , __lowerCAmelCase )
72
from __future__ import annotations from fractions import Fraction def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def __magic_name__ ( __lowerCAmelCase : int ) -> list[str]: __lowerCamelCase = [] __lowerCamelCase = 11 __lowerCamelCase = int('''1''' + '''0''' * digit_len ) for num in range(__lowerCAmelCase , __lowerCAmelCase ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(__lowerCAmelCase , __lowerCAmelCase ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 __lowerCamelCase = 10 return solutions def __magic_name__ ( __lowerCAmelCase : int = 2 ) -> int: __lowerCamelCase = 1.0 for fraction in fraction_list(__lowerCAmelCase ): __lowerCamelCase = Fraction(__lowerCAmelCase ) result *= frac.denominator / frac.numerator return int(__lowerCAmelCase ) if __name__ == "__main__": print(solution())
270
0
import itertools from dataclasses import dataclass from typing import List, Optional import pyarrow as pa import pyarrow.parquet as pq import datasets from datasets.table import table_cast a =datasets.utils.logging.get_logger(__name__) @dataclass class A_ ( datasets.BuilderConfig ): _UpperCAmelCase : int = 10_000 _UpperCAmelCase : Optional[List[str]] = None _UpperCAmelCase : Optional[datasets.Features] = None class A_ ( datasets.ArrowBasedBuilder ): _UpperCAmelCase : int = ParquetConfig def lowerCAmelCase ( self : List[str]): return datasets.DatasetInfo(features=self.config.features) def lowerCAmelCase ( self : Dict ,SCREAMING_SNAKE_CASE__ : Dict): if not self.config.data_files: raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}") __lowerCamelCase : Dict = dl_manager.download_and_extract(self.config.data_files) if isinstance(SCREAMING_SNAKE_CASE__ ,(str, list, tuple)): __lowerCamelCase : List[str] = data_files if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : List[str] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __lowerCamelCase : Optional[Any] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE__) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,gen_kwargs={'files': files})] __lowerCamelCase : Optional[Any] = [] for split_name, files in data_files.items(): if isinstance(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__): __lowerCamelCase : Union[str, Any] = [files] # Use `dl_manager.iter_files` to skip hidden files in an extracted archive __lowerCamelCase : Union[str, Any] = [dl_manager.iter_files(SCREAMING_SNAKE_CASE__) for file in files] # Infer features is they are stoed in the arrow schema if self.info.features is None: for file in itertools.chain.from_iterable(SCREAMING_SNAKE_CASE__): with open(SCREAMING_SNAKE_CASE__ ,'rb') as f: __lowerCamelCase : int = datasets.Features.from_arrow_schema(pq.read_schema(SCREAMING_SNAKE_CASE__)) break splits.append(datasets.SplitGenerator(name=SCREAMING_SNAKE_CASE__ ,gen_kwargs={'files': files})) return splits def lowerCAmelCase ( self : List[str] ,SCREAMING_SNAKE_CASE__ : pa.Table): if self.info.features is not None: # more expensive cast to support nested features with keys in a different order # allows str <-> int/float or str to Audio for example __lowerCamelCase : Optional[int] = table_cast(SCREAMING_SNAKE_CASE__ ,self.info.features.arrow_schema) return pa_table def lowerCAmelCase ( self : List[Any] ,SCREAMING_SNAKE_CASE__ : Optional[int]): __lowerCamelCase : Union[str, Any] = self.info.features.arrow_schema if self.info.features is not None else None if self.info.features is not None and self.config.columns is not None: if sorted(field.name for field in schema) != sorted(self.config.columns): raise ValueError( F"Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'") for file_idx, file in enumerate(itertools.chain.from_iterable(SCREAMING_SNAKE_CASE__)): with open(SCREAMING_SNAKE_CASE__ ,'rb') as f: __lowerCamelCase : Tuple = pq.ParquetFile(SCREAMING_SNAKE_CASE__) try: for batch_idx, record_batch in enumerate( parquet_file.iter_batches(batch_size=self.config.batch_size ,columns=self.config.columns)): __lowerCamelCase : Tuple = pa.Table.from_batches([record_batch]) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield F"{file_idx}_{batch_idx}", self._cast_table(SCREAMING_SNAKE_CASE__) except ValueError as e: logger.error(F"Failed to read file '{file}' with error {type(SCREAMING_SNAKE_CASE__)}: {e}") raise
73
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipTextConfig", "BlipVisionConfig", ], "processing_blip": ["BlipProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = ["BlipImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipModel", "BlipPreTrainedModel", "BlipForConditionalGeneration", "BlipForQuestionAnswering", "BlipVisionModel", "BlipTextModel", "BlipForImageTextRetrieval", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBlipModel", "TFBlipPreTrainedModel", "TFBlipForConditionalGeneration", "TFBlipForQuestionAnswering", "TFBlipVisionModel", "TFBlipTextModel", "TFBlipForImageTextRetrieval", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
"""simple docstring""" from ..utils import DummyObject, requires_backends class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: int = ['''torch'''] def __init__( self : Union[str, Any] ,*A_ : Tuple ,**A_ : Optional[int] ) -> Any: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : Optional[int] ,**A_ : Tuple ) -> Optional[int]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : List[Any] ,**A_ : Dict ) -> int: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''torch'''] def __init__( self : Optional[int] ,*A_ : Optional[Any] ,**A_ : Union[str, Any] ) -> Optional[int]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : List[Any] ,**A_ : List[str] ) -> List[str]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,*A_ : Union[str, Any] ,**A_ : Dict ) -> List[Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''torch'''] def __init__( self : Any ,*A_ : List[Any] ,**A_ : Dict ) -> Any: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : Dict ,**A_ : Tuple ) -> List[str]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int ,*A_ : str ,**A_ : List[str] ) -> List[Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''torch'''] def __init__( self : Any ,*A_ : Union[str, Any] ,**A_ : List[Any] ) -> Optional[Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : Union[str, Any] ,**A_ : Union[str, Any] ) -> List[Any]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int ,*A_ : List[str] ,**A_ : List[Any] ) -> Tuple: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = ['''torch'''] def __init__( self : Optional[int] ,*A_ : str ,**A_ : List[str] ) -> List[str]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : Optional[Any] ,**A_ : List[Any] ) -> List[Any]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : int ,**A_ : List[Any] ) -> Tuple: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''torch'''] def __init__( self : str ,*A_ : Optional[Any] ,**A_ : Optional[int] ) -> List[Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : List[str] ,**A_ : Optional[int] ) -> Optional[Any]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int ,*A_ : int ,**A_ : int ) -> str: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''torch'''] def __init__( self : List[str] ,*A_ : Union[str, Any] ,**A_ : Optional[int] ) -> int: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : List[Any] ,**A_ : str ) -> int: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : Union[str, Any] ,**A_ : Union[str, Any] ) -> Tuple: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = ['''torch'''] def __init__( self : List[Any] ,*A_ : int ,**A_ : int ) -> Optional[Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : int ,**A_ : Tuple ) -> List[str]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,*A_ : Optional[Any] ,**A_ : Tuple ) -> Optional[Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = ['''torch'''] def __init__( self : List[str] ,*A_ : int ,**A_ : str ) -> Union[str, Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : List[Any] ,**A_ : Optional[int] ) -> Any: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[Any] ,*A_ : Tuple ,**A_ : Any ) -> Any: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ['''torch'''] def __init__( self : Any ,*A_ : Optional[Any] ,**A_ : List[Any] ) -> Optional[Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : str ,**A_ : List[str] ) -> Dict: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : int ,**A_ : Any ) -> int: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''torch'''] def __init__( self : Tuple ,*A_ : Tuple ,**A_ : Tuple ) -> Any: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : Union[str, Any] ,**A_ : Tuple ) -> Tuple: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : Union[str, Any] ,**A_ : Dict ) -> str: requires_backends(cls ,['torch'] ) def _snake_case ( *snake_case__ : Any , **snake_case__ : Dict ): requires_backends(snake_case__ , ['torch'] ) def _snake_case ( *snake_case__ : Optional[int] , **snake_case__ : List[Any] ): requires_backends(snake_case__ , ['torch'] ) def _snake_case ( *snake_case__ : str , **snake_case__ : str ): requires_backends(snake_case__ , ['torch'] ) def _snake_case ( *snake_case__ : int , **snake_case__ : List[Any] ): requires_backends(snake_case__ , ['torch'] ) def _snake_case ( *snake_case__ : List[str] , **snake_case__ : Any ): requires_backends(snake_case__ , ['torch'] ) def _snake_case ( *snake_case__ : Any , **snake_case__ : Any ): requires_backends(snake_case__ , ['torch'] ) def _snake_case ( *snake_case__ : int , **snake_case__ : Tuple ): requires_backends(snake_case__ , ['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''torch'''] def __init__( self : Optional[Any] ,*A_ : Optional[int] ,**A_ : Dict ) -> Dict: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,*A_ : Any ,**A_ : List[Any] ) -> Any: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ,*A_ : Optional[int] ,**A_ : Union[str, Any] ) -> List[str]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ['''torch'''] def __init__( self : Tuple ,*A_ : List[str] ,**A_ : List[Any] ) -> Optional[Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,*A_ : Optional[int] ,**A_ : Union[str, Any] ) -> List[Any]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ,*A_ : Tuple ,**A_ : Union[str, Any] ) -> Tuple: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Dict = ['''torch'''] def __init__( self : str ,*A_ : Union[str, Any] ,**A_ : Any ) -> Tuple: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ,*A_ : Optional[Any] ,**A_ : List[Any] ) -> Any: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int ,*A_ : Optional[int] ,**A_ : List[Any] ) -> Union[str, Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: int = ['''torch'''] def __init__( self : Optional[Any] ,*A_ : Any ,**A_ : Any ) -> Tuple: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : List[str] ,**A_ : Dict ) -> Union[str, Any]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : List[str] ,**A_ : Optional[int] ) -> Dict: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''torch'''] def __init__( self : Optional[int] ,*A_ : Any ,**A_ : List[str] ) -> Union[str, Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int ,*A_ : Any ,**A_ : List[str] ) -> Dict: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int ,*A_ : int ,**A_ : Dict ) -> List[str]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''torch'''] def __init__( self : List[str] ,*A_ : Dict ,**A_ : Optional[int] ) -> Dict: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,*A_ : Dict ,**A_ : Any ) -> int: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : Optional[Any] ,**A_ : Tuple ) -> int: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: int = ['''torch'''] def __init__( self : List[str] ,*A_ : List[str] ,**A_ : int ) -> Any: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : Tuple ,**A_ : Optional[int] ) -> Any: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,*A_ : List[Any] ,**A_ : Any ) -> Any: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''torch'''] def __init__( self : Optional[Any] ,*A_ : str ,**A_ : Optional[int] ) -> Dict: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : List[str] ,**A_ : Optional[Any] ) -> Optional[Any]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,*A_ : List[str] ,**A_ : Tuple ) -> Union[str, Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: str = ['''torch'''] def __init__( self : str ,*A_ : Union[str, Any] ,**A_ : Dict ) -> Any: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : List[Any] ,**A_ : Any ) -> Optional[Any]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,*A_ : List[str] ,**A_ : Optional[Any] ) -> int: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''torch'''] def __init__( self : int ,*A_ : int ,**A_ : Union[str, Any] ) -> str: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : int ,**A_ : List[Any] ) -> Tuple: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : Union[str, Any] ,**A_ : Any ) -> Dict: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = ['''torch'''] def __init__( self : str ,*A_ : Optional[Any] ,**A_ : List[str] ) -> Any: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : Optional[Any] ,**A_ : str ) -> Any: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : int ,**A_ : Tuple ) -> Tuple: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: str = ['''torch'''] def __init__( self : List[Any] ,*A_ : List[str] ,**A_ : List[str] ) -> int: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : Dict ,**A_ : int ) -> List[str]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : Tuple ,**A_ : Optional[Any] ) -> Optional[Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: int = ['''torch'''] def __init__( self : Any ,*A_ : List[str] ,**A_ : Any ) -> Tuple: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[Any] ,*A_ : Tuple ,**A_ : List[Any] ) -> Dict: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : List[str] ,**A_ : Optional[Any] ) -> List[Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Dict = ['''torch'''] def __init__( self : Tuple ,*A_ : List[str] ,**A_ : Optional[Any] ) -> Union[str, Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : Any ,**A_ : Optional[int] ) -> List[Any]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : Dict ,**A_ : Optional[int] ) -> str: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''torch'''] def __init__( self : Any ,*A_ : Optional[int] ,**A_ : List[Any] ) -> str: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : List[Any] ,**A_ : List[str] ) -> Tuple: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ,*A_ : Union[str, Any] ,**A_ : Any ) -> Optional[int]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''torch'''] def __init__( self : List[Any] ,*A_ : Dict ,**A_ : Tuple ) -> Optional[int]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple ,*A_ : int ,**A_ : Tuple ) -> Tuple: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,*A_ : str ,**A_ : Dict ) -> str: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Tuple = ['''torch'''] def __init__( self : Tuple ,*A_ : Union[str, Any] ,**A_ : Optional[int] ) -> Any: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : Tuple ,**A_ : Union[str, Any] ) -> List[str]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : Union[str, Any] ,**A_ : Optional[int] ) -> List[str]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = ['''torch'''] def __init__( self : Union[str, Any] ,*A_ : Dict ,**A_ : str ) -> Union[str, Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,*A_ : Union[str, Any] ,**A_ : List[Any] ) -> Dict: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple ,*A_ : str ,**A_ : Optional[Any] ) -> int: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ['''torch'''] def __init__( self : List[Any] ,*A_ : Optional[Any] ,**A_ : str ) -> str: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,*A_ : List[str] ,**A_ : str ) -> int: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple ,*A_ : List[Any] ,**A_ : Tuple ) -> Dict: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''torch'''] def __init__( self : List[str] ,*A_ : int ,**A_ : Tuple ) -> List[str]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : Dict ,**A_ : List[Any] ) -> Union[str, Any]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple ,*A_ : Optional[Any] ,**A_ : List[Any] ) -> Dict: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''torch'''] def __init__( self : Union[str, Any] ,*A_ : Any ,**A_ : Dict ) -> List[Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : int ,**A_ : int ) -> str: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : str ,**A_ : List[str] ) -> Union[str, Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: int = ['''torch'''] def __init__( self : int ,*A_ : Any ,**A_ : Any ) -> int: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[Any] ,*A_ : List[Any] ,**A_ : Tuple ) -> List[str]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,*A_ : Tuple ,**A_ : str ) -> List[str]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Any = ['''torch'''] def __init__( self : Tuple ,*A_ : str ,**A_ : List[str] ) -> Any: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[Any] ,*A_ : Any ,**A_ : Any ) -> int: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[Any] ,*A_ : List[str] ,**A_ : Optional[Any] ) -> Any: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ['''torch'''] def __init__( self : List[Any] ,*A_ : str ,**A_ : Union[str, Any] ) -> Any: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : Dict ,**A_ : Dict ) -> Dict: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ,*A_ : List[Any] ,**A_ : str ) -> Tuple: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ['''torch'''] def __init__( self : Union[str, Any] ,*A_ : List[Any] ,**A_ : Optional[int] ) -> Optional[int]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ,*A_ : Tuple ,**A_ : Union[str, Any] ) -> Optional[int]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : Any ,**A_ : List[Any] ) -> Any: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = ['''torch'''] def __init__( self : str ,*A_ : Optional[Any] ,**A_ : Dict ) -> Union[str, Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : List[str] ,**A_ : List[str] ) -> int: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ,*A_ : List[str] ,**A_ : str ) -> List[str]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: str = ['''torch'''] def __init__( self : List[Any] ,*A_ : Dict ,**A_ : Any ) -> Dict: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ,*A_ : List[str] ,**A_ : List[Any] ) -> List[str]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Dict ,*A_ : Dict ,**A_ : Optional[int] ) -> Tuple: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: str = ['''torch'''] def __init__( self : Optional[int] ,*A_ : List[Any] ,**A_ : int ) -> Any: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : Union[str, Any] ,**A_ : Optional[Any] ) -> int: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[Any] ,*A_ : Union[str, Any] ,**A_ : Union[str, Any] ) -> List[str]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: int = ['''torch'''] def __init__( self : int ,*A_ : Optional[Any] ,**A_ : int ) -> Dict: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple ,*A_ : Any ,**A_ : str ) -> Dict: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,*A_ : Any ,**A_ : str ) -> Tuple: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Dict = ['''torch'''] def __init__( self : Optional[Any] ,*A_ : Tuple ,**A_ : Dict ) -> List[str]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : int ,*A_ : Tuple ,**A_ : List[Any] ) -> Any: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,*A_ : Optional[Any] ,**A_ : List[str] ) -> List[Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''torch'''] def __init__( self : List[str] ,*A_ : Dict ,**A_ : List[Any] ) -> Optional[Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : Optional[Any] ,**A_ : Optional[int] ) -> Union[str, Any]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : Union[str, Any] ,**A_ : Union[str, Any] ) -> Union[str, Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: int = ['''torch'''] def __init__( self : List[str] ,*A_ : Any ,**A_ : int ) -> int: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : Tuple ,**A_ : Tuple ) -> Optional[int]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,*A_ : List[Any] ,**A_ : str ) -> List[str]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Any = ['''torch'''] def __init__( self : Dict ,*A_ : Tuple ,**A_ : Tuple ) -> List[Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : int ,**A_ : Optional[Any] ) -> Tuple: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[Any] ,*A_ : str ,**A_ : List[Any] ) -> Tuple: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = ['''torch'''] def __init__( self : Tuple ,*A_ : Any ,**A_ : Tuple ) -> List[Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : List[Any] ,**A_ : Optional[Any] ) -> int: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : Dict ,**A_ : Dict ) -> Optional[Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[Any] = ['''torch'''] def __init__( self : Any ,*A_ : Dict ,**A_ : Dict ) -> Tuple: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : str ,*A_ : Optional[Any] ,**A_ : Union[str, Any] ) -> List[str]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any ,*A_ : Dict ,**A_ : Optional[int] ) -> Union[str, Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Optional[Any] = ['''torch'''] def __init__( self : List[Any] ,*A_ : Any ,**A_ : Union[str, Any] ) -> Tuple: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Tuple ,*A_ : List[Any] ,**A_ : str ) -> str: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : Optional[int] ,**A_ : Optional[Any] ) -> str: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Any = ['''torch'''] def __init__( self : Optional[int] ,*A_ : List[str] ,**A_ : int ) -> Optional[Any]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str] ,*A_ : Dict ,**A_ : List[Any] ) -> Any: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ,*A_ : Union[str, Any] ,**A_ : Any ) -> Tuple: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: Union[str, Any] = ['''torch'''] def __init__( self : str ,*A_ : Optional[Any] ,**A_ : Optional[Any] ) -> Optional[int]: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : Optional[int] ,**A_ : Optional[Any] ) -> Union[str, Any]: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Optional[int] ,*A_ : int ,**A_ : str ) -> Optional[Any]: requires_backends(cls ,['torch'] ) class lowerCAmelCase_ ( metaclass=_lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = ['''torch'''] def __init__( self : List[str] ,*A_ : Tuple ,**A_ : Tuple ) -> Any: requires_backends(self ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : Union[str, Any] ,*A_ : Optional[int] ,**A_ : int ) -> Any: requires_backends(cls ,['torch'] ) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[Any] ,*A_ : str ,**A_ : Union[str, Any] ) -> Optional[int]: requires_backends(cls ,['torch'] )
74
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
'''simple docstring''' import itertools import math def a_ ( __snake_case : int ) -> bool: """simple docstring""" 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(__snake_case ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def a_ ( ) -> List[str]: """simple docstring""" lowerCamelCase_ =2 while True: if is_prime(__snake_case ): yield num num += 1 def a_ ( __snake_case : int = 1_0001 ) -> int: """simple docstring""" return next(itertools.islice(prime_generator() , nth - 1 , __snake_case ) ) if __name__ == "__main__": print(F"""{solution() = }""")
75
import pprint import requests SCREAMING_SNAKE_CASE__ : str = "https://zenquotes.io/api" def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = random_quotes() pprint.pprint(response)
270
0
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =UnCLIPImageVariationPipeline lowerCamelCase__ =IMAGE_VARIATION_PARAMS - {'height', 'width', 'guidance_scale'} lowerCamelCase__ =IMAGE_VARIATION_BATCH_PARAMS lowerCamelCase__ =[ 'generator', 'return_dict', 'decoder_num_inference_steps', 'super_res_num_inference_steps', ] lowerCamelCase__ =False @property def __UpperCamelCase ( self : int ) -> List[Any]: """simple docstring""" return 32 @property def __UpperCamelCase ( self : Dict ) -> int: """simple docstring""" return 32 @property def __UpperCamelCase ( self : List[str] ) -> Dict: """simple docstring""" return self.time_input_dim @property def __UpperCamelCase ( self : Tuple ) -> Union[str, Any]: """simple docstring""" return self.time_input_dim * 4 @property def __UpperCamelCase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" return 100 @property def __UpperCamelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def __UpperCamelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = 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=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(a ) @property def __UpperCamelCase ( self : Optional[int] ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) return CLIPVisionModelWithProjection(a ) @property def __UpperCamelCase ( self : Optional[int] ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = { "clip_embeddings_dim": self.text_embedder_hidden_size, "time_embed_dim": self.time_embed_dim, "cross_attention_dim": self.cross_attention_dim, } SCREAMING_SNAKE_CASE : Dict = UnCLIPTextProjModel(**a ) return model @property def __UpperCamelCase ( self : int ) -> str: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : str = { "sample_size": 32, # RGB in channels "in_channels": 3, # Out channels is double in channels because predicts mean and variance "out_channels": 6, "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": "identity", } SCREAMING_SNAKE_CASE : int = UNetaDConditionModel(**a ) return model @property def __UpperCamelCase ( self : Tuple ) -> int: """simple docstring""" return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def __UpperCamelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def __UpperCamelCase ( self : Any ) -> Optional[Any]: """simple docstring""" torch.manual_seed(1 ) SCREAMING_SNAKE_CASE : Tuple = UNetaDModel(**self.dummy_super_res_kwargs ) return model def __UpperCamelCase ( self : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = self.dummy_decoder SCREAMING_SNAKE_CASE : List[str] = self.dummy_text_proj SCREAMING_SNAKE_CASE : int = self.dummy_text_encoder SCREAMING_SNAKE_CASE : int = self.dummy_tokenizer SCREAMING_SNAKE_CASE : str = self.dummy_super_res_first SCREAMING_SNAKE_CASE : List[Any] = self.dummy_super_res_last SCREAMING_SNAKE_CASE : str = UnCLIPScheduler( variance_type="learned_range" , prediction_type="epsilon" , num_train_timesteps=1000 , ) SCREAMING_SNAKE_CASE : str = UnCLIPScheduler( variance_type="fixed_small_log" , prediction_type="epsilon" , num_train_timesteps=1000 , ) SCREAMING_SNAKE_CASE : List[str] = CLIPImageProcessor(crop_size=32 , size=32 ) SCREAMING_SNAKE_CASE : Dict = self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def __UpperCamelCase ( self : Any , a : str , a : Union[str, Any]=0 , a : Tuple=True ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a ) ).to(a ) if str(a ).startswith("mps" ): SCREAMING_SNAKE_CASE : Tuple = torch.manual_seed(a ) else: SCREAMING_SNAKE_CASE : int = torch.Generator(device=a ).manual_seed(a ) if pil_image: SCREAMING_SNAKE_CASE : Dict = input_image * 0.5 + 0.5 SCREAMING_SNAKE_CASE : List[Any] = input_image.clamp(0 , 1 ) SCREAMING_SNAKE_CASE : Union[str, Any] = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() SCREAMING_SNAKE_CASE : Tuple = DiffusionPipeline.numpy_to_pil(a )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def __UpperCamelCase ( self : List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = "cpu" SCREAMING_SNAKE_CASE : Optional[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = self.pipeline_class(**a ) SCREAMING_SNAKE_CASE : int = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_inputs(a , pil_image=a ) SCREAMING_SNAKE_CASE : Dict = pipe(**a ) SCREAMING_SNAKE_CASE : Any = output.images SCREAMING_SNAKE_CASE : int = self.get_dummy_inputs(a , pil_image=a ) SCREAMING_SNAKE_CASE : int = pipe( **a , return_dict=a , )[0] SCREAMING_SNAKE_CASE : List[Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Union[str, Any] = np.array( [ 0.9997, 0.0002, 0.9997, 0.9997, 0.9969, 0.0023, 0.9997, 0.9969, 0.9970, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCamelCase ( self : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = "cpu" SCREAMING_SNAKE_CASE : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = self.pipeline_class(**a ) SCREAMING_SNAKE_CASE : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) SCREAMING_SNAKE_CASE : Any = self.get_dummy_inputs(a , pil_image=a ) SCREAMING_SNAKE_CASE : Optional[int] = pipe(**a ) SCREAMING_SNAKE_CASE : Optional[Any] = output.images SCREAMING_SNAKE_CASE : List[str] = self.get_dummy_inputs(a , pil_image=a ) SCREAMING_SNAKE_CASE : Dict = pipe( **a , return_dict=a , )[0] SCREAMING_SNAKE_CASE : List[str] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Any = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : int = np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCamelCase ( self : List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : int = "cpu" SCREAMING_SNAKE_CASE : List[Any] = self.get_dummy_components() SCREAMING_SNAKE_CASE : List[str] = self.pipeline_class(**a ) SCREAMING_SNAKE_CASE : Union[str, Any] = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_dummy_inputs(a , pil_image=a ) SCREAMING_SNAKE_CASE : str = [ pipeline_inputs["image"], pipeline_inputs["image"], ] SCREAMING_SNAKE_CASE : Dict = pipe(**a ) SCREAMING_SNAKE_CASE : Optional[int] = output.images SCREAMING_SNAKE_CASE : int = self.get_dummy_inputs(a , pil_image=a ) SCREAMING_SNAKE_CASE : str = [ tuple_pipeline_inputs["image"], tuple_pipeline_inputs["image"], ] SCREAMING_SNAKE_CASE : List[str] = pipe( **a , return_dict=a , )[0] SCREAMING_SNAKE_CASE : Optional[int] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Tuple = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) SCREAMING_SNAKE_CASE : List[Any] = np.array( [ 0.9997, 0.9989, 0.0008, 0.0021, 0.9960, 0.0018, 0.0014, 0.0002, 0.9933, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCamelCase ( self : List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = torch.device("cpu" ) class _UpperCamelCase : '''simple docstring''' lowerCamelCase__ =1 SCREAMING_SNAKE_CASE : str = self.get_dummy_components() SCREAMING_SNAKE_CASE : Optional[int] = self.pipeline_class(**a ) SCREAMING_SNAKE_CASE : str = pipe.to(a ) pipe.set_progress_bar_config(disable=a ) SCREAMING_SNAKE_CASE : str = torch.Generator(device=a ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Dict = pipe.decoder.dtype SCREAMING_SNAKE_CASE : List[str] = 1 SCREAMING_SNAKE_CASE : List[str] = ( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) SCREAMING_SNAKE_CASE : List[Any] = pipe.prepare_latents( a , dtype=a , device=a , generator=a , latents=a , scheduler=DummyScheduler() ) SCREAMING_SNAKE_CASE : List[str] = ( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) SCREAMING_SNAKE_CASE : int = pipe.prepare_latents( a , dtype=a , device=a , generator=a , latents=a , scheduler=DummyScheduler() ) SCREAMING_SNAKE_CASE : str = self.get_dummy_inputs(a , pil_image=a ) SCREAMING_SNAKE_CASE : Union[str, Any] = pipe( **a , decoder_latents=a , super_res_latents=a ).images SCREAMING_SNAKE_CASE : str = self.get_dummy_inputs(a , pil_image=a ) # Don't pass image, instead pass embedding SCREAMING_SNAKE_CASE : List[str] = pipeline_inputs.pop("image" ) SCREAMING_SNAKE_CASE : str = pipe.image_encoder(a ).image_embeds SCREAMING_SNAKE_CASE : Optional[Any] = pipe( **a , decoder_latents=a , super_res_latents=a , image_embeddings=a , ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1e-4 @skip_mps def __UpperCamelCase ( self : Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = torch_device == "cpu" # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor SCREAMING_SNAKE_CASE : List[Any] = 1e-2 self._test_attention_slicing_forward_pass( test_max_difference=a , expected_max_diff=a ) @skip_mps def __UpperCamelCase ( self : Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = torch_device == "cpu" SCREAMING_SNAKE_CASE : Optional[int] = True SCREAMING_SNAKE_CASE : List[Any] = [ "decoder_num_inference_steps", "super_res_num_inference_steps", ] self._test_inference_batch_single_identical( test_max_difference=a , relax_max_difference=a , additional_params_copy_to_batched_inputs=a , ) def __UpperCamelCase ( self : Union[str, Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = [ "decoder_num_inference_steps", "super_res_num_inference_steps", ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes SCREAMING_SNAKE_CASE : List[str] = [2, 3] self._test_inference_batch_consistent( batch_sizes=a , additional_params_copy_to_batched_inputs=a , ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=a ) @skip_mps def __UpperCamelCase ( self : Tuple ) -> Any: """simple docstring""" return super().test_dict_tuple_outputs_equivalent() @skip_mps def __UpperCamelCase ( self : List[str] ) -> Dict: """simple docstring""" return super().test_save_load_local() @skip_mps def __UpperCamelCase ( self : Tuple ) -> Dict: """simple docstring""" return super().test_save_load_optional_components() @slow @require_torch_gpu class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : List[Any] ) -> int: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self : List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png" ) SCREAMING_SNAKE_CASE : Optional[Any] = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/unclip/karlo_v1_alpha_cat_variation_fp16.npy" ) SCREAMING_SNAKE_CASE : str = UnCLIPImageVariationPipeline.from_pretrained( "kakaobrain/karlo-v1-alpha-image-variations" , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE : Tuple = pipeline.to(a ) pipeline.set_progress_bar_config(disable=a ) SCREAMING_SNAKE_CASE : Optional[int] = torch.Generator(device="cpu" ).manual_seed(0 ) SCREAMING_SNAKE_CASE : str = pipeline( a , generator=a , output_type="np" , ) SCREAMING_SNAKE_CASE : Union[str, Any] = output.images[0] assert image.shape == (256, 256, 3) assert_mean_pixel_difference(a , a , 15 )
76
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __magic_name__ ( __lowerCAmelCase : int ) -> int: __lowerCamelCase = prime_factors(__lowerCAmelCase ) if is_square_free(__lowerCAmelCase ): return -1 if len(__lowerCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
270
0
"""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 UpperCAmelCase_ ( unittest.TestCase): def _UpperCAmelCase ( self ) -> Union[str, Any]: lowercase__ : Dict = 0 def _UpperCAmelCase ( self ) -> Optional[int]: lowercase__ : Tuple = AutoImageProcessor.from_pretrained('openai/clip-vit-base-patch32' ) self.assertIsInstance(a , a ) def _UpperCAmelCase ( self ) -> Any: with tempfile.TemporaryDirectory() as tmpdirname: lowercase__ : str = Path(a ) / 'preprocessor_config.json' lowercase__ : str = Path(a ) / 'config.json' json.dump( {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'} , open(a , 'w' ) , ) json.dump({'model_type': 'clip'} , open(a , 'w' ) ) lowercase__ : Union[str, Any] = AutoImageProcessor.from_pretrained(a ) self.assertIsInstance(a , a ) def _UpperCAmelCase ( self ) -> List[str]: # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: lowercase__ : str = Path(a ) / 'preprocessor_config.json' lowercase__ : int = Path(a ) / 'config.json' json.dump( {'feature_extractor_type': 'CLIPFeatureExtractor', 'processor_class': 'CLIPProcessor'} , open(a , 'w' ) , ) json.dump({'model_type': 'clip'} , open(a , 'w' ) ) lowercase__ : List[str] = AutoImageProcessor.from_pretrained(a ) self.assertIsInstance(a , a ) def _UpperCAmelCase ( self ) -> Optional[Any]: with tempfile.TemporaryDirectory() as tmpdirname: lowercase__ : Dict = CLIPConfig() # Create a dummy config file with image_proceesor_type lowercase__ : Optional[int] = Path(a ) / 'preprocessor_config.json' lowercase__ : 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 lowercase__ : int = AutoImageProcessor.from_pretrained(a ).to_dict() config_dict.pop('image_processor_type' ) lowercase__ : Tuple = CLIPImageProcessor(**a ) # save in new folder model_config.save_pretrained(a ) config.save_pretrained(a ) lowercase__ : Union[str, Any] = AutoImageProcessor.from_pretrained(a ) # make sure private variable is not incorrectly saved lowercase__ : Optional[int] = json.loads(config.to_json_string() ) self.assertTrue('_processor_class' not in dict_as_saved ) self.assertIsInstance(a , a ) def _UpperCAmelCase ( self ) -> List[str]: with tempfile.TemporaryDirectory() as tmpdirname: lowercase__ : Dict = Path(a ) / 'preprocessor_config.json' json.dump( {'image_processor_type': 'CLIPImageProcessor', 'processor_class': 'CLIPProcessor'} , open(a , 'w' ) , ) lowercase__ : List[str] = AutoImageProcessor.from_pretrained(a ) self.assertIsInstance(a , a ) def _UpperCAmelCase ( self ) -> Union[str, Any]: with self.assertRaisesRegex( a , 'clip-base is not a local folder and is not a valid model identifier' ): lowercase__ : Any = AutoImageProcessor.from_pretrained('clip-base' ) def _UpperCAmelCase ( self ) -> List[Any]: with self.assertRaisesRegex( a , R'aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)' ): lowercase__ : Dict = AutoImageProcessor.from_pretrained(a , revision='aaaaaa' ) def _UpperCAmelCase ( self ) -> Union[str, Any]: with self.assertRaisesRegex( a , 'hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.' , ): lowercase__ : int = AutoImageProcessor.from_pretrained('hf-internal-testing/config-no-model' ) def _UpperCAmelCase ( self ) -> Optional[int]: # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(a ): lowercase__ : List[Any] = AutoImageProcessor.from_pretrained('hf-internal-testing/test_dynamic_image_processor' ) # If remote code is disabled, we can't load this config. with self.assertRaises(a ): lowercase__ : Optional[int] = AutoImageProcessor.from_pretrained( 'hf-internal-testing/test_dynamic_image_processor' , trust_remote_code=a ) lowercase__ : Union[str, Any] = 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 ) lowercase__ : str = AutoImageProcessor.from_pretrained(a , trust_remote_code=a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , 'NewImageProcessor' ) def _UpperCAmelCase ( self ) -> int: 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: lowercase__ : Optional[Any] = Path(a ) / 'preprocessor_config.json' lowercase__ : List[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' ) ) lowercase__ : Union[str, Any] = 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 ) lowercase__ : Optional[int] = 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 _UpperCAmelCase ( self ) -> Dict: class UpperCAmelCase_ ( _a): lowerCamelCase__ : Union[str, Any] = True try: AutoConfig.register('custom' , a ) AutoImageProcessor.register(a , a ) # If remote code is not set, the default is to use local lowercase__ : int = 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. lowercase__ : 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(image_processor.is_local ) # If remote is enabled, we load from the Hub lowercase__ : 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]
77
import argparse import collections import json import os import re import string import sys import numpy as np SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"\b(a|an|the)\b", re.UNICODE) SCREAMING_SNAKE_CASE__ : int = None def __magic_name__ ( ) -> str: __lowerCamelCase = argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.''' ) parser.add_argument('''data_file''' , metavar='''data.json''' , help='''Input data JSON file.''' ) parser.add_argument('''pred_file''' , metavar='''pred.json''' , help='''Model predictions.''' ) parser.add_argument( '''--out-file''' , '''-o''' , metavar='''eval.json''' , help='''Write accuracy metrics to file (default is stdout).''' ) parser.add_argument( '''--na-prob-file''' , '''-n''' , metavar='''na_prob.json''' , help='''Model estimates of probability of no answer.''' ) parser.add_argument( '''--na-prob-thresh''' , '''-t''' , type=__lowerCAmelCase , default=1.0 , help='''Predict "" if no-answer probability exceeds this (default = 1.0).''' , ) parser.add_argument( '''--out-image-dir''' , '''-p''' , metavar='''out_images''' , default=__lowerCAmelCase , help='''Save precision-recall curves to directory.''' ) parser.add_argument('''--verbose''' , '''-v''' , action='''store_true''' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = bool(qa['''answers''']['''text'''] ) return qid_to_has_ans def __magic_name__ ( __lowerCAmelCase : Dict ) -> Optional[Any]: def remove_articles(__lowerCAmelCase : Optional[int] ): return ARTICLES_REGEX.sub(''' ''' , __lowerCAmelCase ) def white_space_fix(__lowerCAmelCase : Optional[int] ): return " ".join(text.split() ) def remove_punc(__lowerCAmelCase : Union[str, Any] ): __lowerCamelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__lowerCAmelCase : Dict ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__lowerCAmelCase ) ) ) ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Optional[int]: if not s: return [] return normalize_answer(__lowerCAmelCase ).split() def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple ) -> int: return int(normalize_answer(__lowerCAmelCase ) == normalize_answer(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple ) -> str: __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = collections.Counter(__lowerCAmelCase ) & collections.Counter(__lowerCAmelCase ) __lowerCamelCase = sum(common.values() ) if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = (2 * precision * recall) / (precision + recall) return fa def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] ) -> Optional[Any]: __lowerCamelCase = {} __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = qa['''id'''] __lowerCamelCase = [t for t in qa['''answers''']['''text'''] if normalize_answer(__lowerCAmelCase )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __lowerCamelCase = [''''''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue __lowerCamelCase = preds[qid] # Take max over all gold answers __lowerCamelCase = max(compute_exact(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) __lowerCamelCase = max(compute_fa(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) return exact_scores, fa_scores def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ) -> List[str]: __lowerCamelCase = {} for qid, s in scores.items(): __lowerCamelCase = na_probs[qid] > na_prob_thresh if pred_na: __lowerCamelCase = float(not qid_to_has_ans[qid] ) else: __lowerCamelCase = s return new_scores def __magic_name__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=None ) -> Union[str, Any]: if not qid_list: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores.values() ) / total), ('''f1''', 100.0 * sum(fa_scores.values() ) / total), ('''total''', total), ] ) else: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('''f1''', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('''total''', total), ] ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ) -> int: for k in new_eval: __lowerCamelCase = new_eval[k] def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ) -> Optional[Any]: plt.step(__lowerCAmelCase , __lowerCAmelCase , color='''b''' , alpha=0.2 , where='''post''' ) plt.fill_between(__lowerCAmelCase , __lowerCAmelCase , step='''post''' , alpha=0.2 , color='''b''' ) plt.xlabel('''Recall''' ) plt.ylabel('''Precision''' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__lowerCAmelCase ) plt.savefig(__lowerCAmelCase ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Tuple=None ) -> int: __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) __lowerCamelCase = 0.0 __lowerCamelCase = 1.0 __lowerCamelCase = 0.0 __lowerCamelCase = [1.0] __lowerCamelCase = [0.0] __lowerCamelCase = 0.0 for i, qid in enumerate(__lowerCAmelCase ): if qid_to_has_ans[qid]: true_pos += scores[qid] __lowerCamelCase = true_pos / float(i + 1 ) __lowerCamelCase = true_pos / float(__lowerCAmelCase ) if i == len(__lowerCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__lowerCAmelCase ) recalls.append(__lowerCAmelCase ) if out_image: plot_pr_curve(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return {"ap": 100.0 * avg_prec} def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] ) -> List[Any]: if out_image_dir and not os.path.exists(__lowerCAmelCase ): os.makedirs(__lowerCAmelCase ) __lowerCamelCase = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_exact.png''' ) , title='''Precision-Recall curve for Exact Match score''' , ) __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_f1.png''' ) , title='''Precision-Recall curve for F1 score''' , ) __lowerCamelCase = {k: float(__lowerCAmelCase ) for k, v in qid_to_has_ans.items()} __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_oracle.png''' ) , title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)''' , ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_exact''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_f1''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_oracle''' ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> Optional[Any]: if not qid_list: return __lowerCamelCase = [na_probs[k] for k in qid_list] __lowerCamelCase = np.ones_like(__lowerCAmelCase ) / float(len(__lowerCAmelCase ) ) plt.hist(__lowerCAmelCase , weights=__lowerCAmelCase , bins=20 , range=(0.0, 1.0) ) plt.xlabel('''Model probability of no-answer''' ) plt.ylabel('''Proportion of dataset''' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__lowerCAmelCase , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ) -> Optional[int]: __lowerCamelCase = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __lowerCamelCase = num_no_ans __lowerCamelCase = cur_score __lowerCamelCase = 0.0 __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) for i, qid in enumerate(__lowerCAmelCase ): if qid not in scores: continue if qid_to_has_ans[qid]: __lowerCamelCase = scores[qid] else: if preds[qid]: __lowerCamelCase = -1 else: __lowerCamelCase = 0 cur_score += diff if cur_score > best_score: __lowerCamelCase = cur_score __lowerCamelCase = na_probs[qid] return 100.0 * best_score / len(__lowerCAmelCase ), best_thresh def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] ) -> int: __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = best_exact __lowerCamelCase = exact_thresh __lowerCamelCase = best_fa __lowerCamelCase = fa_thresh def __magic_name__ ( ) -> Optional[int]: with open(OPTS.data_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) __lowerCamelCase = dataset_json['''data'''] with open(OPTS.pred_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) else: __lowerCamelCase = {k: 0.0 for k in preds} __lowerCamelCase = make_qid_to_has_ans(__lowerCAmelCase ) # maps qid to True/False __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if v] __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if not v] __lowerCamelCase , __lowerCamelCase = get_raw_scores(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase ) if has_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''HasAns''' ) if no_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''NoAns''' ) if OPTS.na_prob_file: find_all_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''hasAns''' ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''noAns''' ) if OPTS.out_file: with open(OPTS.out_file , '''w''' ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) else: print(json.dumps(__lowerCAmelCase , indent=2 ) ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
270
0
"""simple docstring""" from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class A_ : """simple docstring""" def __init__( self :Optional[int] , lowercase_ :Optional[Any] , ) -> str: UpperCAmelCase = parent UpperCAmelCase = 13 UpperCAmelCase = 7 UpperCAmelCase = True UpperCAmelCase = True UpperCAmelCase = False UpperCAmelCase = True UpperCAmelCase = 99 UpperCAmelCase = 32 UpperCAmelCase = 2 UpperCAmelCase = 4 UpperCAmelCase = 37 UpperCAmelCase = 'gelu' UpperCAmelCase = 0.1 UpperCAmelCase = 0.1 UpperCAmelCase = 5_12 UpperCAmelCase = 16 UpperCAmelCase = 2 UpperCAmelCase = 0.02 UpperCAmelCase = 3 UpperCAmelCase = 4 UpperCAmelCase = None def UpperCAmelCase__ ( self :List[Any] ) -> int: UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase = None if self.use_input_mask: UpperCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase = None UpperCAmelCase = None UpperCAmelCase = None if self.use_labels: UpperCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self :Optional[int] , lowercase_ :Dict , lowercase_ :str , lowercase_ :List[str] , lowercase_ :str , lowercase_ :Optional[Any] , lowercase_ :Optional[int] ) -> List[str]: UpperCAmelCase = TFDistilBertModel(config=lowercase_ ) UpperCAmelCase = {'input_ids': input_ids, 'attention_mask': input_mask} UpperCAmelCase = model(lowercase_ ) UpperCAmelCase = [input_ids, input_mask] UpperCAmelCase = model(lowercase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self :Any , lowercase_ :Tuple , lowercase_ :Tuple , lowercase_ :Optional[Any] , lowercase_ :Any , lowercase_ :Tuple , lowercase_ :Dict ) -> Tuple: UpperCAmelCase = TFDistilBertForMaskedLM(config=lowercase_ ) UpperCAmelCase = {'input_ids': input_ids, 'attention_mask': input_mask} UpperCAmelCase = model(lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase__ ( self :Union[str, Any] , lowercase_ :Optional[int] , lowercase_ :Any , lowercase_ :Any , lowercase_ :Any , lowercase_ :str , lowercase_ :Tuple ) -> str: UpperCAmelCase = TFDistilBertForQuestionAnswering(config=lowercase_ ) UpperCAmelCase = { 'input_ids': input_ids, 'attention_mask': input_mask, } UpperCAmelCase = model(lowercase_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase__ ( self :Optional[Any] , lowercase_ :List[Any] , lowercase_ :Any , lowercase_ :Dict , lowercase_ :Union[str, Any] , lowercase_ :Optional[int] , lowercase_ :List[str] ) -> int: UpperCAmelCase = self.num_labels UpperCAmelCase = TFDistilBertForSequenceClassification(lowercase_ ) UpperCAmelCase = {'input_ids': input_ids, 'attention_mask': input_mask} UpperCAmelCase = model(lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase__ ( self :Any , lowercase_ :Dict , lowercase_ :List[str] , lowercase_ :Union[str, Any] , lowercase_ :Tuple , lowercase_ :Union[str, Any] , lowercase_ :Any ) -> Dict: UpperCAmelCase = self.num_choices UpperCAmelCase = TFDistilBertForMultipleChoice(lowercase_ ) UpperCAmelCase = tf.tile(tf.expand_dims(lowercase_ , 1 ) , (1, self.num_choices, 1) ) UpperCAmelCase = tf.tile(tf.expand_dims(lowercase_ , 1 ) , (1, self.num_choices, 1) ) UpperCAmelCase = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, } UpperCAmelCase = model(lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase__ ( self :Dict , lowercase_ :Optional[int] , lowercase_ :Dict , lowercase_ :str , lowercase_ :Optional[Any] , lowercase_ :Union[str, Any] , lowercase_ :Tuple ) -> Optional[Any]: UpperCAmelCase = self.num_labels UpperCAmelCase = TFDistilBertForTokenClassification(lowercase_ ) UpperCAmelCase = {'input_ids': input_ids, 'attention_mask': input_mask} UpperCAmelCase = model(lowercase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self :Union[str, Any] ) -> List[Any]: UpperCAmelCase = self.prepare_config_and_inputs() ((UpperCAmelCase) , (UpperCAmelCase) , (UpperCAmelCase) , (UpperCAmelCase) , (UpperCAmelCase) , (UpperCAmelCase)) = config_and_inputs UpperCAmelCase = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class A_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = ( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) __UpperCamelCase = ( { """feature-extraction""": TFDistilBertModel, """fill-mask""": TFDistilBertForMaskedLM, """question-answering""": TFDistilBertForQuestionAnswering, """text-classification""": TFDistilBertForSequenceClassification, """token-classification""": TFDistilBertForTokenClassification, """zero-shot""": TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def UpperCAmelCase__ ( self :str ) -> Any: UpperCAmelCase = TFDistilBertModelTester(self ) UpperCAmelCase = ConfigTester(self , config_class=lowercase_ , dim=37 ) def UpperCAmelCase__ ( self :str ) -> Optional[Any]: self.config_tester.run_common_tests() def UpperCAmelCase__ ( self :List[Any] ) -> str: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*lowercase_ ) def UpperCAmelCase__ ( self :Dict ) -> List[Any]: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*lowercase_ ) def UpperCAmelCase__ ( self :Optional[Any] ) -> Tuple: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*lowercase_ ) def UpperCAmelCase__ ( self :Optional[int] ) -> List[Any]: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*lowercase_ ) def UpperCAmelCase__ ( self :Optional[Any] ) -> Dict: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*lowercase_ ) def UpperCAmelCase__ ( self :int ) -> Dict: UpperCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*lowercase_ ) @slow def UpperCAmelCase__ ( self :Tuple ) -> int: for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): UpperCAmelCase = TFDistilBertModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) @require_tf class A_ ( unittest.TestCase ): """simple docstring""" @slow def UpperCAmelCase__ ( self :Optional[int] ) -> Optional[int]: UpperCAmelCase = TFDistilBertModel.from_pretrained('distilbert-base-uncased' ) UpperCAmelCase = tf.constant([[0, 1, 2, 3, 4, 5]] ) UpperCAmelCase = model(lowercase_ )[0] UpperCAmelCase = [1, 6, 7_68] self.assertEqual(output.shape , lowercase_ ) UpperCAmelCase = tf.constant( [ [ [0.1926_1885, -0.1373_2955, 0.411_9799], [0.2215_0156, -0.0742_2661, 0.3903_7204], [0.2275_6018, -0.089_6414, 0.370_1467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , lowercase_ , atol=1E-4 )
78
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F'{bindir}/../../examples/pytorch/translation'): from run_translation import main # noqa set_seed(42) SCREAMING_SNAKE_CASE__ : Any = "sshleifer/student_marian_en_ro_6_1" SCREAMING_SNAKE_CASE__ : Tuple = "sshleifer/tiny-mbart" @require_torch class lowerCAmelCase__ ( __lowercase ): def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , ) -> Optional[int]: __lowerCamelCase = self.run_trainer( eval_steps=1 , max_len=12 , model_name=SCREAMING_SNAKE_CASE__ , num_train_epochs=1 , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , predict_with_generate=SCREAMING_SNAKE_CASE__ , do_train=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history if not do_eval: return __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats __lowerCamelCase = eval_metrics[-1] assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) assert not math.isnan(float(last_step_stats['''eval_loss'''] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def __A ( self : Optional[int] ) -> int: self.run_seqaseq_quick() @require_torch_multi_gpu def __A ( self : int ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @require_torch_multi_gpu def __A ( self : Optional[Any] ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Optional[int] ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple --fp16''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Tuple ) -> Any: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick( distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2 --fp16''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @require_apex @require_torch_gpu def __A ( self : Union[str, Any] ) -> List[str]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) @parameterized.expand(['''base''', '''low''', '''high''', '''mixed'''] ) @require_torch_multi_gpu def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout __lowerCamelCase = { # test with the default log_level - should be info and thus log info once '''base''': {'''extra_args_str''': '''''', '''n_matches''': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes '''low''': {'''extra_args_str''': '''--log_level debug --log_level_replica debug''', '''n_matches''': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica '''high''': {'''extra_args_str''': '''--log_level error --log_level_replica debug''', '''n_matches''': 1}, # test with high log_level and log_level_replica - should be quiet on all processes '''mixed''': {'''extra_args_str''': '''--log_level error --log_level_replica error''', '''n_matches''': 0}, } __lowerCamelCase = experiments[experiment_id] __lowerCamelCase = {'''distributed''': True, '''predict_with_generate''': False, '''do_eval''': False, '''do_predict''': False} __lowerCamelCase = '''Running training''' with CaptureStderr() as cl: self.run_seqaseq_quick(**SCREAMING_SNAKE_CASE__ , extra_args_str=data['''extra_args_str'''] ) __lowerCamelCase = len(re.findall(SCREAMING_SNAKE_CASE__ , cl.err ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ , data['''n_matches'''] ) @slow def __A ( self : Any ) -> Optional[Any]: __lowerCamelCase = self.run_trainer( eval_steps=2 , max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=10 , distributed=SCREAMING_SNAKE_CASE__ , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] __lowerCamelCase = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) # test if do_predict saves generations and metrics __lowerCamelCase = os.listdir(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {os.path.basename(SCREAMING_SNAKE_CASE__ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def __A ( self : Optional[int] ) -> str: from transformers.training_args import OptimizerNames def train_and_return_metrics(SCREAMING_SNAKE_CASE__ : str ) -> Tuple[int, float]: __lowerCamelCase = '''--skip_memory_metrics 0''' __lowerCamelCase = self.run_trainer( max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=1 , optim=SCREAMING_SNAKE_CASE__ , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , n_gpus_to_use=1 , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(Path(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = int(logs[0]['''train_mem_gpu_peaked_delta'''] / 2**20 ) __lowerCamelCase = int(logs[0]['''train_mem_gpu_alloc_delta'''] / 2**20 ) __lowerCamelCase = logs[0]['''train_loss'''] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) __lowerCamelCase = gpu_alloc_mem_orig - gpu_alloc_mem_bnb __lowerCamelCase = gpu_peak_mem_orig + gpu_alloc_mem_orig __lowerCamelCase = gpu_peak_mem_bnb + gpu_alloc_mem_bnb __lowerCamelCase = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings __lowerCamelCase = 1_20 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and''' f''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , ) self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less total gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and''' f''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , ) self.assertEqual( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , f'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = 3e-3 , SCREAMING_SNAKE_CASE__ : str = "adafactor" , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : int = None , ) -> List[Any]: __lowerCamelCase = self.test_file_dir / '''../fixtures/tests_samples/wmt_en_ro''' __lowerCamelCase = self.get_auto_remove_tmp_dir() __lowerCamelCase = f''' --model_name_or_path {model_name} --train_file {data_dir}/train.json --validation_file {data_dir}/val.json --test_file {data_dir}/test.json --output_dir {output_dir} --overwrite_output_dir --max_train_samples 8 --max_source_length {max_len} --max_target_length {max_len} --do_train --num_train_epochs {str(SCREAMING_SNAKE_CASE__ )} --per_device_train_batch_size 4 --learning_rate {learning_rate} --warmup_steps 8 --logging_steps 0 --logging_strategy no --save_steps {str(SCREAMING_SNAKE_CASE__ )} --group_by_length --label_smoothing_factor 0.1 --target_lang ro_RO --source_lang en_XX '''.split() __lowerCamelCase = f''' --do_eval --per_device_eval_batch_size 4 --max_eval_samples 8 --val_max_target_length {max_len} --evaluation_strategy steps --eval_steps {str(SCREAMING_SNAKE_CASE__ )} '''.split() __lowerCamelCase = ''' --do_predict '''.split() __lowerCamelCase = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f'''--optim {optim}'''.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: __lowerCamelCase = get_gpu_count() __lowerCamelCase = get_torch_dist_unique_port() __lowerCamelCase = f''' -m torch.distributed.run --nproc_per_node={n_gpus_to_use} --master_port={master_port} {self.examples_dir_str}/pytorch/translation/run_translation.py '''.split() __lowerCamelCase = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) else: __lowerCamelCase = ['''run_translation.py'''] + args with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): main() return output_dir
270
0
'''simple docstring''' from __future__ import annotations def __lowercase ( __lowercase , __lowercase = None , __lowercase = None ) -> None: '''simple docstring''' if start is None: _A = 0 if end is None: _A = len(__lowercase ) - 1 if start >= end: return _A = (start + end) // 2 slowsort(__lowercase , __lowercase , __lowercase ) slowsort(__lowercase , mid + 1 , __lowercase ) if sequence[end] < sequence[mid]: _A , _A = sequence[mid], sequence[end] slowsort(__lowercase , __lowercase , end - 1 ) if __name__ == "__main__": from doctest import testmod testmod()
79
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__ : Dict = { "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__ : int = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowercase ): a__ : Any = """mask2former""" a__ : Dict = ["""swin"""] a__ : Any = {"""hidden_size""": """hidden_dim"""} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 20_48 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_55 , SCREAMING_SNAKE_CASE__ : int = 1_00 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_25_44 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 16, 32] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> str: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.''' ) __lowerCamelCase = CONFIG_MAPPING['''swin''']( image_size=2_24 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = backbone_config.pop('''model_type''' ) __lowerCamelCase = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # 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 )}''' ) __lowerCamelCase = backbone_config __lowerCamelCase = feature_size __lowerCamelCase = mask_feature_size __lowerCamelCase = hidden_dim __lowerCamelCase = encoder_feedforward_dim __lowerCamelCase = activation_function __lowerCamelCase = encoder_layers __lowerCamelCase = decoder_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = dropout __lowerCamelCase = dim_feedforward __lowerCamelCase = pre_norm __lowerCamelCase = enforce_input_projection __lowerCamelCase = common_stride __lowerCamelCase = ignore_value __lowerCamelCase = num_queries __lowerCamelCase = no_object_weight __lowerCamelCase = class_weight __lowerCamelCase = mask_weight __lowerCamelCase = dice_weight __lowerCamelCase = train_num_points __lowerCamelCase = oversample_ratio __lowerCamelCase = importance_sample_ratio __lowerCamelCase = init_std __lowerCamelCase = init_xavier_std __lowerCamelCase = use_auxiliary_loss __lowerCamelCase = feature_strides __lowerCamelCase = output_auxiliary_logits __lowerCamelCase = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def __A ( cls : Any , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Any ) -> Dict[str, any]: __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.backbone_config.to_dict() __lowerCamelCase = self.__class__.model_type return output
270
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig a__ : Dict = { 'google/tapas-base-finetuned-sqa': ( 'https://huggingface.co/google/tapas-base-finetuned-sqa/resolve/main/config.json' ), 'google/tapas-base-finetuned-wtq': ( 'https://huggingface.co/google/tapas-base-finetuned-wtq/resolve/main/config.json' ), 'google/tapas-base-finetuned-wikisql-supervised': ( 'https://huggingface.co/google/tapas-base-finetuned-wikisql-supervised/resolve/main/config.json' ), 'google/tapas-base-finetuned-tabfact': ( 'https://huggingface.co/google/tapas-base-finetuned-tabfact/resolve/main/config.json' ), } class lowercase_ ( a__ ): __UpperCAmelCase = 'tapas' def __init__( self , a=3_05_22 , a=7_68 , a=12 , a=12 , a=30_72 , a="gelu" , a=0.1 , a=0.1 , a=10_24 , a=[3, 2_56, 2_56, 2, 2_56, 2_56, 10] , a=0.02 , a=1e-12 , a=0 , a=10.0 , a=0 , a=1.0 , a=None , a=1.0 , a=False , a=None , a=1.0 , a=1.0 , a=False , a=False , a="ratio" , a=None , a=None , a=64 , a=32 , a=False , a=True , a=False , a=False , a=True , a=False , a=None , a=None , **a , ): super().__init__(pad_token_id=a , **a ) # BERT hyperparameters (with updated max_position_embeddings and type_vocab_sizes) UpperCamelCase__ = vocab_size UpperCamelCase__ = hidden_size UpperCamelCase__ = num_hidden_layers UpperCamelCase__ = num_attention_heads UpperCamelCase__ = hidden_act UpperCamelCase__ = intermediate_size UpperCamelCase__ = hidden_dropout_prob UpperCamelCase__ = attention_probs_dropout_prob UpperCamelCase__ = max_position_embeddings UpperCamelCase__ = type_vocab_sizes UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps # Fine-tuning task hyperparameters UpperCamelCase__ = positive_label_weight UpperCamelCase__ = num_aggregation_labels UpperCamelCase__ = aggregation_loss_weight UpperCamelCase__ = use_answer_as_supervision UpperCamelCase__ = answer_loss_importance UpperCamelCase__ = use_normalized_answer_loss UpperCamelCase__ = huber_loss_delta UpperCamelCase__ = temperature UpperCamelCase__ = aggregation_temperature UpperCamelCase__ = use_gumbel_for_cells UpperCamelCase__ = use_gumbel_for_aggregation UpperCamelCase__ = average_approximation_function UpperCamelCase__ = cell_selection_preference UpperCamelCase__ = answer_loss_cutoff UpperCamelCase__ = max_num_rows UpperCamelCase__ = max_num_columns UpperCamelCase__ = average_logits_per_cell UpperCamelCase__ = select_one_column UpperCamelCase__ = allow_empty_column_selection UpperCamelCase__ = init_cell_selection_weights_to_zero UpperCamelCase__ = reset_position_index_per_cell UpperCamelCase__ = disable_per_token_loss # Aggregation hyperparameters UpperCamelCase__ = aggregation_labels UpperCamelCase__ = no_aggregation_label_index if isinstance(self.aggregation_labels , a ): UpperCamelCase__ = {int(a ): v for k, v in aggregation_labels.items()}
80
import os def __magic_name__ ( ) -> str: __lowerCamelCase = os.path.join(os.path.dirname(__lowerCAmelCase ) , '''num.txt''' ) with open(__lowerCAmelCase ) as file_hand: return str(sum(int(__lowerCAmelCase ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
270
0