code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
def _a ( lowercase__ : int = 10 , lowercase__ : int = 22 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = range(1 , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = range(1 , lowercase__ ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(F"""{solution(10, 22) = }""")
85
from pathlib import Path import numpy as np from PIL import Image def _a ( lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return (gray > 1_27) & (gray <= 2_55) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros_like(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE__ : Optional[Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE__ : List[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE__ : List[str] = int(summation > 0 ) return output if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE__ : int = Path(__file__).resolve().parent / "image_data" / "lena.jpg" SCREAMING_SNAKE_CASE__ : int = np.array(Image.open(lena_path)) # kernel to be applied SCREAMING_SNAKE_CASE__ : str = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) SCREAMING_SNAKE_CASE__ : Optional[int] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image SCREAMING_SNAKE_CASE__ : Optional[int] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
85
1
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) def _a ( lowercase__ : List[str] , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = set() SCREAMING_SNAKE_CASE__ : Any = [] def parse_line(lowercase__ : Optional[Any] ): for line in fp: if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : int = line.decode('UTF-8' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(' ' ): # process a single warning and move it to `selected_warnings`. if len(lowercase__ ) > 0: SCREAMING_SNAKE_CASE__ : Optional[int] = '\n'.join(lowercase__ ) # Only keep the warnings specified in `targets` if any(f''': {x}: ''' in warning for x in targets ): selected_warnings.add(lowercase__ ) buffer.clear() continue else: SCREAMING_SNAKE_CASE__ : Optional[int] = line.strip() buffer.append(lowercase__ ) if from_gh: for filename in os.listdir(lowercase__ ): SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join(lowercase__ , lowercase__ ) if not os.path.isdir(lowercase__ ): # read the file if filename != "warnings.txt": continue with open(lowercase__ ) as fp: parse_line(lowercase__ ) else: try: with zipfile.ZipFile(lowercase__ ) as z: for filename in z.namelist(): if not os.path.isdir(lowercase__ ): # read the file if filename != "warnings.txt": continue with z.open(lowercase__ ) as fp: parse_line(lowercase__ ) except Exception: logger.warning( f'''{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.''' ) return selected_warnings def _a ( lowercase__ : List[Any] , lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = set() SCREAMING_SNAKE_CASE__ : Optional[int] = [os.path.join(lowercase__ , lowercase__ ) for p in os.listdir(lowercase__ ) if (p.endswith('.zip' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(lowercase__ , lowercase__ ) ) return selected_warnings if __name__ == "__main__": def _a ( lowercase__ : Union[str, Any] ): '''simple docstring''' return values.split(',' ) SCREAMING_SNAKE_CASE__ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") parser.add_argument( "--output_dir", type=str, required=True, help="Where to store the downloaded artifacts and other result files.", ) parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") # optional parameters parser.add_argument( "--targets", default="DeprecationWarning,UserWarning,FutureWarning", type=list_str, help="Comma-separated list of target warning(s) which we want to extract.", ) parser.add_argument( "--from_gh", action="store_true", help="If running from a GitHub action workflow and collecting warnings from its artifacts.", ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() SCREAMING_SNAKE_CASE__ : Any = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links SCREAMING_SNAKE_CASE__ : Dict = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("=" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts SCREAMING_SNAKE_CASE__ : Any = extract_warnings(args.output_dir, args.targets) SCREAMING_SNAKE_CASE__ : Any = sorted(selected_warnings) with open(os.path.join(args.output_dir, "selected_warnings.json"), "w", encoding="UTF-8") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
85
def _a ( lowercase__ : int = 60_08_51_47_51_43 ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Dict = int(lowercase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : int = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 SCREAMING_SNAKE_CASE__ : str = i while n % i == 0: SCREAMING_SNAKE_CASE__ : List[Any] = n // i i += 1 return int(lowercase__ ) if __name__ == "__main__": print(F"""{solution() = }""")
85
1
# This is the module that test_patching.py uses to test patch_submodule() import os # noqa: this is just for tests import os as renamed_os # noqa: this is just for tests from os import path # noqa: this is just for tests from os import path as renamed_path # noqa: this is just for tests from os.path import join # noqa: this is just for tests from os.path import join as renamed_join # noqa: this is just for tests SCREAMING_SNAKE_CASE__ : Dict = open # noqa: we just need to have a builtin inside this module to test it properly
85
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = int(lowercase__ ) if n_element < 1: SCREAMING_SNAKE_CASE__ : Tuple = ValueError('a should be a positive number' ) raise my_error SCREAMING_SNAKE_CASE__ : Any = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = (0, 0, 0) SCREAMING_SNAKE_CASE__ : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") SCREAMING_SNAKE_CASE__ : int = hamming(int(n)) print("-----------------------------------------------------") print(F"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
85
1
from ..utils import DummyObject, requires_backends class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['torch', 'torchsde'] def __init__( self : Tuple , *a_ : Any , **a_ : List[Any] )-> Any: """simple docstring""" requires_backends(self , ['torch', 'torchsde'] ) @classmethod def __lowercase( cls : Optional[Any] , *a_ : Tuple , **a_ : Optional[Any] )-> int: """simple docstring""" requires_backends(cls , ['torch', 'torchsde'] ) @classmethod def __lowercase( cls : List[Any] , *a_ : Tuple , **a_ : str )-> str: """simple docstring""" requires_backends(cls , ['torch', 'torchsde'] )
85
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def _a ( lowercase__ : List[str] , lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = [] for part_id in partition_order: SCREAMING_SNAKE_CASE__ : Optional[int] = df.where(f'''SPARK_PARTITION_ID() = {part_id}''' ).collect() for row_idx, row in enumerate(lowercase__ ): expected_row_ids_and_row_dicts.append((f'''{part_id}_{row_idx}''', row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() SCREAMING_SNAKE_CASE__ : Any = spark.range(1_00 ).repartition(1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = Spark(lowercase__ ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() SCREAMING_SNAKE_CASE__ : int = spark.range(10 ).repartition(2 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [1, 0] SCREAMING_SNAKE_CASE__ : str = _generate_iterable_examples(lowercase__ , lowercase__ ) # Reverse the partitions. SCREAMING_SNAKE_CASE__ : List[Any] = _get_expected_row_ids_and_row_dicts_for_partition_order(lowercase__ , lowercase__ ) for i, (row_id, row_dict) in enumerate(generate_fn() ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() SCREAMING_SNAKE_CASE__ : str = spark.range(10 ).repartition(1 ) SCREAMING_SNAKE_CASE__ : int = SparkExamplesIterable(lowercase__ ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(lowercase__ ): assert row_id == f'''0_{i}''' assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() SCREAMING_SNAKE_CASE__ : Dict = spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch('numpy.random.Generator' ) as generator_mock: SCREAMING_SNAKE_CASE__ : str = lambda lowercase__ : x.reverse() SCREAMING_SNAKE_CASE__ : List[str] = _get_expected_row_ids_and_row_dicts_for_partition_order(lowercase__ , [2, 1, 0] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = SparkExamplesIterable(lowercase__ ).shuffle_data_sources(lowercase__ ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(lowercase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() SCREAMING_SNAKE_CASE__ : Union[str, Any] = spark.range(20 ).repartition(4 ) # Partitions 0 and 2 SCREAMING_SNAKE_CASE__ : Tuple = SparkExamplesIterable(lowercase__ ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 SCREAMING_SNAKE_CASE__ : Any = _get_expected_row_ids_and_row_dicts_for_partition_order(lowercase__ , [0, 2] ) for i, (row_id, row_dict) in enumerate(lowercase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 SCREAMING_SNAKE_CASE__ : Optional[int] = SparkExamplesIterable(lowercase__ ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 SCREAMING_SNAKE_CASE__ : Optional[int] = _get_expected_row_ids_and_row_dicts_for_partition_order(lowercase__ , [1, 3] ) for i, (row_id, row_dict) in enumerate(lowercase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = pyspark.sql.SparkSession.builder.master('local[*]' ).appName('pyspark' ).getOrCreate() SCREAMING_SNAKE_CASE__ : Any = spark.range(1_00 ).repartition(1 ) SCREAMING_SNAKE_CASE__ : str = Spark(lowercase__ ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 1_00
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
from collections.abc import Sequence from queue import Queue class snake_case : def __init__( self : Optional[int] , a_ : Tuple , a_ : str , a_ : Union[str, Any] , a_ : Optional[Any]=None , a_ : List[str]=None )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = start SCREAMING_SNAKE_CASE__ : Any = end SCREAMING_SNAKE_CASE__ : Any = val SCREAMING_SNAKE_CASE__ : Union[str, Any] = (start + end) // 2 SCREAMING_SNAKE_CASE__ : List[str] = left SCREAMING_SNAKE_CASE__ : str = right def __repr__( self : List[Any] )-> List[str]: """simple docstring""" return F'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})''' class snake_case : def __init__( self : Tuple , a_ : Sequence , a_ : Dict )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = collection SCREAMING_SNAKE_CASE__ : Union[str, Any] = function if self.collection: SCREAMING_SNAKE_CASE__ : Tuple = self._build_tree(0 , len(a_ ) - 1 ) def __lowercase( self : Union[str, Any] , a_ : List[str] , a_ : List[str] )-> str: """simple docstring""" self._update_tree(self.root , a_ , a_ ) def __lowercase( self : Tuple , a_ : List[Any] , a_ : Optional[Any] )-> Union[str, Any]: """simple docstring""" return self._query_range(self.root , a_ , a_ ) def __lowercase( self : int , a_ : str , a_ : List[str] )-> int: """simple docstring""" if start == end: return SegmentTreeNode(a_ , a_ , self.collection[start] ) SCREAMING_SNAKE_CASE__ : Any = (start + end) // 2 SCREAMING_SNAKE_CASE__ : Optional[int] = self._build_tree(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self._build_tree(mid + 1 , a_ ) return SegmentTreeNode(a_ , a_ , self.fn(left.val , right.val ) , a_ , a_ ) def __lowercase( self : str , a_ : str , a_ : List[Any] , a_ : str )-> List[Any]: """simple docstring""" if node.start == i and node.end == i: SCREAMING_SNAKE_CASE__ : Optional[int] = val return if i <= node.mid: self._update_tree(node.left , a_ , a_ ) else: self._update_tree(node.right , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.fn(node.left.val , node.right.val ) def __lowercase( self : Any , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] )-> List[str]: """simple docstring""" if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , a_ , a_ ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , a_ , node.mid ) , self._query_range(node.right , node.mid + 1 , a_ ) , ) else: # range in right child tree return self._query_range(node.right , a_ , a_ ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" if self.root is not None: SCREAMING_SNAKE_CASE__ : Dict = Queue() queue.put(self.root ) while not queue.empty(): SCREAMING_SNAKE_CASE__ : Any = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print("*" * 50) SCREAMING_SNAKE_CASE__ : Any = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
85
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs SCREAMING_SNAKE_CASE__ : int = imread(r"digital_image_processing/image_data/lena_small.jpg") SCREAMING_SNAKE_CASE__ : List[Any] = cvtColor(img, COLOR_BGR2GRAY) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = cn.convert_to_negative(lowercase__ ) # assert negative_img array for at least one True assert negative_img.any() def _a ( ): '''simple docstring''' with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowercase__ , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ : List[str] = canny.canny(lowercase__ ) # assert canny array for at least one True assert canny_array.any() def _a ( ): '''simple docstring''' assert gg.gaussian_filter(lowercase__ , 5 , sigma=0.9 ).all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) SCREAMING_SNAKE_CASE__ : Tuple = conv.img_convolve(lowercase__ , lowercase__ ).astype(lowercase__ ) assert res.any() def _a ( ): '''simple docstring''' assert med.median_filter(lowercase__ , 3 ).any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = sob.sobel_filter(lowercase__ ) assert grad.any() and theta.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = sp.make_sepia(lowercase__ , 20 ) assert sepia.all() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = bs.Burkes(imread(lowercase__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = rs.NearestNeighbour(imread(lowercase__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ : Dict = imread(lowercase__ , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ : List[Any] = lbp.get_neighbors_pixel( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): SCREAMING_SNAKE_CASE__ : str = lbp.local_binary_value(lowercase__ , lowercase__ , lowercase__ ) assert lbp_image.any()
85
1
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = { "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json", "google/bigbird-roberta-large": "https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json", "google/bigbird-base-trivia-itc": "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class snake_case ( UpperCamelCase_ ): lowercase_ = 'big_bird' def __init__( self : Any , a_ : List[str]=5_0358 , a_ : Union[str, Any]=768 , a_ : Optional[Any]=12 , a_ : Any=12 , a_ : List[str]=3072 , a_ : str="gelu_new" , a_ : str=0.1 , a_ : str=0.1 , a_ : Optional[int]=4096 , a_ : Tuple=2 , a_ : str=0.02 , a_ : str=1e-1_2 , a_ : Any=True , a_ : List[Any]=0 , a_ : Union[str, Any]=1 , a_ : List[Any]=2 , a_ : List[str]=66 , a_ : Optional[int]="block_sparse" , a_ : int=True , a_ : Dict=False , a_ : Any=64 , a_ : Tuple=3 , a_ : Tuple=None , **a_ : List[str] , )-> List[str]: """simple docstring""" super().__init__( pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , sep_token_id=a_ , **a_ , ) SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Any = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : str = intermediate_size SCREAMING_SNAKE_CASE__ : Any = hidden_act SCREAMING_SNAKE_CASE__ : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : Tuple = type_vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = use_cache SCREAMING_SNAKE_CASE__ : Optional[int] = rescale_embeddings SCREAMING_SNAKE_CASE__ : Any = attention_type SCREAMING_SNAKE_CASE__ : Dict = use_bias SCREAMING_SNAKE_CASE__ : List[Any] = block_size SCREAMING_SNAKE_CASE__ : List[Any] = num_random_blocks SCREAMING_SNAKE_CASE__ : Any = classifier_dropout class snake_case ( UpperCamelCase_ ): @property def __lowercase( self : List[Any] )-> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : Any = {0: 'batch', 1: 'choice', 2: 'sequence'} else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
85
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu SCREAMING_SNAKE_CASE__ : Any = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: SCREAMING_SNAKE_CASE__ : Tuple = json.load(f) @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : List[str] , a_ : Any )-> str: """simple docstring""" return FSMTTokenizer.from_pretrained(a_ ) def __lowercase( self : int , a_ : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FSMTForConditionalGeneration.from_pretrained(a_ ).to(a_ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['en-ru', 26.0], ['ru-en', 22.0], ['en-de', 22.0], ['de-en', 29.0], ] ) @slow def __lowercase( self : int , a_ : Optional[int] , a_ : str )-> List[str]: """simple docstring""" # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality SCREAMING_SNAKE_CASE__ : Any = F'''facebook/wmt19-{pair}''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_model(a_ ) SCREAMING_SNAKE_CASE__ : int = bleu_data[pair]['src'] SCREAMING_SNAKE_CASE__ : Optional[int] = bleu_data[pair]['tgt'] SCREAMING_SNAKE_CASE__ : Any = tokenizer(a_ , return_tensors='pt' , truncation=a_ , padding='longest' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( input_ids=batch.input_ids , num_beams=8 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.batch_decode( a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_bleu(a_ , a_ ) print(a_ ) self.assertGreaterEqual(scores['bleu'] , a_ )
85
1
from __future__ import annotations import pandas as pd def _a ( lowercase__ : list[int] , lowercase__ : list[int] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [0] * no_of_processes SCREAMING_SNAKE_CASE__ : int = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = burst_time[i] SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Any = 9_99_99_99_99 SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : Any = False # Process until all processes are completed while complete != no_of_processes: for j in range(lowercase__ ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: SCREAMING_SNAKE_CASE__ : Dict = remaining_time[j] SCREAMING_SNAKE_CASE__ : List[str] = j SCREAMING_SNAKE_CASE__ : List[str] = True if not check: increment_time += 1 continue remaining_time[short] -= 1 SCREAMING_SNAKE_CASE__ : Any = remaining_time[short] if minm == 0: SCREAMING_SNAKE_CASE__ : int = 9_99_99_99_99 if remaining_time[short] == 0: complete += 1 SCREAMING_SNAKE_CASE__ : str = False # Find finish time of current process SCREAMING_SNAKE_CASE__ : str = increment_time + 1 # Calculate waiting time SCREAMING_SNAKE_CASE__ : int = finish_time - arrival_time[short] SCREAMING_SNAKE_CASE__ : int = finar - burst_time[short] if waiting_time[short] < 0: SCREAMING_SNAKE_CASE__ : int = 0 # Increment time increment_time += 1 return waiting_time def _a ( lowercase__ : list[int] , lowercase__ : int , lowercase__ : list[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = [0] * no_of_processes for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = burst_time[i] + waiting_time[i] return turn_around_time def _a ( lowercase__ : list[int] , lowercase__ : list[int] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : List[str] = 0 for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = total_waiting_time + waiting_time[i] SCREAMING_SNAKE_CASE__ : List[str] = total_turn_around_time + turn_around_time[i] print(f'''Average waiting time = {total_waiting_time / no_of_processes:.5f}''' ) print('Average turn around time =' , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print("Enter how many process you want to analyze") SCREAMING_SNAKE_CASE__ : str = int(input()) SCREAMING_SNAKE_CASE__ : Optional[int] = [0] * no_of_processes SCREAMING_SNAKE_CASE__ : str = [0] * no_of_processes SCREAMING_SNAKE_CASE__ : int = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print("Enter the arrival time and burst time for process:--" + str(i + 1)) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = map(int, input().split()) SCREAMING_SNAKE_CASE__ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Any = burst_time SCREAMING_SNAKE_CASE__ : Union[str, Any] = no_of_processes SCREAMING_SNAKE_CASE__ : str = waiting_time SCREAMING_SNAKE_CASE__ : int = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Any = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ "Process", "BurstTime", "ArrivalTime", "WaitingTime", "TurnAroundTime", ], ) # Printing the dataFrame pd.set_option("display.max_rows", fcfs.shape[0] + 1) print(fcfs)
85
import os import pytest from attr import dataclass SCREAMING_SNAKE_CASE__ : int = "us-east-1" # defaults region @dataclass class snake_case : lowercase_ = 42 lowercase_ = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' lowercase_ = { 'task_name': 'mnli', 'per_device_train_batch_size': 16, 'per_device_eval_batch_size': 16, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 500, 'save_steps': 5_500, } lowercase_ = {**hyperparameters, 'max_steps': 1_000} @property def __lowercase( self : List[str] )-> str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return F'''{self.framework}-transfromers-test''' @property def __lowercase( self : int )-> str: """simple docstring""" return F'''./tests/sagemaker/scripts/{self.framework}''' @property def __lowercase( self : Tuple )-> str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def _a ( lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
85
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = { "abeja/gpt-neox-japanese-2.7b": "https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'gpt_neox_japanese' def __init__( self : Any , a_ : Optional[int]=3_2000 , a_ : List[Any]=2560 , a_ : Any=32 , a_ : Union[str, Any]=32 , a_ : Any=4 , a_ : List[Any]="gelu" , a_ : Optional[int]=1.00 , a_ : int=1_0000 , a_ : Optional[int]=2048 , a_ : str=0.02 , a_ : Any=1e-5 , a_ : Dict=True , a_ : Tuple=3_1996 , a_ : Any=3_1999 , a_ : str=0.1 , a_ : Optional[int]=0.0 , **a_ : List[Any] , )-> List[str]: """simple docstring""" super().__init__(bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_multiple_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : int = rotary_pct SCREAMING_SNAKE_CASE__ : Tuple = rotary_emb_base SCREAMING_SNAKE_CASE__ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Tuple = use_cache SCREAMING_SNAKE_CASE__ : str = attention_dropout SCREAMING_SNAKE_CASE__ : int = hidden_dropout
85
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = FunnelTokenizer lowercase_ = FunnelTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : str = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase( self : Any , **a_ : Any )-> List[str]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Tuple , **a_ : List[Any] )-> List[Any]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : int = 'unwanted, running' return input_text, output_text def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(a_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [7, 4, 5, 10, 8, 9] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer('UNwant\u00E9d,running' ) SCREAMING_SNAKE_CASE__ : List[Any] = len(inputs['input_ids'] ) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running' ) self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len )
85
1
from statistics import mean import numpy as np def _a ( lowercase__ : list , lowercase__ : list , lowercase__ : list , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 # Number of processes finished SCREAMING_SNAKE_CASE__ : Tuple = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. SCREAMING_SNAKE_CASE__ : Optional[int] = [0] * no_of_process # List to include calculation results SCREAMING_SNAKE_CASE__ : Optional[Any] = [0] * no_of_process # Sort by arrival time. SCREAMING_SNAKE_CASE__ : Optional[int] = [burst_time[i] for i in np.argsort(lowercase__ )] SCREAMING_SNAKE_CASE__ : List[str] = [process_name[i] for i in np.argsort(lowercase__ )] arrival_time.sort() while no_of_process > finished_process_count: SCREAMING_SNAKE_CASE__ : Tuple = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: SCREAMING_SNAKE_CASE__ : str = arrival_time[i] SCREAMING_SNAKE_CASE__ : Any = 0 # Index showing the location of the process being performed SCREAMING_SNAKE_CASE__ : Any = 0 # Saves the current response ratio. SCREAMING_SNAKE_CASE__ : Any = 0 for i in range(0 , lowercase__ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: SCREAMING_SNAKE_CASE__ : Any = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: SCREAMING_SNAKE_CASE__ : Union[str, Any] = temp SCREAMING_SNAKE_CASE__ : Optional[Any] = i # Calculate the turn around time SCREAMING_SNAKE_CASE__ : Optional[int] = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. SCREAMING_SNAKE_CASE__ : Tuple = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def _a ( lowercase__ : list , lowercase__ : list , lowercase__ : list , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [0] * no_of_process for i in range(0 , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[str] = 5 SCREAMING_SNAKE_CASE__ : Optional[int] = ["A", "B", "C", "D", "E"] SCREAMING_SNAKE_CASE__ : Dict = [1, 2, 3, 4, 5] SCREAMING_SNAKE_CASE__ : Dict = [1, 2, 3, 4, 5] SCREAMING_SNAKE_CASE__ : Optional[Any] = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) SCREAMING_SNAKE_CASE__ : Optional[Any] = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print("Process name \tArrival time \tBurst time \tTurn around time \tWaiting time") for i in range(0, no_of_process): print( F"""{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t""" F"""{turn_around_time[i]}\t\t\t{waiting_time[i]}""" ) print(F"""average waiting time : {mean(waiting_time):.5f}""") print(F"""average turn around time : {mean(turn_around_time):.5f}""")
85
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 SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json", # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case ( UpperCamelCase_ ): lowercase_ = 'levit' def __init__( self : str , a_ : Optional[Any]=224 , a_ : List[str]=3 , a_ : Any=3 , a_ : Any=2 , a_ : Tuple=1 , a_ : int=16 , a_ : Optional[int]=[128, 256, 384] , a_ : Dict=[4, 8, 12] , a_ : List[str]=[4, 4, 4] , a_ : Any=[16, 16, 16] , a_ : Dict=0 , a_ : Tuple=[2, 2, 2] , a_ : Union[str, Any]=[2, 2, 2] , a_ : Optional[Any]=0.02 , **a_ : str , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : Any = kernel_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = stride SCREAMING_SNAKE_CASE__ : Any = padding SCREAMING_SNAKE_CASE__ : Any = hidden_sizes SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = key_dim SCREAMING_SNAKE_CASE__ : int = drop_path_rate SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = attention_ratio SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.11' ) @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowercase( self : Any )-> float: """simple docstring""" return 1e-4
85
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : int = { "configuration_albert": ["ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "AlbertConfig", "AlbertOnnxConfig"], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Dict = ["AlbertTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = ["AlbertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "AlbertForMaskedLM", "AlbertForMultipleChoice", "AlbertForPreTraining", "AlbertForQuestionAnswering", "AlbertForSequenceClassification", "AlbertForTokenClassification", "AlbertModel", "AlbertPreTrainedModel", "load_tf_weights_in_albert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Dict = [ "TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFAlbertForMaskedLM", "TFAlbertForMultipleChoice", "TFAlbertForPreTraining", "TFAlbertForQuestionAnswering", "TFAlbertForSequenceClassification", "TFAlbertForTokenClassification", "TFAlbertMainLayer", "TFAlbertModel", "TFAlbertPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "FlaxAlbertForMaskedLM", "FlaxAlbertForMultipleChoice", "FlaxAlbertForPreTraining", "FlaxAlbertForQuestionAnswering", "FlaxAlbertForSequenceClassification", "FlaxAlbertForTokenClassification", "FlaxAlbertModel", "FlaxAlbertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_albert import ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, AlbertConfig, AlbertOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert import AlbertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_albert_fast import AlbertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_albert import ( ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, AlbertPreTrainedModel, load_tf_weights_in_albert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_albert import ( TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFAlbertForMaskedLM, TFAlbertForMultipleChoice, TFAlbertForPreTraining, TFAlbertForQuestionAnswering, TFAlbertForSequenceClassification, TFAlbertForTokenClassification, TFAlbertMainLayer, TFAlbertModel, TFAlbertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_albert import ( FlaxAlbertForMaskedLM, FlaxAlbertForMultipleChoice, FlaxAlbertForPreTraining, FlaxAlbertForQuestionAnswering, FlaxAlbertForSequenceClassification, FlaxAlbertForTokenClassification, FlaxAlbertModel, FlaxAlbertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : List[str] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : List[Any] , a_ : Tuple , a_ : Optional[Any]=0 )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : List[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'french fries' SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : List[str] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : Tuple = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : int = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = components['vae'] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : List[Any] , a_ : Dict=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : Tuple = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Tuple = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : List[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : int )-> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : Dict = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : List[Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] SCREAMING_SNAKE_CASE__ : Any = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
85
1
from __future__ import annotations def _a ( lowercase__ : list[list[int]] ): '''simple docstring''' for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(lowercase__ ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(lowercase__ ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
85
import math from collections.abc import Callable def _a ( lowercase__ : Callable[[float], float] , lowercase__ : float , lowercase__ : float ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : float = xa SCREAMING_SNAKE_CASE__ : float = xa while True: if x_n == x_na or function(lowercase__ ) == function(lowercase__ ): raise ZeroDivisionError('float division by zero, could not find root' ) SCREAMING_SNAKE_CASE__ : float = x_na - ( function(lowercase__ ) / ((function(lowercase__ ) - function(lowercase__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na SCREAMING_SNAKE_CASE__ : Dict = x_na SCREAMING_SNAKE_CASE__ : List[str] = x_na def _a ( lowercase__ : float ): '''simple docstring''' return math.pow(lowercase__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
85
1
def _a ( lowercase__ : int = 1_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = set() SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : Any = n + 1 # maximum limit for a in range(2 , lowercase__ ): for b in range(2 , lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = a**b # calculates the current power collect_powers.add(lowercase__ ) # adds the result to the set return len(lowercase__ ) if __name__ == "__main__": print("Number of terms ", solution(int(str(input()).strip())))
85
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'AutoImageProcessor' lowercase_ = 'AutoTokenizer' def __init__( self : List[Any] , a_ : int , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self.image_processor def __call__( self : Tuple , a_ : str=None , a_ : List[Any]=None , a_ : Optional[Any]=None , **a_ : Dict )-> Tuple: """simple docstring""" if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : List[str] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : Dict , *a_ : Any , **a_ : Any )-> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Dict , *a_ : Union[str, Any] , **a_ : Optional[int] )-> Dict: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Any )-> Any: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
85
1
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 CLIPSegProcessor, ViTImageProcessor @require_vision class snake_case ( unittest.TestCase ): def __lowercase( self : Optional[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = tempfile.mkdtemp() # fmt: off SCREAMING_SNAKE_CASE__ : Optional[Any] = ['l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>'] # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = dict(zip(a_ , range(len(a_ ) ) ) ) SCREAMING_SNAKE_CASE__ : Dict = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', ''] SCREAMING_SNAKE_CASE__ : str = {'unk_token': '<unk>'} SCREAMING_SNAKE_CASE__ : Any = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(a_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a_ ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { 'do_resize': True, 'size': 20, 'do_center_crop': True, 'crop_size': 18, 'do_normalize': True, 'image_mean': [0.4814_5466, 0.457_8275, 0.4082_1073], 'image_std': [0.2686_2954, 0.2613_0258, 0.2757_7711], } SCREAMING_SNAKE_CASE__ : Dict = os.path.join(self.tmpdirname , a_ ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(a_ , a_ ) def __lowercase( self : Any , **a_ : Any )-> str: """simple docstring""" return CLIPTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , **a_ : Optional[int] )-> List[str]: """simple docstring""" return CLIPTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Any , **a_ : List[str] )-> int: """simple docstring""" return ViTImageProcessor.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Tuple )-> Optional[int]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : Dict = [Image.fromarray(np.moveaxis(a_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Any = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Optional[Any] = CLIPSegProcessor(tokenizer=a_ , image_processor=a_ ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = CLIPSegProcessor.from_pretrained(self.tmpdirname , use_fast=a_ ) SCREAMING_SNAKE_CASE__ : Dict = CLIPSegProcessor(tokenizer=a_ , image_processor=a_ ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = CLIPSegProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , a_ ) self.assertIsInstance(processor_fast.tokenizer , a_ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , a_ ) self.assertIsInstance(processor_fast.image_processor , a_ ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = CLIPSegProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) SCREAMING_SNAKE_CASE__ : Dict = self.get_image_processor(do_normalize=a_ , padding_value=1.0 ) SCREAMING_SNAKE_CASE__ : str = CLIPSegProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=a_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , a_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , a_ ) def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = CLIPSegProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Dict = image_processor(a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(images=a_ , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowercase( self : Tuple )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : int = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPSegProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'lower newer' SCREAMING_SNAKE_CASE__ : List[str] = processor(text=a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer(a_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = CLIPSegProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'lower newer' SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[str] = processor(text=a_ , images=a_ ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(a_ ): processor() def __lowercase( self : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] = CLIPSegProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : int = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : str = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = processor(images=a_ , visual_prompt=a_ ) self.assertListEqual(list(inputs.keys() ) , ['pixel_values', 'conditional_pixel_values'] ) # test if it raises when no input is passed with pytest.raises(a_ ): processor() def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPSegProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE__ : Dict = processor.batch_decode(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.batch_decode(a_ ) self.assertListEqual(a_ , a_ )
85
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _a ( lowercase__ : int = 3 ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(lowercase__ ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumRegister(lowercase__ , 'qr' ) SCREAMING_SNAKE_CASE__ : int = ClassicalRegister(lowercase__ , 'cr' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumCircuit(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = number_of_qubits for i in range(lowercase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowercase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase__ , lowercase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowercase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowercase__ , lowercase__ ) # simulate with 10000 shots SCREAMING_SNAKE_CASE__ : Optional[int] = Aer.get_backend('qasm_simulator' ) SCREAMING_SNAKE_CASE__ : Tuple = execute(lowercase__ , lowercase__ , shots=1_00_00 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
85
1
import torch from diffusers import DPMSolverSDEScheduler from diffusers.utils import torch_device from diffusers.utils.testing_utils import require_torchsde from .test_schedulers import SchedulerCommonTest @require_torchsde class snake_case ( UpperCamelCase_ ): lowercase_ = (DPMSolverSDEScheduler,) lowercase_ = 10 def __lowercase( self : Any , **a_ : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = { 'num_train_timesteps': 1100, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'noise_sampler_seed': 0, } config.update(**a_ ) return config def __lowercase( self : int )-> str: """simple docstring""" for timesteps in [10, 50, 100, 1000]: self.check_over_configs(num_train_timesteps=a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001] , [0.0002, 0.002, 0.02] ): self.check_over_configs(beta_start=a_ , beta_end=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=a_ ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=a_ ) def __lowercase( self : Union[str, Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : str = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler_class(**a_ ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : List[str] = self.dummy_model() SCREAMING_SNAKE_CASE__ : Optional[int] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[int] = sample.to(a_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler.scale_model_input(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.step(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = output.prev_sample SCREAMING_SNAKE_CASE__ : Dict = torch.sum(torch.abs(a_ ) ) SCREAMING_SNAKE_CASE__ : Any = torch.mean(torch.abs(a_ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.47_8210_4492_1875 ) < 1e-2 assert abs(result_mean.item() - 0.2178_7059_6456_5277 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3521_1181_6406 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9068_9229_9652 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Any = self.get_scheduler_config(prediction_type='v_prediction' ) SCREAMING_SNAKE_CASE__ : List[Any] = scheduler_class(**a_ ) scheduler.set_timesteps(self.num_inference_steps ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_sample_deter * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[int] = sample.to(a_ ) for i, t in enumerate(scheduler.timesteps ): SCREAMING_SNAKE_CASE__ : List[Any] = scheduler.scale_model_input(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = scheduler.step(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = output.prev_sample SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.sum(torch.abs(a_ ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.mean(torch.abs(a_ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 124.77_1492_0043_9453 ) < 1e-2 assert abs(result_mean.item() - 0.1_6226_2890_1481_6284 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 128.1_6633_6059_5703 ) < 1e-2 assert abs(result_mean.item() - 0.1_6688_3260_0116_7297 ) < 1e-3 else: assert abs(result_sum.item() - 119.8_4875_4882_8125 ) < 1e-2 assert abs(result_mean.item() - 0.1560_5306_6253_6621 ) < 1e-3 def __lowercase( self : str )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : int = scheduler_class(**a_ ) scheduler.set_timesteps(self.num_inference_steps , device=a_ ) SCREAMING_SNAKE_CASE__ : str = self.dummy_model() SCREAMING_SNAKE_CASE__ : Dict = self.dummy_sample_deter.to(a_ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : Optional[int] = scheduler.scale_model_input(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = scheduler.step(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.prev_sample SCREAMING_SNAKE_CASE__ : List[Any] = torch.sum(torch.abs(a_ ) ) SCREAMING_SNAKE_CASE__ : Any = torch.mean(torch.abs(a_ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 167.46_9573_9746_0938 ) < 1e-2 assert abs(result_mean.item() - 0.2_1805_9346_0798_2635 ) < 1e-3 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 171.59_3536_3769_5312 ) < 1e-2 assert abs(result_mean.item() - 0.2_2342_9083_8241_5771 ) < 1e-3 else: assert abs(result_sum.item() - 162.52_3834_2285_1562 ) < 1e-2 assert abs(result_mean.item() - 0.211_6195_7085_1326 ) < 1e-3 def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.scheduler_classes[0] SCREAMING_SNAKE_CASE__ : Any = self.get_scheduler_config() SCREAMING_SNAKE_CASE__ : Optional[Any] = scheduler_class(**a_ , use_karras_sigmas=a_ ) scheduler.set_timesteps(self.num_inference_steps , device=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dummy_model() SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_sample_deter.to(a_ ) * scheduler.init_noise_sigma SCREAMING_SNAKE_CASE__ : Optional[int] = sample.to(a_ ) for t in scheduler.timesteps: SCREAMING_SNAKE_CASE__ : Tuple = scheduler.scale_model_input(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = scheduler.step(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Tuple = output.prev_sample SCREAMING_SNAKE_CASE__ : List[Any] = torch.sum(torch.abs(a_ ) ) SCREAMING_SNAKE_CASE__ : str = torch.mean(torch.abs(a_ ) ) if torch_device in ["mps"]: assert abs(result_sum.item() - 176.66_9741_3574_2188 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 elif torch_device in ["cuda"]: assert abs(result_sum.item() - 177.63_6535_6445_3125 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2 else: assert abs(result_sum.item() - 170.3_1352_2338_8672 ) < 1e-2 assert abs(result_mean.item() - 0.2_3003_8727_3098_1811 ) < 1e-2
85
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.mean(1 ) # Centralize the data of class i SCREAMING_SNAKE_CASE__ : Optional[Any] = data - column_reshape(lowercase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowercase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : Any = np.dot(lowercase__ , centered_data.T ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = features.mean(1 ) SCREAMING_SNAKE_CASE__ : List[str] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.shape[1] SCREAMING_SNAKE_CASE__ : List[Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : str = device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' if features.any(): SCREAMING_SNAKE_CASE__ : Any = features.mean(1 ) # Center the dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = features - np.reshape(lowercase__ , (data_mean.size, 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(lowercase__ , centered_data.T ) / features.shape[1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = np.linalg.eigh(lowercase__ ) # Take all the columns in the reverse order (-1), and then takes only the first SCREAMING_SNAKE_CASE__ : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.dot(filtered_eigenvectors.T , lowercase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = eigh( covariance_between_classes(lowercase__ , lowercase__ , lowercase__ ) , covariance_within_classes(lowercase__ , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = eigenvectors[:, ::-1][:, :dimensions] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.svd(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = svd_matrix[:, 0:dimensions] SCREAMING_SNAKE_CASE__ : int = np.dot(filtered_svd_matrix.T , lowercase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 0, 0, 1, 1] ) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : Optional[int] = linear_discriminant_analysis( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : int = principal_component_analysis(lowercase__ , lowercase__ ) if not np.allclose(lowercase__ , lowercase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
85
1
from string import ascii_lowercase, ascii_uppercase def _a ( lowercase__ : str ): '''simple docstring''' if not sentence: return "" SCREAMING_SNAKE_CASE__ : Tuple = dict(zip(lowercase__ , lowercase__ ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
85
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = "Hello world! cécé herlolip" SCREAMING_SNAKE_CASE__ : Dict = namedtuple( "BertAbsConfig", [ "temp_dir", "large", "use_bert_emb", "finetune_bert", "encoder", "share_emb", "max_pos", "enc_layers", "enc_hidden_size", "enc_heads", "enc_ff_size", "enc_dropout", "dec_layers", "dec_hidden_size", "dec_heads", "dec_ff_size", "dec_dropout", ], ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = BertAbsConfig( temp_dir='.' , finetune_bert=lowercase__ , large=lowercase__ , share_emb=lowercase__ , use_bert_emb=lowercase__ , encoder='bert' , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ , lambda lowercase__ , lowercase__ : storage ) SCREAMING_SNAKE_CASE__ : Any = AbsSummarizer(lowercase__ , torch.device('cpu' ) , lowercase__ ) original.eval() SCREAMING_SNAKE_CASE__ : List[Any] = BertAbsSummarizer(lowercase__ , torch.device('cpu' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('convert the model' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('Make sure that the models\' outputs are identical' ) SCREAMING_SNAKE_CASE__ : Any = BertTokenizer.from_pretrained('bert-base-uncased' ) # prepare the model inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode('This is sample éàalj\'-.' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor(lowercase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode('This is sample 3 éàalj\'-.' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor(lowercase__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE__ : int = encoder_input_ids SCREAMING_SNAKE_CASE__ : Any = decoder_input_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE__ : Optional[Any] = original(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = original.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = new_model( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = new_model.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.allclose(lowercase__ , lowercase__ , atol=1E-3 ) if are_identical: logging.info('all weights are equal up to 1e-3' ) else: raise ValueError('the weights are different. The new model is likely different from the original one.' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('saving the model\'s state dictionary' ) torch.save( new_model.state_dict() , './bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() parser.add_argument( "--bertabs_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model.", ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
85
1
# Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib SCREAMING_SNAKE_CASE__ : List[Any] = get_logger() SCREAMING_SNAKE_CASE__ : Optional[dict] = None class snake_case ( TensorFormatter[Mapping, 'jax.Array', Mapping] ): def __init__( self : Any , a_ : Dict=None , a_ : Dict=None , **a_ : Optional[int] )-> Tuple: """simple docstring""" super().__init__(features=a_ ) import jax from jaxlib.xla_client import Device if isinstance(a_ , a_ ): raise ValueError( F'''Expected {device} to be a `str` not {type(a_ )}, as `jaxlib.xla_extension.Device` ''' 'is not serializable neither with `pickle` nor with `dill`. Instead you can surround ' 'the device with `str()` to get its string identifier that will be internally mapped ' 'to the actual `jaxlib.xla_extension.Device`.' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = device if isinstance(a_ , a_ ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: SCREAMING_SNAKE_CASE__ : List[Any] = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F'''Device with string identifier {self.device} not listed among the available ''' F'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ''' F'''device: {str(jax.devices()[0] )}.''' ) SCREAMING_SNAKE_CASE__ : Tuple = str(jax.devices()[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = jnp_array_kwargs @staticmethod def __lowercase( )-> Dict[str, "jaxlib.xla_extension.Device"]: """simple docstring""" import jax return {str(a_ ): device for device in jax.devices()} def __lowercase( self : str , a_ : Dict )-> List[str]: """simple docstring""" import jax import jax.numpy as jnp if isinstance(a_ , a_ ) and column: if all( isinstance(a_ , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(a_ , axis=0 ) return column def __lowercase( self : int , a_ : Union[str, Any] )-> Union[str, Any]: """simple docstring""" import jax import jax.numpy as jnp if isinstance(a_ , (str, bytes, type(a_ )) ): return value elif isinstance(a_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() SCREAMING_SNAKE_CASE__ : Optional[int] = {} if isinstance(a_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: SCREAMING_SNAKE_CASE__ : str = {'dtype': jnp.intaa} else: SCREAMING_SNAKE_CASE__ : List[Any] = {'dtype': jnp.intaa} elif isinstance(a_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): SCREAMING_SNAKE_CASE__ : Optional[int] = {'dtype': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(a_ , PIL.Image.Image ): SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: SCREAMING_SNAKE_CASE__ : Optional[int] = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(a_ , **{**default_dtype, **self.jnp_array_kwargs} ) def __lowercase( self : Optional[Any] , a_ : Any )-> Union[str, Any]: """simple docstring""" import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(a_ , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(a_ , '__array__' ) and not isinstance(a_ , jax.Array ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(a_ , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(a_ ) for substruct in data_struct] ) elif isinstance(a_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(a_ ) for substruct in data_struct] ) return self._tensorize(a_ ) def __lowercase( self : Union[str, Any] , a_ : dict )-> List[str]: """simple docstring""" return map_nested(self._recursive_tensorize , a_ , map_list=a_ ) def __lowercase( self : Dict , a_ : pa.Table )-> Mapping: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.numpy_arrow_extractor().extract_row(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.python_features_decoder.decode_row(a_ ) return self.recursive_tensorize(a_ ) def __lowercase( self : Any , a_ : pa.Table )-> "jax.Array": """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.numpy_arrow_extractor().extract_column(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.python_features_decoder.decode_column(a_ , pa_table.column_names[0] ) SCREAMING_SNAKE_CASE__ : Dict = self.recursive_tensorize(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self._consolidate(a_ ) return column def __lowercase( self : Optional[int] , a_ : pa.Table )-> Mapping: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.numpy_arrow_extractor().extract_batch(a_ ) SCREAMING_SNAKE_CASE__ : str = self.python_features_decoder.decode_batch(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.recursive_tensorize(a_ ) for column_name in batch: SCREAMING_SNAKE_CASE__ : Tuple = self._consolidate(batch[column_name] ) return batch
85
from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case : def __init__( self : Tuple , a_ : int , a_ : Optional[int]=3 , a_ : Tuple=32 , a_ : Any=3 , a_ : Tuple=10 , a_ : Optional[int]=[10, 20, 30, 40] , a_ : List[Any]=[1, 1, 2, 1] , a_ : int=True , a_ : Optional[Any]=True , a_ : Any="relu" , a_ : int=3 , a_ : List[Any]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Tuple = embeddings_size SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : str = len(a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_config() return config, pixel_values, labels def __lowercase( self : str )-> str: """simple docstring""" 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 , ) def __lowercase( self : List[str] , a_ : int , a_ : Any , a_ : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFRegNetModel(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , training=a_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase( self : Union[str, Any] , a_ : Dict , a_ : int , a_ : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetForImageClassification(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ , training=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowercase_ = ( {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification} if is_tf_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self , config_class=a_ , has_text_modality=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" pass def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" def check_hidden_states_output(a_ : int , a_ : Union[str, Any] , a_ : Tuple ): SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(a_ , a_ ) , training=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(a_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE__ : List[Any] = layer_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True check_hidden_states_output(a_ , a_ , a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(a_ : str , a_ : Tuple , a_ : Optional[int] , a_ : Union[str, Any]={} ): SCREAMING_SNAKE_CASE__ : int = model(a_ , return_dict=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , return_dict=a_ , **a_ ).to_tuple() def recursive_check(a_ : List[Any] , a_ : int ): if isinstance(a_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a_ , a_ ): recursive_check(a_ , a_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(a_ , a_ ) ) , msg=( 'Tuple and dict output are not equal. Difference:' F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(a_ , a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def __lowercase( self : Any )-> List[str]: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFRegNetModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : List[Any] )-> int: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=a_ , return_tensors='tf' ) # forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ , training=a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , a_ , atol=1e-4 )
85
1
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.mean(1 ) # Centralize the data of class i SCREAMING_SNAKE_CASE__ : Optional[Any] = data - column_reshape(lowercase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowercase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : Any = np.dot(lowercase__ , centered_data.T ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = features.mean(1 ) SCREAMING_SNAKE_CASE__ : List[str] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.shape[1] SCREAMING_SNAKE_CASE__ : List[Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : str = device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' if features.any(): SCREAMING_SNAKE_CASE__ : Any = features.mean(1 ) # Center the dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = features - np.reshape(lowercase__ , (data_mean.size, 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(lowercase__ , centered_data.T ) / features.shape[1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = np.linalg.eigh(lowercase__ ) # Take all the columns in the reverse order (-1), and then takes only the first SCREAMING_SNAKE_CASE__ : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.dot(filtered_eigenvectors.T , lowercase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = eigh( covariance_between_classes(lowercase__ , lowercase__ , lowercase__ ) , covariance_within_classes(lowercase__ , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = eigenvectors[:, ::-1][:, :dimensions] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.svd(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = svd_matrix[:, 0:dimensions] SCREAMING_SNAKE_CASE__ : int = np.dot(filtered_svd_matrix.T , lowercase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 0, 0, 1, 1] ) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : Optional[int] = linear_discriminant_analysis( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : int = principal_component_analysis(lowercase__ , lowercase__ ) if not np.allclose(lowercase__ , lowercase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy SCREAMING_SNAKE_CASE__ : Dict = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__ : List[str] = "pytorch_model.bin" @dataclasses.dataclass class snake_case : lowercase_ = dataclasses.field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models.'} ) lowercase_ = dataclasses.field( default=UpperCamelCase_ , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co.'} , ) @dataclasses.dataclass class snake_case : lowercase_ = dataclasses.field(metadata={'help': 'A csv or a json file containing the training data.'} ) lowercase_ = dataclasses.field(metadata={'help': 'A csv or a json file containing the data to predict on.'} ) lowercase_ = dataclasses.field( default=UpperCamelCase_ , metadata={'help': 'A csv or a json file containing the validation data.'} ) lowercase_ = dataclasses.field( default=UpperCamelCase_ , metadata={'help': 'The name of the task to train on.'} , ) lowercase_ = dataclasses.field( default=UpperCamelCase_ , metadata={'help': 'The list of labels for the task.'} ) @dataclasses.dataclass class snake_case : lowercase_ = dataclasses.field( metadata={'help': 'The output directory where the model predictions and checkpoints will be written.'} ) lowercase_ = dataclasses.field( default='accuracy' , metadata={'help': 'The evaluation metric used for the task.'} ) lowercase_ = dataclasses.field( default='no' , metadata={ 'help': 'The evaluation strategy to adopt during training. Possible values are: ["no", "step", "epoch]' } , ) lowercase_ = dataclasses.field( default=10 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , ) lowercase_ = dataclasses.field( default=0.0 , metadata={ 'help': 'How much the specified evaluation metric must improve to satisfy early stopping conditions.' } , ) lowercase_ = dataclasses.field( default=UpperCamelCase_ , metadata={'help': 'Whether to filter the pseudo-labeled data based on the confidence score.'} , ) lowercase_ = dataclasses.field( default=UpperCamelCase_ , metadata={'help': 'Whether to filter the pseudo-labeled data based on the validation performance.'} , ) lowercase_ = dataclasses.field( default=UpperCamelCase_ , metadata={'help': 'Whether to fine-tune on labeled data after pseudo training.'} , ) lowercase_ = dataclasses.field( default=0.0 , metadata={'help': 'Confidence threshold for pseudo-labeled data filtering.'} , ) lowercase_ = dataclasses.field( default=100 , metadata={'help': 'Number of evaluation calls with no improvement after which training will be stopped.'} , ) lowercase_ = dataclasses.field( default=UpperCamelCase_ , metadata={'help': 'Random seed for initialization.'} , ) def _a ( lowercase__ : Optional[Any] , lowercase__ : Tuple , lowercase__ : Optional[int] , lowercase__ : Tuple , lowercase__ : Any , lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: SCREAMING_SNAKE_CASE__ : Any = dataset.filter(lambda lowercase__ : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 SCREAMING_SNAKE_CASE__ : List[str] = int(eval_result * len(lowercase__ ) ) print(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = dataset.sort('probability' , reverse=lowercase__ ) SCREAMING_SNAKE_CASE__ : int = dataset.select(range(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Any = dataset.remove_columns(['label', 'probability'] ) SCREAMING_SNAKE_CASE__ : Dict = dataset.rename_column('prediction' , 'label' ) SCREAMING_SNAKE_CASE__ : List[str] = dataset.map(lambda lowercase__ : {"label": idalabel[example["label"]]} ) SCREAMING_SNAKE_CASE__ : Any = dataset.shuffle(seed=args.seed ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(lowercase__ , f'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(lowercase__ , index=lowercase__ ) else: dataset.to_json(lowercase__ ) def _a ( lowercase__ : Union[str, Any] , lowercase__ : str , lowercase__ : Tuple , lowercase__ : int , **lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() SCREAMING_SNAKE_CASE__ : Dict = STModelArguments(model_name_or_path=lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = STDataArguments(train_file=lowercase__ , infer_file=lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = STTrainingArguments(output_dir=lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(lowercase__ ).items(): setattr(lowercase__ , lowercase__ , lowercase__ ) for key, value in kwargs.items(): if hasattr(lowercase__ , lowercase__ ): setattr(lowercase__ , lowercase__ , lowercase__ ) # Sanity checks SCREAMING_SNAKE_CASE__ : List[Any] = {} SCREAMING_SNAKE_CASE__ : Optional[Any] = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None SCREAMING_SNAKE_CASE__ : Optional[int] = args.train_file SCREAMING_SNAKE_CASE__ : Tuple = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None SCREAMING_SNAKE_CASE__ : Tuple = args.eval_file for key in data_files: SCREAMING_SNAKE_CASE__ : str = data_files[key].split('.' )[-1] assert extension in ["csv", "json"], f'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: SCREAMING_SNAKE_CASE__ : Tuple = extension else: assert extension == args.data_file_extension, f'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), f'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info('Creating the initial data directory for self-training...' ) SCREAMING_SNAKE_CASE__ : List[Any] = f'''{args.output_dir}/self-train_iter-{{}}'''.format SCREAMING_SNAKE_CASE__ : Optional[Any] = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=lowercase__ ) os.makedirs(lowercase__ , exist_ok=lowercase__ ) accelerator.wait_for_everyone() SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Optional[int] = None SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : Optional[int] = False # Show the progress bar SCREAMING_SNAKE_CASE__ : Optional[int] = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): SCREAMING_SNAKE_CASE__ : Optional[int] = data_dir_format(lowercase__ ) assert os.path.exists(lowercase__ ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join(lowercase__ , 'stage-1' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { 'accelerator': accelerator, 'model_name_or_path': args.model_name_or_path, 'cache_dir': args.cache_dir, 'do_train': True, 'train_file': data_files['train'] if iteration == 0 else data_files['train_pseudo'], 'do_eval': True if args.eval_file is not None else False, 'eval_file': data_files['eval'], 'do_predict': True, 'infer_file': data_files['infer'], 'task_name': args.task_name, 'label_list': args.label_list, 'output_dir': current_output_dir, 'eval_metric': args.eval_metric, 'evaluation_strategy': args.evaluation_strategy, 'early_stopping_patience': args.early_stopping_patience, 'early_stopping_threshold': args.early_stopping_threshold, 'seed': args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(lowercase__ , lowercase__ ): arguments_dict.update({key: value} ) SCREAMING_SNAKE_CASE__ : Any = os.path.join(lowercase__ , 'best-checkpoint' , lowercase__ ) if os.path.exists(lowercase__ ): logger.info( 'Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1.' , lowercase__ , lowercase__ , ) else: logger.info('***** Running self-training: iteration: %d, stage: 1 *****' , lowercase__ ) finetune(**lowercase__ ) accelerator.wait_for_everyone() assert os.path.exists(lowercase__ ) logger.info('Self-training job completed: iteration: %d, stage: 1.' , lowercase__ ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data SCREAMING_SNAKE_CASE__ : int = os.path.join(lowercase__ , 'best-checkpoint' ) SCREAMING_SNAKE_CASE__ : List[Any] = os.path.join(lowercase__ , 'stage-2' ) # Update arguments_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = model_path SCREAMING_SNAKE_CASE__ : List[Any] = data_files['train'] SCREAMING_SNAKE_CASE__ : str = current_output_dir SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(lowercase__ , 'best-checkpoint' , lowercase__ ) if os.path.exists(lowercase__ ): logger.info( 'Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2.' , lowercase__ , lowercase__ , ) else: logger.info('***** Running self-training: iteration: %d, stage: 2 *****' , lowercase__ ) finetune(**lowercase__ ) accelerator.wait_for_everyone() assert os.path.exists(lowercase__ ) logger.info('Self-training job completed: iteration: %d, stage: 2.' , lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = iteration SCREAMING_SNAKE_CASE__ : List[str] = data_dir_format(iteration + 1 ) SCREAMING_SNAKE_CASE__ : Dict = AutoConfig.from_pretrained(os.path.join(lowercase__ , 'best-checkpoint' ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = config.idalabel SCREAMING_SNAKE_CASE__ : int = os.path.join(lowercase__ , 'eval_results_best-checkpoint.json' ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(lowercase__ , 'test_results_best-checkpoint.json' ) assert os.path.exists(lowercase__ ) with open(lowercase__ , 'r' ) as f: SCREAMING_SNAKE_CASE__ : Dict = float(json.load(lowercase__ )[args.eval_metric] ) SCREAMING_SNAKE_CASE__ : Any = os.path.join(lowercase__ , 'infer_output_best-checkpoint.csv' ) assert os.path.exists(lowercase__ ) # Loading the dataset from local csv or json files. SCREAMING_SNAKE_CASE__ : Optional[Any] = load_dataset(args.data_file_extension , data_files={'data': data_files['infer']} )['data'] SCREAMING_SNAKE_CASE__ : Any = load_dataset('csv' , data_files={'data': infer_output_file} )['data'] if accelerator.is_main_process: os.makedirs(lowercase__ , exist_ok=lowercase__ ) shutil.copy(lowercase__ , os.path.join(lowercase__ , f'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(lowercase__ ): shutil.copy(lowercase__ , os.path.join(lowercase__ , f'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) accelerator.wait_for_everyone() SCREAMING_SNAKE_CASE__ : int = os.path.join(lowercase__ , f'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: SCREAMING_SNAKE_CASE__ : str = eval_result if best_iteration is None: SCREAMING_SNAKE_CASE__ : Any = new_iteration SCREAMING_SNAKE_CASE__ : List[str] = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: SCREAMING_SNAKE_CASE__ : Tuple = new_iteration SCREAMING_SNAKE_CASE__ : Dict = new_eval_result SCREAMING_SNAKE_CASE__ : Any = 0 else: if new_eval_result == best_eval_result: SCREAMING_SNAKE_CASE__ : Tuple = new_iteration SCREAMING_SNAKE_CASE__ : Optional[Any] = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: SCREAMING_SNAKE_CASE__ : List[Any] = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info('Best iteration: %d' , lowercase__ ) logger.info('Best evaluation result: %s = %f' , args.eval_metric , lowercase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase__ , f'''eval_results_iter-{iteration}.json''' ) , os.path.join(lowercase__ , 'eval_results_best-iteration.json' ) , ) else: # Assume that the last iteration is the best logger.info('Best iteration: %d' , args.max_selftrain_iterations - 1 ) logger.info('Best evaluation result: %s = %f' , args.eval_metric , lowercase__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(lowercase__ , f'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(lowercase__ , 'eval_results_best-iteration.json' ) , )
85
def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) if n == 0: return 0 SCREAMING_SNAKE_CASE__ : str = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : int = max( lowercase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase__ ) ) return max_revue def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : str = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : list , lowercase__ : list ): '''simple docstring''' if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: SCREAMING_SNAKE_CASE__ : List[str] = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Any = max( lowercase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = max_revenue return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. SCREAMING_SNAKE_CASE__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : int = 0 for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(lowercase__ , prices[j - 1] + max_rev[i - j] ) SCREAMING_SNAKE_CASE__ : Dict = max_revenue_i return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' if n < 0: SCREAMING_SNAKE_CASE__ : Tuple = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowercase__ ) if n > len(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = ( 'Each integral piece of rod must have a corresponding price. ' f'''Got n = {n} but length of prices = {len(lowercase__ )}''' ) raise ValueError(lowercase__ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [6, 10, 12, 15, 20, 23] SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. SCREAMING_SNAKE_CASE__ : Optional[Any] = 36 SCREAMING_SNAKE_CASE__ : Tuple = top_down_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = bottom_up_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = naive_cut_rod_recursive(lowercase__ , lowercase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
85
1
import os from typing import List, Optional, Union from ...image_processing_utils import BatchFeature from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType from ..auto import AutoTokenizer class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'BlipImageProcessor' lowercase_ = 'AutoTokenizer' def __init__( self : List[str] , a_ : List[Any] , a_ : Any , a_ : Union[str, Any] )-> Dict: """simple docstring""" super().__init__(a_ , a_ ) # add QFormer tokenizer SCREAMING_SNAKE_CASE__ : Tuple = qformer_tokenizer def __call__( self : Any , a_ : ImageInput = None , a_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , a_ : bool = True , a_ : Union[bool, str, PaddingStrategy] = False , a_ : Union[bool, str, TruncationStrategy] = None , a_ : Optional[int] = None , a_ : int = 0 , a_ : Optional[int] = None , a_ : Optional[bool] = None , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = True , a_ : Optional[Union[str, TensorType]] = None , **a_ : str , )-> BatchFeature: """simple docstring""" if images is None and text is None: raise ValueError('You have to specify at least images or text.' ) SCREAMING_SNAKE_CASE__ : List[str] = BatchFeature() if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer( text=a_ , add_special_tokens=a_ , padding=a_ , truncation=a_ , max_length=a_ , stride=a_ , pad_to_multiple_of=a_ , return_attention_mask=a_ , return_overflowing_tokens=a_ , return_special_tokens_mask=a_ , return_offsets_mapping=a_ , return_token_type_ids=a_ , return_length=a_ , verbose=a_ , return_tensors=a_ , **a_ , ) encoding.update(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.qformer_tokenizer( text=a_ , add_special_tokens=a_ , padding=a_ , truncation=a_ , max_length=a_ , stride=a_ , pad_to_multiple_of=a_ , return_attention_mask=a_ , return_overflowing_tokens=a_ , return_special_tokens_mask=a_ , return_offsets_mapping=a_ , return_token_type_ids=a_ , return_length=a_ , verbose=a_ , return_tensors=a_ , **a_ , ) SCREAMING_SNAKE_CASE__ : List[str] = qformer_text_encoding.pop('input_ids' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = qformer_text_encoding.pop('attention_mask' ) if images is not None: SCREAMING_SNAKE_CASE__ : Tuple = self.image_processor(a_ , return_tensors=a_ ) encoding.update(a_ ) return encoding def __lowercase( self : List[str] , *a_ : str , **a_ : Optional[Any] )-> Dict: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : int , *a_ : str , **a_ : str )-> Optional[int]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def __lowercase( self : Optional[int] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) def __lowercase( self : int , a_ : Optional[int] , **a_ : Optional[Any] )-> Tuple: """simple docstring""" if os.path.isfile(a_ ): raise ValueError(F'''Provided path ({save_directory}) should be a directory, not a file''' ) os.makedirs(a_ , exist_ok=a_ ) SCREAMING_SNAKE_CASE__ : str = os.path.join(a_ , 'qformer_tokenizer' ) self.qformer_tokenizer.save_pretrained(a_ ) return super().save_pretrained(a_ , **a_ ) @classmethod def __lowercase( cls : Optional[int] , a_ : int , **a_ : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = AutoTokenizer.from_pretrained(a_ , subfolder='qformer_tokenizer' ) SCREAMING_SNAKE_CASE__ : Any = cls._get_arguments_from_pretrained(a_ , **a_ ) args.append(a_ ) return cls(*a_ )
85
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") SCREAMING_SNAKE_CASE__ : Any = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = CamembertTokenizer lowercase_ = CamembertTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Tuple )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Dict = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = '<pad>' SCREAMING_SNAKE_CASE__ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(a_ ) , 1004 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE__ : str = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=a_ , )
85
1
SCREAMING_SNAKE_CASE__ : Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE__ : List[Any] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] SCREAMING_SNAKE_CASE__ : List[str] = { 0: "Sunday", 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", } def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert len(str(lowercase__ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: SCREAMING_SNAKE_CASE__ : List[Any] = year // 1_00 SCREAMING_SNAKE_CASE__ : str = (5 * (century % 4) + 2) % 7 SCREAMING_SNAKE_CASE__ : int = year % 1_00 SCREAMING_SNAKE_CASE__ : Union[str, Any] = centurian % 12 SCREAMING_SNAKE_CASE__ : Any = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 SCREAMING_SNAKE_CASE__ : Tuple = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) SCREAMING_SNAKE_CASE__ : Any = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
85
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable SCREAMING_SNAKE_CASE__ : Any = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["DPTFeatureExtractor"] SCREAMING_SNAKE_CASE__ : Tuple = ["DPTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST", "DPTForDepthEstimation", "DPTForSemanticSegmentation", "DPTModel", "DPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
def _a ( lowercase__ : int , lowercase__ : float , lowercase__ : float ): '''simple docstring''' return round(float(moles / volume ) * nfactor ) def _a ( lowercase__ : float , lowercase__ : float , lowercase__ : float ): '''simple docstring''' return round(float((moles * 0.0821 * temperature) / (volume) ) ) def _a ( lowercase__ : float , lowercase__ : float , lowercase__ : float ): '''simple docstring''' return round(float((moles * 0.0821 * temperature) / (pressure) ) ) def _a ( lowercase__ : float , lowercase__ : float , lowercase__ : float ): '''simple docstring''' return round(float((pressure * volume) / (0.0821 * moles) ) ) if __name__ == "__main__": import doctest doctest.testmod()
85
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 SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : int = 8 , **a_ : Union[str, Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = do_rescale SCREAMING_SNAKE_CASE__ : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Dict = do_pad SCREAMING_SNAKE_CASE__ : Any = pad_size def __lowercase( self : str , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : str )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = get_image_size(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE__ : List[Any] = (old_width // size + 1) * size - old_width return pad(a_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a_ ) def __lowercase( self : Tuple , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Dict , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : List[str] = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE__ : List[str] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE__ : Tuple = make_list_of_images(a_ ) if not valid_images(a_ ): 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. SCREAMING_SNAKE_CASE__ : List[str] = [to_numpy_array(a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE__ : str = [self.pad(a_ , size=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
85
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Dict = { "configuration_pegasus_x": ["PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP", "PegasusXConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST", "PegasusXForConditionalGeneration", "PegasusXModel", "PegasusXPreTrainedModel", ] if TYPE_CHECKING: from .configuration_pegasus_x import PEGASUS_X_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusXConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pegasus_x import ( PEGASUS_X_PRETRAINED_MODEL_ARCHIVE_LIST, PegasusXForConditionalGeneration, PegasusXModel, PegasusXPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
from pathlib import Path import numpy as np from PIL import Image def _a ( lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return (gray > 1_27) & (gray <= 2_55) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros_like(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE__ : Optional[Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE__ : List[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE__ : List[str] = int(summation > 0 ) return output if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE__ : int = Path(__file__).resolve().parent / "image_data" / "lena.jpg" SCREAMING_SNAKE_CASE__ : int = np.array(Image.open(lena_path)) # kernel to be applied SCREAMING_SNAKE_CASE__ : str = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) SCREAMING_SNAKE_CASE__ : Optional[int] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image SCREAMING_SNAKE_CASE__ : Optional[int] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
85
1
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs SCREAMING_SNAKE_CASE__ : int = imread(r"digital_image_processing/image_data/lena_small.jpg") SCREAMING_SNAKE_CASE__ : List[Any] = cvtColor(img, COLOR_BGR2GRAY) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = cn.convert_to_negative(lowercase__ ) # assert negative_img array for at least one True assert negative_img.any() def _a ( ): '''simple docstring''' with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowercase__ , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ : List[str] = canny.canny(lowercase__ ) # assert canny array for at least one True assert canny_array.any() def _a ( ): '''simple docstring''' assert gg.gaussian_filter(lowercase__ , 5 , sigma=0.9 ).all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) SCREAMING_SNAKE_CASE__ : Tuple = conv.img_convolve(lowercase__ , lowercase__ ).astype(lowercase__ ) assert res.any() def _a ( ): '''simple docstring''' assert med.median_filter(lowercase__ , 3 ).any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = sob.sobel_filter(lowercase__ ) assert grad.any() and theta.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = sp.make_sepia(lowercase__ , 20 ) assert sepia.all() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = bs.Burkes(imread(lowercase__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = rs.NearestNeighbour(imread(lowercase__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ : Dict = imread(lowercase__ , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ : List[Any] = lbp.get_neighbors_pixel( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): SCREAMING_SNAKE_CASE__ : str = lbp.local_binary_value(lowercase__ , lowercase__ , lowercase__ ) assert lbp_image.any()
85
def _a ( lowercase__ : int = 60_08_51_47_51_43 ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Dict = int(lowercase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : int = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 SCREAMING_SNAKE_CASE__ : str = i while n % i == 0: SCREAMING_SNAKE_CASE__ : List[Any] = n // i i += 1 return int(lowercase__ ) if __name__ == "__main__": print(F"""{solution() = }""")
85
1
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) class snake_case : lowercase_ = None @experimental def _a ( lowercase__ : Any , lowercase__ : Optional[int] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Optional[Any] , lowercase__ : List[Any] , lowercase__ : str ): '''simple docstring''' if ParallelBackendConfig.backend_name is None: return _map_with_multiprocessing_pool( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) return _map_with_joblib(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : Any , lowercase__ : Dict , lowercase__ : str , lowercase__ : Optional[Any] , lowercase__ : Optional[Any] , lowercase__ : List[Any] , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_proc if num_proc <= len(lowercase__ ) else len(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = [] # We organize the splits ourselve (contiguous splits) for index in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : List[Any] = len(lowercase__ ) // num_proc SCREAMING_SNAKE_CASE__ : Dict = len(lowercase__ ) % num_proc SCREAMING_SNAKE_CASE__ : List[str] = div * index + min(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = start + div + (1 if index < mod else 0) split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc) ) if len(lowercase__ ) != sum(len(i[1] ) for i in split_kwds ): raise ValueError( f'''Error dividing inputs iterable among processes. ''' f'''Total number of objects {len(lowercase__ )}, ''' f'''length: {sum(len(i[1] ) for i in split_kwds )}''' ) logger.info( f'''Spawning {num_proc} processes for {len(lowercase__ )} objects in slices of {[len(i[1] ) for i in split_kwds]}''' ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = None, None if not disable_tqdm: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = (RLock(),), tqdm.set_lock with Pool(lowercase__ , initargs=lowercase__ , initializer=lowercase__ ) as pool: SCREAMING_SNAKE_CASE__ : Union[str, Any] = pool.map(lowercase__ , lowercase__ ) logger.info(f'''Finished {num_proc} processes''' ) SCREAMING_SNAKE_CASE__ : Tuple = [obj for proc_res in mapped for obj in proc_res] logger.info(f'''Unpacked {len(lowercase__ )} objects''' ) return mapped def _a ( lowercase__ : List[str] , lowercase__ : str , lowercase__ : List[str] , lowercase__ : List[Any] , lowercase__ : Union[str, Any] , lowercase__ : List[str] , lowercase__ : Optional[Any] ): '''simple docstring''' import joblib with joblib.parallel_backend(ParallelBackendConfig.backend_name , n_jobs=lowercase__ ): return joblib.Parallel()( joblib.delayed(lowercase__ )((function, obj, types, None, True, None) ) for obj in iterable ) @experimental @contextlib.contextmanager def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = backend_name if backend_name == "spark": from joblibspark import register_spark register_spark() # TODO: call create_cache_and_write_probe if "download" in steps # TODO: raise NotImplementedError when Dataset.map etc is called try: yield finally: SCREAMING_SNAKE_CASE__ : Tuple = None
85
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = int(lowercase__ ) if n_element < 1: SCREAMING_SNAKE_CASE__ : Tuple = ValueError('a should be a positive number' ) raise my_error SCREAMING_SNAKE_CASE__ : Any = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = (0, 0, 0) SCREAMING_SNAKE_CASE__ : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") SCREAMING_SNAKE_CASE__ : int = hamming(int(n)) print("-----------------------------------------------------") print(F"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
85
1
def _a ( lowercase__ : str ): '''simple docstring''' assert column_title.isupper() SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : List[Any] = len(lowercase__ ) - 1 SCREAMING_SNAKE_CASE__ : str = 0 while index >= 0: SCREAMING_SNAKE_CASE__ : Union[str, Any] = (ord(column_title[index] ) - 64) * pow(26 , lowercase__ ) answer += value power += 1 index -= 1 return answer if __name__ == "__main__": from doctest import testmod testmod()
85
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
from __future__ import annotations def _a ( lowercase__ : list ): '''simple docstring''' if not nums: raise ValueError('List is empty' ) return sum(lowercase__ ) / len(lowercase__ ) if __name__ == "__main__": import doctest doctest.testmod()
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
# # This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or # many nodes) can talk to each other via nccl and allocate gpu memory. # # To run first adjust the number of processes and nodes: # # python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port # # You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d # # use torch.distributed.launch instead of torch.distributed.run for torch < 1.9 # # If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with: # # NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py # # which should tell you what's going on behind the scenes. # # # This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that # runs on 2 nodes of 4 gpus per node: # # #SBATCH --job-name=test-nodes # name # #SBATCH --nodes=2 # nodes # #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node! # #SBATCH --cpus-per-task=10 # number of cores per tasks # #SBATCH --gres=gpu:4 # number of gpus # #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS) # #SBATCH --output=%x-%j.out # output file name # # GPUS_PER_NODE=4 # MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) # MASTER_PORT=6000 # # srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \ # --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \ # --master_addr $MASTER_ADDR --master_port $MASTER_PORT \ # torch-distributed-gpu-test.py' # import fcntl import os import socket import torch import torch.distributed as dist def _a ( *lowercase__ : List[str] ): '''simple docstring''' with open(lowercase__ , 'r' ) as fh: fcntl.flock(lowercase__ , fcntl.LOCK_EX ) try: print(*lowercase__ ) finally: fcntl.flock(lowercase__ , fcntl.LOCK_UN ) SCREAMING_SNAKE_CASE__ : int = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(local_rank) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.device("cuda", local_rank) SCREAMING_SNAKE_CASE__ : Dict = socket.gethostname() SCREAMING_SNAKE_CASE__ : str = F"""[{hostname}-{local_rank}]""" try: # test distributed dist.init_process_group("nccl") dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank SCREAMING_SNAKE_CASE__ : str = dist.get_rank() SCREAMING_SNAKE_CASE__ : List[str] = dist.get_world_size() printflock(F"""{gpu} is OK (global rank: {rank}/{world_size})""") dist.barrier() if rank == 0: printflock(F"""pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}""") except Exception: printflock(F"""{gpu} is broken""") raise
85
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs SCREAMING_SNAKE_CASE__ : int = imread(r"digital_image_processing/image_data/lena_small.jpg") SCREAMING_SNAKE_CASE__ : List[Any] = cvtColor(img, COLOR_BGR2GRAY) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = cn.convert_to_negative(lowercase__ ) # assert negative_img array for at least one True assert negative_img.any() def _a ( ): '''simple docstring''' with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowercase__ , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ : List[str] = canny.canny(lowercase__ ) # assert canny array for at least one True assert canny_array.any() def _a ( ): '''simple docstring''' assert gg.gaussian_filter(lowercase__ , 5 , sigma=0.9 ).all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) SCREAMING_SNAKE_CASE__ : Tuple = conv.img_convolve(lowercase__ , lowercase__ ).astype(lowercase__ ) assert res.any() def _a ( ): '''simple docstring''' assert med.median_filter(lowercase__ , 3 ).any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = sob.sobel_filter(lowercase__ ) assert grad.any() and theta.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = sp.make_sepia(lowercase__ , 20 ) assert sepia.all() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = bs.Burkes(imread(lowercase__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = rs.NearestNeighbour(imread(lowercase__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ : Dict = imread(lowercase__ , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ : List[Any] = lbp.get_neighbors_pixel( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): SCREAMING_SNAKE_CASE__ : str = lbp.local_binary_value(lowercase__ , lowercase__ , lowercase__ ) assert lbp_image.any()
85
1
from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): import torch from transformers.modeling_outputs import BaseModelOutput from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase_ ) class snake_case ( UpperCamelCase_ ): def __init__( self : List[Any] , **a_ : str )-> Any: """simple docstring""" super().__init__(**a_ ) if self.framework == "tf": raise ValueError(F'''The {self.__class__} is only available in PyTorch.''' ) requires_backends(self , 'vision' ) self.check_model_type(a_ ) def __call__( self : Optional[Any] , a_ : Union[str, "Image.Image", List[Dict[str, Any]]] , a_ : Union[str, List[str]] = None , **a_ : Dict , )-> Optional[Any]: """simple docstring""" if "text_queries" in kwargs: SCREAMING_SNAKE_CASE__ : Dict = kwargs.pop('text_queries' ) if isinstance(a_ , (str, Image.Image) ): SCREAMING_SNAKE_CASE__ : Optional[int] = {'image': image, 'candidate_labels': candidate_labels} else: SCREAMING_SNAKE_CASE__ : Any = image SCREAMING_SNAKE_CASE__ : int = super().__call__(a_ , **a_ ) return results def __lowercase( self : Dict , **a_ : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = {} if "threshold" in kwargs: SCREAMING_SNAKE_CASE__ : Tuple = kwargs['threshold'] if "top_k" in kwargs: SCREAMING_SNAKE_CASE__ : Union[str, Any] = kwargs['top_k'] return {}, {}, postprocess_params def __lowercase( self : Dict , a_ : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = load_image(inputs['image'] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['candidate_labels'] if isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : Any = candidate_labels.split(',' ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor([[image.height, image.width]] , dtype=torch.intaa ) for i, candidate_label in enumerate(a_ ): SCREAMING_SNAKE_CASE__ : List[str] = self.tokenizer(a_ , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : List[str] = self.image_processor(a_ , return_tensors=self.framework ) yield { "is_last": i == len(a_ ) - 1, "target_size": target_size, "candidate_label": candidate_label, **text_inputs, **image_features, } def __lowercase( self : Any , a_ : Any )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = model_inputs.pop('target_size' ) SCREAMING_SNAKE_CASE__ : Tuple = model_inputs.pop('candidate_label' ) SCREAMING_SNAKE_CASE__ : Any = model_inputs.pop('is_last' ) SCREAMING_SNAKE_CASE__ : int = self.model(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = {'target_size': target_size, 'candidate_label': candidate_label, 'is_last': is_last, **outputs} return model_outputs def __lowercase( self : List[Any] , a_ : List[str] , a_ : Any=0.1 , a_ : Optional[int]=None )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = [] for model_output in model_outputs: SCREAMING_SNAKE_CASE__ : List[Any] = model_output['candidate_label'] SCREAMING_SNAKE_CASE__ : Optional[Any] = BaseModelOutput(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.image_processor.post_process_object_detection( outputs=a_ , threshold=a_ , target_sizes=model_output['target_size'] )[0] for index in outputs["scores"].nonzero(): SCREAMING_SNAKE_CASE__ : Dict = outputs['scores'][index].item() SCREAMING_SNAKE_CASE__ : int = self._get_bounding_box(outputs['boxes'][index][0] ) SCREAMING_SNAKE_CASE__ : Dict = {'score': score, 'label': label, 'box': box} results.append(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = sorted(a_ , key=lambda a_ : x["score"] , reverse=a_ ) if top_k: SCREAMING_SNAKE_CASE__ : Any = results[:top_k] return results def __lowercase( self : Tuple , a_ : "torch.Tensor" )-> Dict[str, int]: """simple docstring""" if self.framework != "pt": raise ValueError('The ZeroShotObjectDetectionPipeline is only available in PyTorch.' ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = box.int().tolist() SCREAMING_SNAKE_CASE__ : List[Any] = { 'xmin': xmin, 'ymin': ymin, 'xmax': xmax, 'ymax': ymax, } return bbox
85
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu SCREAMING_SNAKE_CASE__ : Any = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: SCREAMING_SNAKE_CASE__ : Tuple = json.load(f) @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : List[str] , a_ : Any )-> str: """simple docstring""" return FSMTTokenizer.from_pretrained(a_ ) def __lowercase( self : int , a_ : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FSMTForConditionalGeneration.from_pretrained(a_ ).to(a_ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['en-ru', 26.0], ['ru-en', 22.0], ['en-de', 22.0], ['de-en', 29.0], ] ) @slow def __lowercase( self : int , a_ : Optional[int] , a_ : str )-> List[str]: """simple docstring""" # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality SCREAMING_SNAKE_CASE__ : Any = F'''facebook/wmt19-{pair}''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_model(a_ ) SCREAMING_SNAKE_CASE__ : int = bleu_data[pair]['src'] SCREAMING_SNAKE_CASE__ : Optional[int] = bleu_data[pair]['tgt'] SCREAMING_SNAKE_CASE__ : Any = tokenizer(a_ , return_tensors='pt' , truncation=a_ , padding='longest' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( input_ids=batch.input_ids , num_beams=8 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.batch_decode( a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_bleu(a_ , a_ ) print(a_ ) self.assertGreaterEqual(scores['bleu'] , a_ )
85
1
import time import warnings from abc import ABC from copy import deepcopy from typing import Optional import torch from ..utils import add_start_docstrings, logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[int] = r"\n Args:\n input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax\n or scores for each vocabulary token after SoftMax.\n kwargs (`Dict[str, Any]`, *optional*):\n Additional stopping criteria specific kwargs.\n\n Return:\n `bool`. `False` indicates we should continue, `True` indicates we should stop.\n\n" class snake_case ( UpperCamelCase_ ): @add_start_docstrings(a_ ) def __call__( self : Tuple , a_ : torch.LongTensor , a_ : torch.FloatTensor , **a_ : Optional[int] )-> bool: """simple docstring""" raise NotImplementedError('StoppingCriteria needs to be subclassed' ) class snake_case ( UpperCamelCase_ ): def __init__( self : Tuple , a_ : int , a_ : Optional[int] = None )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = max_length SCREAMING_SNAKE_CASE__ : str = max_position_embeddings @add_start_docstrings(a_ ) def __call__( self : Union[str, Any] , a_ : torch.LongTensor , a_ : torch.FloatTensor , **a_ : Optional[int] )-> bool: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = input_ids.shape[-1] SCREAMING_SNAKE_CASE__ : Dict = cur_len >= self.max_length if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings: logger.warning_once( 'This is a friendly reminder - the current text generation call will exceed the model\'s predefined ' F'''maximum length ({self.max_position_embeddings}). Depending on the model, you may observe ''' 'exceptions, performance degradation, or nothing at all.' ) return is_done class snake_case ( UpperCamelCase_ ): def __init__( self : Dict , a_ : int , a_ : int )-> Optional[int]: """simple docstring""" warnings.warn( 'The class `MaxNewTokensCriteria` is deprecated. ' F'''Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` ''' 'with `max_length = start_length + max_new_tokens` instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = start_length SCREAMING_SNAKE_CASE__ : str = max_new_tokens SCREAMING_SNAKE_CASE__ : Optional[Any] = start_length + max_new_tokens @add_start_docstrings(a_ ) def __call__( self : str , a_ : torch.LongTensor , a_ : torch.FloatTensor , **a_ : int )-> bool: """simple docstring""" return input_ids.shape[-1] >= self.max_length class snake_case ( UpperCamelCase_ ): def __init__( self : List[Any] , a_ : float , a_ : Optional[float] = None )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = max_time SCREAMING_SNAKE_CASE__ : Optional[Any] = time.time() if initial_timestamp is None else initial_timestamp @add_start_docstrings(a_ ) def __call__( self : Dict , a_ : torch.LongTensor , a_ : torch.FloatTensor , **a_ : Any )-> bool: """simple docstring""" return time.time() - self.initial_timestamp > self.max_time class snake_case ( UpperCamelCase_ ): @add_start_docstrings(a_ ) def __call__( self : int , a_ : torch.LongTensor , a_ : torch.FloatTensor , **a_ : List[Any] )-> bool: """simple docstring""" return any(criteria(a_ , a_ ) for criteria in self ) @property def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" for stopping_criterium in self: if isinstance(a_ , a_ ): return stopping_criterium.max_length elif isinstance(a_ , a_ ): return stopping_criterium.max_length return None def _a ( lowercase__ : StoppingCriteriaList , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = stopping_criteria.max_length SCREAMING_SNAKE_CASE__ : int = deepcopy(lowercase__ ) if stopping_max_length is not None and stopping_max_length != max_length: warnings.warn('You set different `max_length` for stopping criteria and `max_length` parameter' , lowercase__ ) elif stopping_max_length is None: new_stopping_criteria.append(MaxLengthCriteria(max_length=lowercase__ ) ) return new_stopping_criteria
85
import os import pytest from attr import dataclass SCREAMING_SNAKE_CASE__ : int = "us-east-1" # defaults region @dataclass class snake_case : lowercase_ = 42 lowercase_ = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' lowercase_ = { 'task_name': 'mnli', 'per_device_train_batch_size': 16, 'per_device_eval_batch_size': 16, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 500, 'save_steps': 5_500, } lowercase_ = {**hyperparameters, 'max_steps': 1_000} @property def __lowercase( self : List[str] )-> str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return F'''{self.framework}-transfromers-test''' @property def __lowercase( self : int )-> str: """simple docstring""" return F'''./tests/sagemaker/scripts/{self.framework}''' @property def __lowercase( self : Tuple )-> str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def _a ( lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
85
1
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Optional[int]=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = [] # fmt: off # stem: rename_keys.append(('cls_token', 'vit.embeddings.cls_token') ) rename_keys.append(('pos_embed', 'vit.embeddings.position_embeddings') ) rename_keys.append(('patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight') ) rename_keys.append(('patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias') ) # backbone rename_keys.append(('patch_embed.backbone.stem.conv.weight', 'vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight') ) rename_keys.append(('patch_embed.backbone.stem.norm.weight', 'vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight') ) rename_keys.append(('patch_embed.backbone.stem.norm.bias', 'vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias') ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight''') ) rename_keys.append((f'''patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias''', f'''vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias''') ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''blocks.{i}.norm1.weight''', f'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''blocks.{i}.norm1.bias''', f'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((f'''blocks.{i}.attn.proj.weight''', f'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.attn.proj.bias''', f'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''blocks.{i}.norm2.weight''', f'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''blocks.{i}.norm2.bias''', f'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.weight''', f'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.bias''', f'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.weight''', f'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.bias''', f'''vit.encoder.layer.{i}.output.dense.bias''') ) if base_model: # layernorm + pooler rename_keys.extend( [ ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ('pre_logits.fc.weight', 'pooler.dense.weight'), ('pre_logits.fc.bias', 'pooler.dense.bias'), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE__ : int = [(pair[0], pair[1][4:]) if pair[1].startswith('vit' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('norm.weight', 'vit.layernorm.weight'), ('norm.bias', 'vit.layernorm.bias'), ('head.weight', 'classifier.weight'), ('head.bias', 'classifier.bias'), ] ) # fmt: on return rename_keys def _a ( lowercase__ : int , lowercase__ : Optional[Any] , lowercase__ : Optional[int]=False ): '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE__ : Any = '' else: SCREAMING_SNAKE_CASE__ : Optional[int] = 'vit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : int = state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : int = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : Tuple , lowercase__ : Dict , lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = val def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE__ : Optional[int] = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ) return im @torch.no_grad() def _a ( lowercase__ : Union[str, Any] , lowercase__ : List[str] , lowercase__ : int=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = BitConfig( global_padding='same' , layer_type='bottleneck' , depths=(3, 4, 9) , out_features=['stage3'] , embedding_dynamic_padding=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ViTHybridConfig(backbone_config=lowercase__ , image_size=3_84 , num_labels=10_00 ) SCREAMING_SNAKE_CASE__ : Any = False # load original model from timm SCREAMING_SNAKE_CASE__ : str = timm.create_model(lowercase__ , pretrained=lowercase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Union[str, Any] = timm_model.state_dict() if base_model: remove_classification_head_(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = create_rename_keys(lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : List[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Optional[Any] = idalabel SCREAMING_SNAKE_CASE__ : Union[str, Any] = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": SCREAMING_SNAKE_CASE__ : int = ViTHybridModel(lowercase__ ).eval() else: SCREAMING_SNAKE_CASE__ : Tuple = ViTHybridForImageClassification(lowercase__ ).eval() model.load_state_dict(lowercase__ ) # create image processor SCREAMING_SNAKE_CASE__ : List[Any] = create_transform(**resolve_data_config({} , model=lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = transform.transforms SCREAMING_SNAKE_CASE__ : List[Any] = { 'bilinear': PILImageResampling.BILINEAR, 'bicubic': PILImageResampling.BICUBIC, 'nearest': PILImageResampling.NEAREST, } SCREAMING_SNAKE_CASE__ : Optional[int] = ViTHybridImageProcessor( do_resize=lowercase__ , size={'shortest_edge': timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=lowercase__ , crop_size={'height': timm_transforms[1].size[0], 'width': timm_transforms[1].size[1]} , do_normalize=lowercase__ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) SCREAMING_SNAKE_CASE__ : Tuple = prepare_img() SCREAMING_SNAKE_CASE__ : Any = transform(lowercase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , return_tensors='pt' ).pixel_values # verify pixel values assert torch.allclose(lowercase__ , lowercase__ ) # verify logits with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits print('Predicted class:' , logits.argmax(-1 ).item() ) if base_model: SCREAMING_SNAKE_CASE__ : Optional[int] = timm_model.forward_features(lowercase__ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(lowercase__ , outputs.pooler_output , atol=1E-3 ) else: SCREAMING_SNAKE_CASE__ : Dict = timm_model(lowercase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowercase__ , outputs.logits , atol=1E-3 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model {vit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) print(f'''Saving processor to {pytorch_dump_folder_path}''' ) processor.save_pretrained(lowercase__ ) if push_to_hub: print(f'''Pushing model and processor to the hub {vit_name}''' ) model.push_to_hub(f'''ybelkada/{vit_name}''' ) processor.push_to_hub(f'''ybelkada/{vit_name}''' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--vit_name", default="vit_base_r50_s16_384", type=str, help="Name of the hybrid ViT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to upload the model to the HuggingFace hub." ) SCREAMING_SNAKE_CASE__ : Any = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
85
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = FunnelTokenizer lowercase_ = FunnelTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : str = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase( self : Any , **a_ : Any )-> List[str]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Tuple , **a_ : List[Any] )-> List[Any]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : int = 'unwanted, running' return input_text, output_text def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(a_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [7, 4, 5, 10, 8, 9] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer('UNwant\u00E9d,running' ) SCREAMING_SNAKE_CASE__ : List[Any] = len(inputs['input_ids'] ) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running' ) self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len )
85
1
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") SCREAMING_SNAKE_CASE__ : Any = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = CamembertTokenizer lowercase_ = CamembertTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Tuple )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Dict = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = '<pad>' SCREAMING_SNAKE_CASE__ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(a_ ) , 1004 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE__ : str = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=a_ , )
85
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 SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json", # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case ( UpperCamelCase_ ): lowercase_ = 'levit' def __init__( self : str , a_ : Optional[Any]=224 , a_ : List[str]=3 , a_ : Any=3 , a_ : Any=2 , a_ : Tuple=1 , a_ : int=16 , a_ : Optional[int]=[128, 256, 384] , a_ : Dict=[4, 8, 12] , a_ : List[str]=[4, 4, 4] , a_ : Any=[16, 16, 16] , a_ : Dict=0 , a_ : Tuple=[2, 2, 2] , a_ : Union[str, Any]=[2, 2, 2] , a_ : Optional[Any]=0.02 , **a_ : str , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : Any = kernel_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = stride SCREAMING_SNAKE_CASE__ : Any = padding SCREAMING_SNAKE_CASE__ : Any = hidden_sizes SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = key_dim SCREAMING_SNAKE_CASE__ : int = drop_path_rate SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = attention_ratio SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.11' ) @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowercase( self : Any )-> float: """simple docstring""" return 1e-4
85
1
from typing import Any import numpy as np def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return np.array_equal(lowercase__ , matrix.conjugate().T ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = v.conjugate().T SCREAMING_SNAKE_CASE__ : Any = v_star.dot(lowercase__ ) assert isinstance(lowercase__ , np.ndarray ) return (v_star_dot.dot(lowercase__ )) / (v_star.dot(lowercase__ )) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = np.array([[2, 2 + 1j, 4], [2 - 1j, 3, 1j], [4, -1j, 1]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1], [2], [3]] ) assert is_hermitian(lowercase__ ), f'''{a} is not hermitian.''' print(rayleigh_quotient(lowercase__ , lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Any = np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]] ) assert is_hermitian(lowercase__ ), f'''{a} is not hermitian.''' assert rayleigh_quotient(lowercase__ , lowercase__ ) == float(3 ) if __name__ == "__main__": import doctest doctest.testmod() tests()
85
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : List[str] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : List[Any] , a_ : Tuple , a_ : Optional[Any]=0 )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : List[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'french fries' SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : List[str] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : Tuple = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : int = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = components['vae'] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : List[Any] , a_ : Dict=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : Tuple = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Tuple = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : List[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : int )-> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : Dict = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : List[Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] SCREAMING_SNAKE_CASE__ : Any = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
85
1
from __future__ import annotations from typing import Any class snake_case : def __init__( self : Any , a_ : int , a_ : int , a_ : float = 0 )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = row, column SCREAMING_SNAKE_CASE__ : List[str] = [[default_value for c in range(a_ )] for r in range(a_ )] def __str__( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = F'''Matrix consist of {self.row} rows and {self.column} columns\n''' # Make string identifier SCREAMING_SNAKE_CASE__ : Dict = 0 for row_vector in self.array: for obj in row_vector: SCREAMING_SNAKE_CASE__ : int = max(a_ , len(str(a_ ) ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = F'''%{max_element_length}s''' # Make string and return def single_line(a_ : list[float] ) -> str: nonlocal string_format_identifier SCREAMING_SNAKE_CASE__ : Optional[int] = '[' line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(a_ ) for row_vector in self.array ) return s def __repr__( self : str )-> str: """simple docstring""" return str(self ) def __lowercase( self : Optional[int] , a_ : tuple[int, int] )-> bool: """simple docstring""" if not (isinstance(a_ , (list, tuple) ) and len(a_ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : List[str] , a_ : tuple[int, int] )-> Any: """simple docstring""" assert self.validate_indicies(a_ ) return self.array[loc[0]][loc[1]] def __setitem__( self : str , a_ : tuple[int, int] , a_ : float )-> None: """simple docstring""" assert self.validate_indicies(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = value def __add__( self : int , a_ : Matrix )-> Matrix: """simple docstring""" assert isinstance(a_ , a_ ) assert self.row == another.row and self.column == another.column # Add SCREAMING_SNAKE_CASE__ : List[str] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE__ : List[Any] = self[r, c] + another[r, c] return result def __neg__( self : Dict )-> Matrix: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE__ : Optional[Any] = -self[r, c] return result def __sub__( self : str , a_ : Matrix )-> Matrix: """simple docstring""" return self + (-another) def __mul__( self : str , a_ : int | float | Matrix )-> Matrix: """simple docstring""" if isinstance(a_ , (int, float) ): # Scalar multiplication SCREAMING_SNAKE_CASE__ : List[str] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE__ : List[str] = self[r, c] * another return result elif isinstance(a_ , a_ ): # Matrix multiplication assert self.column == another.row SCREAMING_SNAKE_CASE__ : Tuple = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: SCREAMING_SNAKE_CASE__ : Optional[Any] = F'''Unsupported type given for another ({type(a_ )})''' raise TypeError(a_ ) def __lowercase( self : Optional[Any] )-> Matrix: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): SCREAMING_SNAKE_CASE__ : int = self[r, c] return result def __lowercase( self : Optional[Any] , a_ : Matrix , a_ : Matrix )-> Any: """simple docstring""" assert isinstance(a_ , a_ ) and isinstance(a_ , a_ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate SCREAMING_SNAKE_CASE__ : str = v.transpose() SCREAMING_SNAKE_CASE__ : Tuple = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = Matrix(3 , 3 , 0 ) for i in range(3 ): SCREAMING_SNAKE_CASE__ : Any = 1 print(f'''a^(-1) is {ainv}''' ) # u, v SCREAMING_SNAKE_CASE__ : Optional[Any] = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1, 2, -3 SCREAMING_SNAKE_CASE__ : Union[str, Any] = Matrix(3 , 1 , 0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = 4, -2, 5 print(f'''u is {u}''' ) print(f'''v is {v}''' ) print(f'''uv^T is {u * v.transpose()}''' ) # Sherman Morrison print(f'''(a + uv^T)^(-1) is {ainv.sherman_morrison(lowercase__ , lowercase__ )}''' ) def _a ( ): '''simple docstring''' import doctest doctest.testmod() testa()
85
import math from collections.abc import Callable def _a ( lowercase__ : Callable[[float], float] , lowercase__ : float , lowercase__ : float ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : float = xa SCREAMING_SNAKE_CASE__ : float = xa while True: if x_n == x_na or function(lowercase__ ) == function(lowercase__ ): raise ZeroDivisionError('float division by zero, could not find root' ) SCREAMING_SNAKE_CASE__ : float = x_na - ( function(lowercase__ ) / ((function(lowercase__ ) - function(lowercase__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na SCREAMING_SNAKE_CASE__ : Dict = x_na SCREAMING_SNAKE_CASE__ : List[str] = x_na def _a ( lowercase__ : float ): '''simple docstring''' return math.pow(lowercase__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
85
1
from collections import UserDict from typing import List, Union from ..utils import ( add_end_docstrings, is_tf_available, is_torch_available, is_vision_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from PIL import Image from ..image_utils import load_image if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING from ..tf_utils import stable_softmax SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase_ ) class snake_case ( UpperCamelCase_ ): def __init__( self : List[str] , **a_ : Tuple )-> List[str]: """simple docstring""" super().__init__(**a_ ) requires_backends(self , 'vision' ) self.check_model_type( TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING ) def __call__( self : Union[str, Any] , a_ : Union[str, List[str], "Image", List["Image"]] , **a_ : List[str] )-> Optional[Any]: """simple docstring""" return super().__call__(a_ , **a_ ) def __lowercase( self : Dict , **a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = {} if "candidate_labels" in kwargs: SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs['candidate_labels'] if "hypothesis_template" in kwargs: SCREAMING_SNAKE_CASE__ : str = kwargs['hypothesis_template'] return preprocess_params, {}, {} def __lowercase( self : str , a_ : int , a_ : Optional[Any]=None , a_ : int="This is a photo of {}." )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = load_image(a_ ) SCREAMING_SNAKE_CASE__ : Any = self.image_processor(images=[image] , return_tensors=self.framework ) SCREAMING_SNAKE_CASE__ : str = candidate_labels SCREAMING_SNAKE_CASE__ : Any = [hypothesis_template.format(a_ ) for x in candidate_labels] SCREAMING_SNAKE_CASE__ : List[str] = self.tokenizer(a_ , return_tensors=self.framework , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = [text_inputs] return inputs def __lowercase( self : Union[str, Any] , a_ : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = model_inputs.pop('candidate_labels' ) SCREAMING_SNAKE_CASE__ : Optional[int] = model_inputs.pop('text_inputs' ) if isinstance(text_inputs[0] , a_ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = text_inputs[0] else: # Batching case. SCREAMING_SNAKE_CASE__ : Optional[Any] = text_inputs[0][0] SCREAMING_SNAKE_CASE__ : Any = self.model(**a_ , **a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { 'candidate_labels': candidate_labels, 'logits': outputs.logits_per_image, } return model_outputs def __lowercase( self : Optional[int] , a_ : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = model_outputs.pop('candidate_labels' ) SCREAMING_SNAKE_CASE__ : Optional[int] = model_outputs['logits'][0] if self.framework == "pt": SCREAMING_SNAKE_CASE__ : List[Any] = logits.softmax(dim=-1 ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : str = probs.tolist() if not isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = [scores] elif self.framework == "tf": SCREAMING_SNAKE_CASE__ : Optional[int] = stable_softmax(a_ , axis=-1 ) SCREAMING_SNAKE_CASE__ : int = probs.numpy().tolist() else: raise ValueError(F'''Unsupported framework: {self.framework}''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [ {'score': score, 'label': candidate_label} for score, candidate_label in sorted(zip(a_ , a_ ) , key=lambda a_ : -x[0] ) ] return result
85
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'AutoImageProcessor' lowercase_ = 'AutoTokenizer' def __init__( self : List[Any] , a_ : int , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self.image_processor def __call__( self : Tuple , a_ : str=None , a_ : List[Any]=None , a_ : Optional[Any]=None , **a_ : Dict )-> Tuple: """simple docstring""" if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : List[str] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : Dict , *a_ : Any , **a_ : Any )-> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Dict , *a_ : Union[str, Any] , **a_ : Optional[int] )-> Dict: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Any )-> Any: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
85
1
def _a ( lowercase__ : str , lowercase__ : bool = False ): '''simple docstring''' if not isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = f'''Expected string as input, found {type(lowercase__ )}''' raise ValueError(lowercase__ ) if not isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = f'''Expected boolean as use_pascal parameter, found {type(lowercase__ )}''' raise ValueError(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = input_str.split('_' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 if use_pascal else 1 SCREAMING_SNAKE_CASE__ : int = words[start_index:] SCREAMING_SNAKE_CASE__ : Dict = [word[0].upper() + word[1:] for word in words_to_capitalize] SCREAMING_SNAKE_CASE__ : List[str] = '' if use_pascal else words[0] return "".join([initial_word, *capitalized_words] ) if __name__ == "__main__": from doctest import testmod testmod()
85
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _a ( lowercase__ : int = 3 ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(lowercase__ ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumRegister(lowercase__ , 'qr' ) SCREAMING_SNAKE_CASE__ : int = ClassicalRegister(lowercase__ , 'cr' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumCircuit(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = number_of_qubits for i in range(lowercase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowercase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase__ , lowercase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowercase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowercase__ , lowercase__ ) # simulate with 10000 shots SCREAMING_SNAKE_CASE__ : Optional[int] = Aer.get_backend('qasm_simulator' ) SCREAMING_SNAKE_CASE__ : Tuple = execute(lowercase__ , lowercase__ , shots=1_00_00 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
85
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE__ : str = { "configuration_squeezebert": [ "SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "SqueezeBertConfig", "SqueezeBertOnnxConfig", ], "tokenization_squeezebert": ["SqueezeBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["SqueezeBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "SqueezeBertForMaskedLM", "SqueezeBertForMultipleChoice", "SqueezeBertForQuestionAnswering", "SqueezeBertForSequenceClassification", "SqueezeBertForTokenClassification", "SqueezeBertModel", "SqueezeBertModule", "SqueezeBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_squeezebert import ( SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertOnnxConfig, ) from .tokenization_squeezebert import SqueezeBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_squeezebert import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, SqueezeBertModule, SqueezeBertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Optional[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.mean(1 ) # Centralize the data of class i SCREAMING_SNAKE_CASE__ : Optional[Any] = data - column_reshape(lowercase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowercase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : Any = np.dot(lowercase__ , centered_data.T ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = features.mean(1 ) SCREAMING_SNAKE_CASE__ : List[str] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.shape[1] SCREAMING_SNAKE_CASE__ : List[Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : str = device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' if features.any(): SCREAMING_SNAKE_CASE__ : Any = features.mean(1 ) # Center the dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = features - np.reshape(lowercase__ , (data_mean.size, 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(lowercase__ , centered_data.T ) / features.shape[1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = np.linalg.eigh(lowercase__ ) # Take all the columns in the reverse order (-1), and then takes only the first SCREAMING_SNAKE_CASE__ : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.dot(filtered_eigenvectors.T , lowercase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = eigh( covariance_between_classes(lowercase__ , lowercase__ , lowercase__ ) , covariance_within_classes(lowercase__ , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = eigenvectors[:, ::-1][:, :dimensions] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.svd(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = svd_matrix[:, 0:dimensions] SCREAMING_SNAKE_CASE__ : int = np.dot(filtered_svd_matrix.T , lowercase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 0, 0, 1, 1] ) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : Optional[int] = linear_discriminant_analysis( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : int = principal_component_analysis(lowercase__ , lowercase__ ) if not np.allclose(lowercase__ , lowercase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
85
1
import json import os import pickle import shutil import tempfile from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset from transformers import is_faiss_available from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bart.tokenization_bart import BartTokenizer from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.dpr.tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.retrieval_rag import CustomHFIndex, RagRetriever from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_sentencepiece, require_tokenizers, require_torch if is_faiss_available(): import faiss @require_faiss class snake_case ( UpperCamelCase_ ): def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : List[Any] = 8 # DPR tok SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : Dict = os.path.join(self.tmpdirname , 'dpr_tokenizer' ) os.makedirs(a_ , exist_ok=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = os.path.join(a_ , DPR_VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) # BART tok SCREAMING_SNAKE_CASE__ : List[str] = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] SCREAMING_SNAKE_CASE__ : Any = dict(zip(a_ , range(len(a_ ) ) ) ) SCREAMING_SNAKE_CASE__ : Tuple = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'unk_token': '<unk>'} SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(self.tmpdirname , 'bart_tokenizer' ) os.makedirs(a_ , exist_ok=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(a_ , BART_VOCAB_FILES_NAMES['vocab_file'] ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(a_ , BART_VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp: fp.write(json.dumps(a_ ) + '\n' ) with open(self.merges_file , 'w' , encoding='utf-8' ) as fp: fp.write('\n'.join(a_ ) ) def __lowercase( self : Union[str, Any] )-> DPRQuestionEncoderTokenizer: """simple docstring""" return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'dpr_tokenizer' ) ) def __lowercase( self : Union[str, Any] )-> DPRContextEncoderTokenizer: """simple docstring""" return DPRContextEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'dpr_tokenizer' ) ) def __lowercase( self : List[Any] )-> BartTokenizer: """simple docstring""" return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname , 'bart_tokenizer' ) ) def __lowercase( self : str )-> int: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = Dataset.from_dict( { 'id': ['0', '1'], 'text': ['foo', 'bar'], 'title': ['Foo', 'Bar'], 'embeddings': [np.ones(self.retrieval_vector_size ), 2 * np.ones(self.retrieval_vector_size )], } ) dataset.add_faiss_index('embeddings' , string_factory='Flat' , metric_type=faiss.METRIC_INNER_PRODUCT ) return dataset def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_dataset() SCREAMING_SNAKE_CASE__ : Optional[int] = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , ) with patch('transformers.models.rag.retrieval_rag.load_dataset' ) as mock_load_dataset: SCREAMING_SNAKE_CASE__ : Any = dataset SCREAMING_SNAKE_CASE__ : int = RagRetriever( a_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) return retriever def __lowercase( self : Tuple , a_ : bool )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_dataset() SCREAMING_SNAKE_CASE__ : Union[str, Any] = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='custom' , ) if from_disk: SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(self.tmpdirname , 'dataset' ) SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.join(self.tmpdirname , 'index.faiss' ) dataset.get_index('embeddings' ).save(os.path.join(self.tmpdirname , 'index.faiss' ) ) dataset.drop_index('embeddings' ) dataset.save_to_disk(os.path.join(self.tmpdirname , 'dataset' ) ) del dataset SCREAMING_SNAKE_CASE__ : Union[str, Any] = RagRetriever( a_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = RagRetriever( a_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() , index=CustomHFIndex(config.retrieval_vector_size , a_ ) , ) return retriever def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = Dataset.from_dict( { 'id': ['0', '1'], 'text': ['foo', 'bar'], 'title': ['Foo', 'Bar'], 'embeddings': [np.ones(self.retrieval_vector_size + 1 ), 2 * np.ones(self.retrieval_vector_size + 1 )], } ) dataset.add_faiss_index('embeddings' , string_factory='Flat' , metric_type=faiss.METRIC_INNER_PRODUCT ) SCREAMING_SNAKE_CASE__ : str = os.path.join(self.tmpdirname , 'hf_bert_base.hnswSQ8_correct_phi_128.c_index' ) dataset.save_faiss_index('embeddings' , index_file_name + '.index.dpr' ) pickle.dump(dataset['id'] , open(index_file_name + '.index_meta.dpr' , 'wb' ) ) SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(self.tmpdirname , 'psgs_w100.tsv.pkl' ) SCREAMING_SNAKE_CASE__ : List[str] = {sample['id']: [sample['text'], sample['title']] for sample in dataset} pickle.dump(a_ , open(a_ , 'wb' ) ) SCREAMING_SNAKE_CASE__ : Any = RagConfig( retrieval_vector_size=self.retrieval_vector_size , question_encoder=DPRConfig().to_dict() , generator=BartConfig().to_dict() , index_name='legacy' , index_path=self.tmpdirname , ) SCREAMING_SNAKE_CASE__ : int = RagRetriever( a_ , question_encoder_tokenizer=self.get_dpr_tokenizer() , generator_tokenizer=self.get_bart_tokenizer() ) return retriever def __lowercase( self : Tuple )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE__ : Any = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = retriever.retrieve(a_ , n_docs=a_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(a_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['embeddings', 'id', 'text', 'title'] ) self.assertEqual(len(doc_dicts[0]['id'] ) , a_ ) self.assertEqual(doc_dicts[0]['id'][0] , '1' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['id'][0] , '0' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __lowercase( self : List[str] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_dummy_canonical_hf_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: with patch('transformers.models.rag.retrieval_rag.load_dataset' ) as mock_load_dataset: SCREAMING_SNAKE_CASE__ : int = self.get_dummy_dataset() retriever.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = RagRetriever.from_pretrained(a_ ) self.assertIsInstance(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : List[Any] = retriever.retrieve(a_ , n_docs=1 ) self.assertTrue(out is not None ) def __lowercase( self : Optional[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : int = self.get_dummy_custom_hf_index_retriever(from_disk=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = retriever.retrieve(a_ , n_docs=a_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(a_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['embeddings', 'id', 'text', 'title'] ) self.assertEqual(len(doc_dicts[0]['id'] ) , a_ ) self.assertEqual(doc_dicts[0]['id'][0] , '1' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['id'][0] , '0' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.get_dummy_custom_hf_index_retriever(from_disk=a_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = RagRetriever.from_pretrained(a_ ) self.assertIsInstance(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Tuple = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : Optional[Any] = retriever.retrieve(a_ , n_docs=1 ) self.assertTrue(out is not None ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 SCREAMING_SNAKE_CASE__ : List[Any] = self.get_dummy_custom_hf_index_retriever(from_disk=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = retriever.retrieve(a_ , n_docs=a_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(a_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['embeddings', 'id', 'text', 'title'] ) self.assertEqual(len(doc_dicts[0]['id'] ) , a_ ) self.assertEqual(doc_dicts[0]['id'][0] , '1' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['id'][0] , '0' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __lowercase( self : Dict )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_dummy_custom_hf_index_retriever(from_disk=a_ ) with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = RagRetriever.from_pretrained(a_ ) self.assertIsInstance(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : Any = retriever.retrieve(a_ , n_docs=1 ) self.assertTrue(out is not None ) def __lowercase( self : str )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_legacy_index_retriever() SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = retriever.retrieve(a_ , n_docs=a_ ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertEqual(len(a_ ) , 2 ) self.assertEqual(sorted(doc_dicts[0] ) , ['text', 'title'] ) self.assertEqual(len(doc_dicts[0]['text'] ) , a_ ) self.assertEqual(doc_dicts[0]['text'][0] , 'bar' ) # max inner product is reached with second doc self.assertEqual(doc_dicts[1]['text'][0] , 'foo' ) # max inner product is reached with first doc self.assertListEqual(doc_ids.tolist() , [[1], [0]] ) def __lowercase( self : Dict )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_dummy_legacy_index_retriever() with tempfile.TemporaryDirectory() as tmp_dirname: retriever.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = RagRetriever.from_pretrained(a_ ) self.assertIsInstance(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = retriever.retrieve(a_ , n_docs=1 ) self.assertTrue(out is not None ) @require_torch @require_tokenizers @require_sentencepiece def __lowercase( self : int )-> Tuple: """simple docstring""" import torch SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : Any = self.get_dummy_canonical_hf_index_retriever() SCREAMING_SNAKE_CASE__ : Optional[Any] = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE__ : str = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = retriever(a_ , a_ , prefix=retriever.config.generator.prefix , n_docs=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = ( out['context_input_ids'], out['context_attention_mask'], out['retrieved_doc_embeds'], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(a_ , a_ ) self.assertIsInstance(a_ , a_ ) self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : int = retriever( a_ , a_ , prefix=retriever.config.generator.prefix , n_docs=a_ , return_tensors='pt' , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = ( # noqa: F841 out['context_input_ids'], out['context_attention_mask'], out['retrieved_doc_embeds'], out['doc_ids'], ) self.assertEqual(retrieved_doc_embeds.shape , (2, n_docs, self.retrieval_vector_size) ) self.assertIsInstance(a_ , torch.Tensor ) self.assertIsInstance(a_ , torch.Tensor ) self.assertIsInstance(a_ , torch.Tensor ) @require_torch @require_tokenizers @require_sentencepiece def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dpr_ctx_encoder_tokenizer() SCREAMING_SNAKE_CASE__ : Dict = 1 SCREAMING_SNAKE_CASE__ : int = self.get_dummy_custom_hf_index_retriever(from_disk=a_ ) retriever.set_ctx_encoder_tokenizer(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [[5, 7], [10, 11]] SCREAMING_SNAKE_CASE__ : List[Any] = np.array( [np.ones(self.retrieval_vector_size ), -np.ones(self.retrieval_vector_size )] , dtype=np.floataa ) SCREAMING_SNAKE_CASE__ : int = retriever(a_ , a_ , prefix=retriever.config.generator.prefix , n_docs=a_ ) self.assertEqual( len(a_ ) , 6 ) # check whether the retriever output consist of 6 attributes including tokenized docs self.assertEqual( all(k in out for k in ('tokenized_doc_ids', 'tokenized_doc_attention_mask') ) , a_ ) # check for doc token related keys in dictionary.
85
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = "Hello world! cécé herlolip" SCREAMING_SNAKE_CASE__ : Dict = namedtuple( "BertAbsConfig", [ "temp_dir", "large", "use_bert_emb", "finetune_bert", "encoder", "share_emb", "max_pos", "enc_layers", "enc_hidden_size", "enc_heads", "enc_ff_size", "enc_dropout", "dec_layers", "dec_hidden_size", "dec_heads", "dec_ff_size", "dec_dropout", ], ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = BertAbsConfig( temp_dir='.' , finetune_bert=lowercase__ , large=lowercase__ , share_emb=lowercase__ , use_bert_emb=lowercase__ , encoder='bert' , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ , lambda lowercase__ , lowercase__ : storage ) SCREAMING_SNAKE_CASE__ : Any = AbsSummarizer(lowercase__ , torch.device('cpu' ) , lowercase__ ) original.eval() SCREAMING_SNAKE_CASE__ : List[Any] = BertAbsSummarizer(lowercase__ , torch.device('cpu' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('convert the model' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('Make sure that the models\' outputs are identical' ) SCREAMING_SNAKE_CASE__ : Any = BertTokenizer.from_pretrained('bert-base-uncased' ) # prepare the model inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode('This is sample éàalj\'-.' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor(lowercase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode('This is sample 3 éàalj\'-.' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor(lowercase__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE__ : int = encoder_input_ids SCREAMING_SNAKE_CASE__ : Any = decoder_input_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE__ : Optional[Any] = original(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = original.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = new_model( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = new_model.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.allclose(lowercase__ , lowercase__ , atol=1E-3 ) if are_identical: logging.info('all weights are equal up to 1e-3' ) else: raise ValueError('the weights are different. The new model is likely different from the original one.' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('saving the model\'s state dictionary' ) torch.save( new_model.state_dict() , './bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() parser.add_argument( "--bertabs_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model.", ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
85
1
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def _a ( lowercase__ : Dict ): '''simple docstring''' if isinstance(lowercase__ , collections.abc.Iterable ): return x return (x, x) @require_flax class snake_case : def __lowercase( self : Dict , a_ : List[Any] , a_ : List[Any] )-> int: """simple docstring""" pass def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" pass def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" pass def __lowercase( self : Any , a_ : np.ndarray , a_ : np.ndarray , a_ : float )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = np.abs((a - b) ).max() self.assertLessEqual(a_ , a_ , F'''Difference between torch and flax is {diff} (>= {tol}).''' ) def __lowercase( self : Optional[Any] , a_ : Optional[int] , a_ : Any , a_ : Optional[Any] , a_ : Dict , a_ : List[Any]=None , **a_ : Optional[int] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = FlaxVisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], config.projection_dim) ) def __lowercase( self : str , a_ : List[Any] , a_ : Dict , a_ : str , a_ : Optional[Any] , a_ : Optional[int]=None , **a_ : List[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_vision_text_model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Tuple = {'vision_model': vision_model, 'text_model': text_model} SCREAMING_SNAKE_CASE__ : Any = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) self.assertEqual(output['text_embeds'].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['image_embeds'].shape , (pixel_values.shape[0], model.config.projection_dim) ) def __lowercase( self : Dict , a_ : Any , a_ : Any , a_ : List[str] , a_ : str , a_ : int=None , **a_ : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.get_vision_text_model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'vision_model': vision_model, 'text_model': text_model} SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Dict = FlaxVisionTextDualEncoderModel.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = model(input_ids=a_ , pixel_values=a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = after_output[0] SCREAMING_SNAKE_CASE__ : Any = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a_ , 1e-3 ) def __lowercase( self : Optional[int] , a_ : List[Any] , a_ : Optional[int] , a_ : List[str] , a_ : int , a_ : int=None , **a_ : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = self.get_vision_text_model(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = {'vision_model': vision_model, 'text_model': text_model} SCREAMING_SNAKE_CASE__ : List[str] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model( input_ids=a_ , pixel_values=a_ , attention_mask=a_ , output_attentions=a_ ) SCREAMING_SNAKE_CASE__ : int = output.vision_model_output.attentions self.assertEqual(len(a_ ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : Any = to_atuple(vision_model.config.image_size ) SCREAMING_SNAKE_CASE__ : Dict = to_atuple(vision_model.config.patch_size ) SCREAMING_SNAKE_CASE__ : str = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) SCREAMING_SNAKE_CASE__ : Dict = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) SCREAMING_SNAKE_CASE__ : int = output.text_model_output.attentions self.assertEqual(len(a_ ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def __lowercase( self : str , a_ : Optional[Any] , a_ : Optional[int] , a_ : List[str] )-> Optional[int]: """simple docstring""" pt_model.to(a_ ) pt_model.eval() # prepare inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs_dict SCREAMING_SNAKE_CASE__ : Tuple = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = pt_model(**a_ ).to_tuple() SCREAMING_SNAKE_CASE__ : Union[str, Any] = fx_model(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(a_ , pt_output.numpy() , 4e-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : str = FlaxVisionTextDualEncoderModel.from_pretrained(a_ , from_pt=a_ ) SCREAMING_SNAKE_CASE__ : int = fx_model_loaded(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(a_ , pt_output.numpy() , 4e-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = VisionTextDualEncoderModel.from_pretrained(a_ , from_flax=a_ ) pt_model_loaded.to(a_ ) pt_model_loaded.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = pt_model_loaded(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(a_ , pt_output_loaded.numpy() , 4e-2 ) def __lowercase( self : int , a_ : List[str] , a_ : str , a_ : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = VisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxVisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , a_ ) SCREAMING_SNAKE_CASE__ : str = fx_state self.check_pt_flax_equivalence(a_ , a_ , a_ ) def __lowercase( self : int , a_ : List[Any] , a_ : int , a_ : List[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = VisionTextDualEncoderConfig.from_vision_text_configs(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = VisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxVisionTextDualEncoderModel(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = load_flax_weights_in_pytorch_model(a_ , fx_model.params ) self.check_pt_flax_equivalence(a_ , a_ , a_ ) def __lowercase( self : Union[str, Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**a_ ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**a_ ) def __lowercase( self : str )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() self.check_save_load(**a_ ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**a_ ) @is_pt_flax_cross_test def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Optional[int] = config_inputs_dict.pop('vision_config' ) SCREAMING_SNAKE_CASE__ : List[Any] = config_inputs_dict.pop('text_config' ) SCREAMING_SNAKE_CASE__ : Tuple = config_inputs_dict self.check_equivalence_pt_to_flax(a_ , a_ , a_ ) self.check_equivalence_flax_to_pt(a_ , a_ , a_ ) @slow def __lowercase( self : str )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.get_pretrained_model_and_inputs() SCREAMING_SNAKE_CASE__ : Any = model_a(**a_ ) SCREAMING_SNAKE_CASE__ : str = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Any = FlaxVisionTextDualEncoderModel.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_a(**a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = after_outputs[0] SCREAMING_SNAKE_CASE__ : List[Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a_ , 1e-5 ) @require_flax class snake_case ( UpperCamelCase_ , unittest.TestCase ): def __lowercase( self : Union[str, Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-vit' , 'hf-internal-testing/tiny-bert' , vision_from_pt=a_ , text_from_pt=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = 13 SCREAMING_SNAKE_CASE__ : Dict = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = random_attention_mask([batch_size, 4] ) SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def __lowercase( self : List[str] , a_ : Any , a_ : Tuple )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = FlaxViTModel(a_ ) SCREAMING_SNAKE_CASE__ : int = FlaxBertModel(a_ ) return vision_model, text_model def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FlaxViTModelTester(self ) SCREAMING_SNAKE_CASE__ : Dict = FlaxBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vit_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Dict = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = vision_config_and_inputs SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): def __lowercase( self : List[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( 'hf-internal-testing/tiny-random-clip' , 'hf-internal-testing/tiny-bert' , vision_from_pt=a_ , text_from_pt=a_ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 13 SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = random_attention_mask([batch_size, 4] ) SCREAMING_SNAKE_CASE__ : List[str] = {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask} return model, inputs def __lowercase( self : str , a_ : Optional[int] , a_ : str )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = FlaxCLIPVisionModel(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = FlaxBertModel(a_ ) return vision_model, text_model def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxCLIPVisionModelTester(self ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxBertModelTester(self ) SCREAMING_SNAKE_CASE__ : Any = clip_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : int = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = vision_config_and_inputs SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian' , logit_scale_init_value=1.0 ) SCREAMING_SNAKE_CASE__ : Tuple = VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processor( text=['una foto di un gatto', 'una foto di un cane'] , images=a_ , padding=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) SCREAMING_SNAKE_CASE__ : Any = np.array([[1.228_4727, 0.310_4122]] ) self.assertTrue(np.allclose(outputs.logits_per_image , a_ , atol=1e-3 ) )
85
from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case : def __init__( self : Tuple , a_ : int , a_ : Optional[int]=3 , a_ : Tuple=32 , a_ : Any=3 , a_ : Tuple=10 , a_ : Optional[int]=[10, 20, 30, 40] , a_ : List[Any]=[1, 1, 2, 1] , a_ : int=True , a_ : Optional[Any]=True , a_ : Any="relu" , a_ : int=3 , a_ : List[Any]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Tuple = embeddings_size SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : str = len(a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_config() return config, pixel_values, labels def __lowercase( self : str )-> str: """simple docstring""" 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 , ) def __lowercase( self : List[str] , a_ : int , a_ : Any , a_ : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFRegNetModel(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , training=a_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase( self : Union[str, Any] , a_ : Dict , a_ : int , a_ : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetForImageClassification(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ , training=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowercase_ = ( {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification} if is_tf_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self , config_class=a_ , has_text_modality=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" pass def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" def check_hidden_states_output(a_ : int , a_ : Union[str, Any] , a_ : Tuple ): SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(a_ , a_ ) , training=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(a_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE__ : List[Any] = layer_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True check_hidden_states_output(a_ , a_ , a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(a_ : str , a_ : Tuple , a_ : Optional[int] , a_ : Union[str, Any]={} ): SCREAMING_SNAKE_CASE__ : int = model(a_ , return_dict=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , return_dict=a_ , **a_ ).to_tuple() def recursive_check(a_ : List[Any] , a_ : int ): if isinstance(a_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a_ , a_ ): recursive_check(a_ , a_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(a_ , a_ ) ) , msg=( 'Tuple and dict output are not equal. Difference:' F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(a_ , a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def __lowercase( self : Any )-> List[str]: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFRegNetModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : List[Any] )-> int: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=a_ , return_tensors='tf' ) # forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ , training=a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , a_ , atol=1e-4 )
85
1
import math from collections.abc import Callable def _a ( lowercase__ : Callable[[float], float] , lowercase__ : float , lowercase__ : float ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : float = xa SCREAMING_SNAKE_CASE__ : float = xa while True: if x_n == x_na or function(lowercase__ ) == function(lowercase__ ): raise ZeroDivisionError('float division by zero, could not find root' ) SCREAMING_SNAKE_CASE__ : float = x_na - ( function(lowercase__ ) / ((function(lowercase__ ) - function(lowercase__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na SCREAMING_SNAKE_CASE__ : Dict = x_na SCREAMING_SNAKE_CASE__ : List[str] = x_na def _a ( lowercase__ : float ): '''simple docstring''' return math.pow(lowercase__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
import numpy as np import torch from torch.utils.data import Dataset from utils import logger class snake_case ( UpperCamelCase_ ): def __init__( self : Optional[Any] , a_ : List[str] , a_ : List[str] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = params SCREAMING_SNAKE_CASE__ : List[str] = np.array(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([len(a_ ) for t in data] ) self.check() self.remove_long_sequences() self.remove_empty_sequences() self.remove_unknown_sequences() self.check() self.print_statistics() def __getitem__( self : List[str] , a_ : Optional[Any] )-> Optional[int]: """simple docstring""" return (self.token_ids[index], self.lengths[index]) def __len__( self : str )-> List[str]: """simple docstring""" return len(self.lengths ) def __lowercase( self : Optional[Any] )-> Optional[Any]: """simple docstring""" assert len(self.token_ids ) == len(self.lengths ) assert all(self.lengths[i] == len(self.token_ids[i] ) for i in range(len(self.lengths ) ) ) def __lowercase( self : Optional[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.params.max_model_input_size SCREAMING_SNAKE_CASE__ : Tuple = self.lengths > max_len logger.info(F'''Splitting {sum(a_ )} too long sequences.''' ) def divide_chunks(a_ : List[str] , a_ : Optional[Any] ): return [l[i : i + n] for i in range(0 , len(a_ ) , a_ )] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] if self.params.mlm: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.params.special_tok_ids['cls_token'], self.params.special_tok_ids['sep_token'] else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.params.special_tok_ids['bos_token'], self.params.special_tok_ids['eos_token'] for seq_, len_ in zip(self.token_ids , self.lengths ): assert (seq_[0] == cls_id) and (seq_[-1] == sep_id), seq_ if len_ <= max_len: new_tok_ids.append(seq_ ) new_lengths.append(len_ ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for sub_s in divide_chunks(seq_ , max_len - 2 ): if sub_s[0] != cls_id: SCREAMING_SNAKE_CASE__ : Optional[Any] = np.insert(a_ , 0 , a_ ) if sub_s[-1] != sep_id: SCREAMING_SNAKE_CASE__ : List[Any] = np.insert(a_ , len(a_ ) , a_ ) assert len(a_ ) <= max_len assert (sub_s[0] == cls_id) and (sub_s[-1] == sep_id), sub_s sub_seqs.append(a_ ) new_tok_ids.extend(a_ ) new_lengths.extend([len(a_ ) for l in sub_seqs] ) SCREAMING_SNAKE_CASE__ : List[Any] = np.array(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.array(a_ ) def __lowercase( self : Union[str, Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = len(self ) SCREAMING_SNAKE_CASE__ : Dict = self.lengths > 11 SCREAMING_SNAKE_CASE__ : List[str] = self.token_ids[indices] SCREAMING_SNAKE_CASE__ : Dict = self.lengths[indices] SCREAMING_SNAKE_CASE__ : Any = len(self ) logger.info(F'''Remove {init_size - new_size} too short (<=11 tokens) sequences.''' ) def __lowercase( self : Union[str, Any] )-> int: """simple docstring""" if "unk_token" not in self.params.special_tok_ids: return else: SCREAMING_SNAKE_CASE__ : Any = self.params.special_tok_ids['unk_token'] SCREAMING_SNAKE_CASE__ : Tuple = len(self ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([np.count_nonzero(a == unk_token_id ) for a in self.token_ids] ) SCREAMING_SNAKE_CASE__ : Tuple = (unk_occs / self.lengths) < 0.5 SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.token_ids[indices] SCREAMING_SNAKE_CASE__ : Any = self.lengths[indices] SCREAMING_SNAKE_CASE__ : Union[str, Any] = len(self ) logger.info(F'''Remove {init_size - new_size} sequences with a high level of unknown tokens (50%).''' ) def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" if not self.params.is_master: return logger.info(F'''{len(self )} sequences''' ) # data_len = sum(self.lengths) # nb_unique_tokens = len(Counter(list(chain(*self.token_ids)))) # logger.info(f'{data_len} tokens ({nb_unique_tokens} unique)') # unk_idx = self.params.special_tok_ids['unk_token'] # nb_unknown = sum([(t==unk_idx).sum() for t in self.token_ids]) # logger.info(f'{nb_unknown} unknown tokens (covering {100*nb_unknown/data_len:.2f}% of the data)') def __lowercase( self : List[Any] , a_ : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = [t[0] for t in batch] SCREAMING_SNAKE_CASE__ : Any = [t[1] for t in batch] assert len(a_ ) == len(a_ ) # Max for paddings SCREAMING_SNAKE_CASE__ : Tuple = max(a_ ) # Pad token ids if self.params.mlm: SCREAMING_SNAKE_CASE__ : List[Any] = self.params.special_tok_ids['pad_token'] else: SCREAMING_SNAKE_CASE__ : Optional[int] = self.params.special_tok_ids['unk_token'] SCREAMING_SNAKE_CASE__ : Optional[Any] = [list(t.astype(a_ ) ) + [pad_idx] * (max_seq_len_ - len(a_ )) for t in token_ids] assert len(tk_ ) == len(a_ ) assert all(len(a_ ) == max_seq_len_ for t in tk_ ) SCREAMING_SNAKE_CASE__ : Any = torch.tensor(tk_ ) # (bs, max_seq_len_) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor(a_ ) # (bs) return tk_t, lg_t
85
def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) if n == 0: return 0 SCREAMING_SNAKE_CASE__ : str = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : int = max( lowercase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase__ ) ) return max_revue def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : str = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : list , lowercase__ : list ): '''simple docstring''' if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: SCREAMING_SNAKE_CASE__ : List[str] = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Any = max( lowercase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = max_revenue return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. SCREAMING_SNAKE_CASE__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : int = 0 for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(lowercase__ , prices[j - 1] + max_rev[i - j] ) SCREAMING_SNAKE_CASE__ : Dict = max_revenue_i return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' if n < 0: SCREAMING_SNAKE_CASE__ : Tuple = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowercase__ ) if n > len(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = ( 'Each integral piece of rod must have a corresponding price. ' f'''Got n = {n} but length of prices = {len(lowercase__ )}''' ) raise ValueError(lowercase__ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [6, 10, 12, 15, 20, 23] SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. SCREAMING_SNAKE_CASE__ : Optional[Any] = 36 SCREAMING_SNAKE_CASE__ : Tuple = top_down_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = bottom_up_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = naive_cut_rod_recursive(lowercase__ , lowercase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
85
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") SCREAMING_SNAKE_CASE__ : Any = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = CamembertTokenizer lowercase_ = CamembertTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Tuple )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Dict = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = '<pad>' SCREAMING_SNAKE_CASE__ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(a_ ) , 1004 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE__ : str = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=a_ , )
85
1
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = FunnelTokenizer lowercase_ = FunnelTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : str = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase( self : Any , **a_ : Any )-> List[str]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Tuple , **a_ : List[Any] )-> List[Any]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : int = 'unwanted, running' return input_text, output_text def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(a_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [7, 4, 5, 10, 8, 9] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer('UNwant\u00E9d,running' ) SCREAMING_SNAKE_CASE__ : List[Any] = len(inputs['input_ids'] ) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running' ) self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len )
85
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable SCREAMING_SNAKE_CASE__ : Any = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["DPTFeatureExtractor"] SCREAMING_SNAKE_CASE__ : Tuple = ["DPTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST", "DPTForDepthEstimation", "DPTForSemanticSegmentation", "DPTModel", "DPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable SCREAMING_SNAKE_CASE__ : Any = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["DPTFeatureExtractor"] SCREAMING_SNAKE_CASE__ : Tuple = ["DPTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST", "DPTForDepthEstimation", "DPTForSemanticSegmentation", "DPTModel", "DPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
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 SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : int = 8 , **a_ : Union[str, Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = do_rescale SCREAMING_SNAKE_CASE__ : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Dict = do_pad SCREAMING_SNAKE_CASE__ : Any = pad_size def __lowercase( self : str , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : str )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = get_image_size(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE__ : List[Any] = (old_width // size + 1) * size - old_width return pad(a_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a_ ) def __lowercase( self : Tuple , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Dict , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : List[str] = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE__ : List[str] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE__ : Tuple = make_list_of_images(a_ ) if not valid_images(a_ ): 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. SCREAMING_SNAKE_CASE__ : List[str] = [to_numpy_array(a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE__ : str = [self.pad(a_ , size=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
85
1
import requests SCREAMING_SNAKE_CASE__ : Union[str, Any] = "YOUR API KEY" def _a ( lowercase__ : str , lowercase__ : str = giphy_api_key ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = '+'.join(query.split() ) SCREAMING_SNAKE_CASE__ : Optional[int] = f'''https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = requests.get(lowercase__ ).json()['data'] return [gif["url"] for gif in gifs] if __name__ == "__main__": print("\n".join(get_gifs("space ship")))
85
from pathlib import Path import numpy as np from PIL import Image def _a ( lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return (gray > 1_27) & (gray <= 2_55) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros_like(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE__ : Optional[Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE__ : List[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE__ : List[str] = int(summation > 0 ) return output if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE__ : int = Path(__file__).resolve().parent / "image_data" / "lena.jpg" SCREAMING_SNAKE_CASE__ : int = np.array(Image.open(lena_path)) # kernel to be applied SCREAMING_SNAKE_CASE__ : str = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) SCREAMING_SNAKE_CASE__ : Optional[int] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image SCREAMING_SNAKE_CASE__ : Optional[int] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
85
1
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaImgaImgPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = KandinskyVaaImgaImgPipeline lowercase_ = ['image_embeds', 'negative_image_embeds', 'image'] lowercase_ = [ 'image_embeds', 'negative_image_embeds', 'image', ] lowercase_ = [ 'generator', 'height', 'width', 'strength', 'guidance_scale', 'num_inference_steps', 'return_dict', 'guidance_scale', 'num_images_per_prompt', 'output_type', 'return_dict', ] lowercase_ = False @property def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" return 32 @property def __lowercase( self : str )-> Any: """simple docstring""" return 32 @property def __lowercase( self : List[str] )-> List[str]: """simple docstring""" return self.time_input_dim @property def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return self.time_input_dim * 4 @property def __lowercase( self : Optional[Any] )-> Union[str, Any]: """simple docstring""" return 100 @property def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : str = { 'in_channels': 4, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'image', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } SCREAMING_SNAKE_CASE__ : Dict = UNetaDConditionModel(**a_ ) return model @property def __lowercase( self : Any )-> int: """simple docstring""" return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def __lowercase( self : Any )-> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = VQModel(**self.dummy_movq_kwargs ) return model def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.dummy_unet SCREAMING_SNAKE_CASE__ : List[Any] = self.dummy_movq SCREAMING_SNAKE_CASE__ : List[str] = { 'num_train_timesteps': 1000, 'beta_schedule': 'linear', 'beta_start': 0.0_0085, 'beta_end': 0.012, 'clip_sample': False, 'set_alpha_to_one': False, 'steps_offset': 0, 'prediction_type': 'epsilon', 'thresholding': False, } SCREAMING_SNAKE_CASE__ : Union[str, Any] = DDIMScheduler(**a_ ) SCREAMING_SNAKE_CASE__ : Any = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def __lowercase( self : Dict , a_ : Any , a_ : Dict=0 )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( a_ ) # create init_image SCREAMING_SNAKE_CASE__ : Union[str, Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ).resize((256, 256) ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : int = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : Any = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { 'image': init_image, 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 64, 'width': 64, 'num_inference_steps': 10, 'guidance_scale': 7.0, 'strength': 0.2, 'output_type': 'np', } return inputs def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 'cpu' SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.pipeline_class(**a_ ) SCREAMING_SNAKE_CASE__ : Any = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pipe(**self.get_dummy_inputs(a_ ) ) SCREAMING_SNAKE_CASE__ : str = output.images SCREAMING_SNAKE_CASE__ : Dict = pipe( **self.get_dummy_inputs(a_ ) , return_dict=a_ , )[0] SCREAMING_SNAKE_CASE__ : Dict = 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__ : Dict = np.array( [0.619_9778, 0.6398_4406, 0.4614_5785, 0.6294_4984, 0.562_2215, 0.4730_6132, 0.4744_1456, 0.460_7606, 0.4871_9263] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}''' assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}''' @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Dict )-> Any: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : Optional[int] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_img2img_frog.npy' ) SCREAMING_SNAKE_CASE__ : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png' ) SCREAMING_SNAKE_CASE__ : Tuple = 'A red cartoon frog, 4k' SCREAMING_SNAKE_CASE__ : Optional[int] = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(a_ ) SCREAMING_SNAKE_CASE__ : Any = KandinskyVaaImgaImgPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-decoder' , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Any = pipeline.to(a_ ) pipeline.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Generator(device='cpu' ).manual_seed(0 ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = pipe_prior( a_ , generator=a_ , num_inference_steps=5 , negative_prompt='' , ).to_tuple() SCREAMING_SNAKE_CASE__ : Any = pipeline( image=a_ , image_embeds=a_ , negative_image_embeds=a_ , generator=a_ , num_inference_steps=100 , height=768 , width=768 , strength=0.2 , output_type='np' , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(a_ , a_ )
85
def _a ( lowercase__ : int = 60_08_51_47_51_43 ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Dict = int(lowercase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : int = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 SCREAMING_SNAKE_CASE__ : str = i while n % i == 0: SCREAMING_SNAKE_CASE__ : List[Any] = n // i i += 1 return int(lowercase__ ) if __name__ == "__main__": print(F"""{solution() = }""")
85
1
from scipy.stats import spearmanr import datasets SCREAMING_SNAKE_CASE__ : List[str] = "\nThe Spearman rank-order correlation coefficient is a measure of the\nrelationship between two datasets. Like other correlation coefficients,\nthis one varies between -1 and +1 with 0 implying no correlation.\nPositive correlations imply that as data in dataset x increases, so\ndoes data in dataset y. Negative correlations imply that as x increases,\ny decreases. Correlations of -1 or +1 imply an exact monotonic relationship.\n\nUnlike the Pearson correlation, the Spearman correlation does not\nassume that both datasets are normally distributed.\n\nThe p-value roughly indicates the probability of an uncorrelated system\nproducing datasets that have a Spearman correlation at least as extreme\nas the one computed from these datasets. The p-values are not entirely\nreliable but are probably reasonable for datasets larger than 500 or so.\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nArgs:\n predictions (`List[float]`): Predicted labels, as returned by a model.\n references (`List[float]`): Ground truth labels.\n return_pvalue (`bool`): If `True`, returns the p-value. If `False`, returns\n only the spearmanr score. Defaults to `False`.\nReturns:\n spearmanr (`float`): Spearman correlation coefficient.\n p-value (`float`): p-value. **Note**: is only returned if `return_pvalue=True` is input.\nExamples:\n Example 1:\n >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5], predictions=[10, 9, 2.5, 6, 4])\n >>> print(results)\n {'spearmanr': -0.7}\n\n Example 2:\n >>> spearmanr_metric = datasets.load_metric(\"spearmanr\")\n >>> results = spearmanr_metric.compute(references=[1, 2, 3, 4, 5],\n ... predictions=[10, 9, 2.5, 6, 4],\n ... return_pvalue=True)\n >>> print(results['spearmanr'])\n -0.7\n >>> print(round(results['spearmanr_pvalue'], 2))\n 0.19\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = r"\\n@book{kokoska2000crc,\n title={CRC standard probability and statistics tables and formulae},\n author={Kokoska, Stephen and Zwillinger, Daniel},\n year={2000},\n publisher={Crc Press}\n}\n@article{2020SciPy-NMeth,\n author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, {\.I}lhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Ant{\^o}nio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\n title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\n journal = {Nature Methods},\n year = {2020},\n volume = {17},\n pages = {261--272},\n adsurl = {https://rdcu.be/b08Wh},\n doi = {10.1038/s41592-019-0686-2},\n}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float' ), 'references': datasets.Value('float' ), } ) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html'] , ) def __lowercase( self : str , a_ : Optional[int] , a_ : Optional[Any] , a_ : Optional[Any]=False )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = spearmanr(a_ , a_ ) if return_pvalue: return {"spearmanr": results[0], "spearmanr_pvalue": results[1]} else: return {"spearmanr": results[0]}
85
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = int(lowercase__ ) if n_element < 1: SCREAMING_SNAKE_CASE__ : Tuple = ValueError('a should be a positive number' ) raise my_error SCREAMING_SNAKE_CASE__ : Any = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = (0, 0, 0) SCREAMING_SNAKE_CASE__ : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") SCREAMING_SNAKE_CASE__ : int = hamming(int(n)) print("-----------------------------------------------------") print(F"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
85
1
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : int , lowercase__ : str=1.0 , lowercase__ : Optional[int]=None , lowercase__ : Any=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Tuple = global_rng SCREAMING_SNAKE_CASE__ : List[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class snake_case ( unittest.TestCase ): def __init__( self : Dict , a_ : int , a_ : List[str]=7 , a_ : Dict=400 , a_ : List[str]=2000 , a_ : Any=2048 , a_ : Optional[Any]=128 , a_ : List[str]=1 , a_ : Any=512 , a_ : List[Any]=30 , a_ : List[str]=4_4100 , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : Any = min_seq_length SCREAMING_SNAKE_CASE__ : Tuple = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : Optional[int] = spectrogram_length SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_size SCREAMING_SNAKE_CASE__ : List[Any] = num_audio_channels SCREAMING_SNAKE_CASE__ : str = hop_length SCREAMING_SNAKE_CASE__ : Any = chunk_length SCREAMING_SNAKE_CASE__ : str = sampling_rate def __lowercase( self : Optional[Any] )-> Optional[Any]: """simple docstring""" return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def __lowercase( self : Optional[int] , a_ : List[Any]=False , a_ : Optional[int]=False )-> List[Any]: """simple docstring""" def _flatten(a_ : Optional[Any] ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = TvltFeatureExtractor def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TvltFeatureExtractionTester(self ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(a_ , 'spectrogram_length' ) ) self.assertTrue(hasattr(a_ , 'feature_size' ) ) self.assertTrue(hasattr(a_ , 'num_audio_channels' ) ) self.assertTrue(hasattr(a_ , 'hop_length' ) ) self.assertTrue(hasattr(a_ , 'chunk_length' ) ) self.assertTrue(hasattr(a_ , 'sampling_rate' ) ) def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract_first.save_pretrained(a_ )[0] check_json_file_has_correct_format(a_ ) SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE__ : Union[str, Any] = dict_first.pop('mel_filters' ) SCREAMING_SNAKE_CASE__ : Any = dict_second.pop('mel_filters' ) self.assertTrue(np.allclose(a_ , a_ ) ) self.assertEqual(a_ , a_ ) def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Dict = os.path.join(a_ , 'feat_extract.json' ) feat_extract_first.to_json_file(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.feature_extraction_class.from_json_file(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE__ : List[str] = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE__ : Dict = dict_first.pop('mel_filters' ) SCREAMING_SNAKE_CASE__ : List[Any] = dict_second.pop('mel_filters' ) self.assertTrue(np.allclose(a_ , a_ ) ) self.assertEqual(a_ , a_ ) def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" # Initialize feature_extractor SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feature_extractor(np_speech_inputs[0] , return_tensors='np' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE__ : Dict = feature_extractor(a_ , return_tensors='np' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE__ : Dict = feature_extractor( a_ , return_tensors='np' , sampling_rate=4_4100 , mask_audio=a_ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : Optional[Any] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : int = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def __lowercase( self : Optional[Any] , a_ : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : str = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : Optional[int] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : str = TvltFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 192, 128) ) SCREAMING_SNAKE_CASE__ : Tuple = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , a_ , atol=1e-4 ) )
85
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class snake_case ( UpperCamelCase_ ): lowercase_ = 'Speech2TextFeatureExtractor' lowercase_ = 'Speech2TextTokenizer' def __init__( self : Optional[Any] , a_ : Optional[Any] , a_ : int )-> List[Any]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extractor SCREAMING_SNAKE_CASE__ : int = False def __call__( self : Union[str, Any] , *a_ : Union[str, Any] , **a_ : Optional[int] )-> Union[str, Any]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*a_ , **a_ ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) SCREAMING_SNAKE_CASE__ : List[str] = kwargs.pop('raw_speech' ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop('audio' , a_ ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('sampling_rate' , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = kwargs.pop('text' , a_ ) if len(a_ ) > 0: SCREAMING_SNAKE_CASE__ : Dict = args[0] SCREAMING_SNAKE_CASE__ : Tuple = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: SCREAMING_SNAKE_CASE__ : str = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ ) if text is not None: SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer(a_ , **a_ ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE__ : str = encodings['input_ids'] return inputs def __lowercase( self : Any , *a_ : Tuple , **a_ : Any )-> Any: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Optional[int] )-> Optional[int]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @contextmanager def __lowercase( self : Any )-> List[str]: """simple docstring""" warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) SCREAMING_SNAKE_CASE__ : List[str] = True SCREAMING_SNAKE_CASE__ : int = self.tokenizer yield SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.feature_extractor SCREAMING_SNAKE_CASE__ : Any = False
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'BridgeTowerImageProcessor' lowercase_ = ('RobertaTokenizer', 'RobertaTokenizerFast') def __init__( self : Dict , a_ : str , a_ : Tuple )-> str: """simple docstring""" super().__init__(a_ , a_ ) def __call__( self : List[Any] , a_ : str , a_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , a_ : bool = True , a_ : Union[bool, str, PaddingStrategy] = False , a_ : Union[bool, str, TruncationStrategy] = None , a_ : Optional[int] = None , a_ : int = 0 , a_ : Optional[int] = None , a_ : Optional[bool] = None , a_ : Optional[bool] = None , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = True , a_ : Optional[Union[str, TensorType]] = None , **a_ : List[Any] , )-> BatchEncoding: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer( text=a_ , add_special_tokens=a_ , padding=a_ , truncation=a_ , max_length=a_ , stride=a_ , pad_to_multiple_of=a_ , return_token_type_ids=a_ , return_attention_mask=a_ , return_overflowing_tokens=a_ , return_special_tokens_mask=a_ , return_offsets_mapping=a_ , return_length=a_ , verbose=a_ , return_tensors=a_ , **a_ , ) # add pixel_values + pixel_mask SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor( a_ , return_tensors=a_ , do_normalize=a_ , do_center_crop=a_ , **a_ ) encoding.update(a_ ) return encoding def __lowercase( self : Dict , *a_ : Any , **a_ : int )-> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : str , *a_ : int , **a_ : str )-> Any: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE__ : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
85
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs SCREAMING_SNAKE_CASE__ : int = imread(r"digital_image_processing/image_data/lena_small.jpg") SCREAMING_SNAKE_CASE__ : List[Any] = cvtColor(img, COLOR_BGR2GRAY) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = cn.convert_to_negative(lowercase__ ) # assert negative_img array for at least one True assert negative_img.any() def _a ( ): '''simple docstring''' with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowercase__ , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ : List[str] = canny.canny(lowercase__ ) # assert canny array for at least one True assert canny_array.any() def _a ( ): '''simple docstring''' assert gg.gaussian_filter(lowercase__ , 5 , sigma=0.9 ).all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) SCREAMING_SNAKE_CASE__ : Tuple = conv.img_convolve(lowercase__ , lowercase__ ).astype(lowercase__ ) assert res.any() def _a ( ): '''simple docstring''' assert med.median_filter(lowercase__ , 3 ).any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = sob.sobel_filter(lowercase__ ) assert grad.any() and theta.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = sp.make_sepia(lowercase__ , 20 ) assert sepia.all() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = bs.Burkes(imread(lowercase__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = rs.NearestNeighbour(imread(lowercase__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ : Dict = imread(lowercase__ , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ : List[Any] = lbp.get_neighbors_pixel( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): SCREAMING_SNAKE_CASE__ : str = lbp.local_binary_value(lowercase__ , lowercase__ , lowercase__ ) assert lbp_image.any()
85
1
from math import pow def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : int , ): '''simple docstring''' if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count SCREAMING_SNAKE_CASE__ : Dict = int(pow(lowercase__ , lowercase__ ) ) if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = backtrack( lowercase__ , lowercase__ , current_number + 1 , lowercase__ , lowercase__ ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = backtrack( lowercase__ , lowercase__ , current_number + 1 , lowercase__ , lowercase__ ) return current_sum, solutions_count def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' if not (1 <= needed_sum <= 10_00 and 2 <= power <= 10): raise ValueError( 'Invalid input\n' 'needed_sum must be between 1 and 1000, power between 2 and 10.' ) return backtrack(lowercase__ , lowercase__ , 1 , 0 , 0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
85
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu SCREAMING_SNAKE_CASE__ : Any = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: SCREAMING_SNAKE_CASE__ : Tuple = json.load(f) @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : List[str] , a_ : Any )-> str: """simple docstring""" return FSMTTokenizer.from_pretrained(a_ ) def __lowercase( self : int , a_ : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FSMTForConditionalGeneration.from_pretrained(a_ ).to(a_ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['en-ru', 26.0], ['ru-en', 22.0], ['en-de', 22.0], ['de-en', 29.0], ] ) @slow def __lowercase( self : int , a_ : Optional[int] , a_ : str )-> List[str]: """simple docstring""" # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality SCREAMING_SNAKE_CASE__ : Any = F'''facebook/wmt19-{pair}''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_model(a_ ) SCREAMING_SNAKE_CASE__ : int = bleu_data[pair]['src'] SCREAMING_SNAKE_CASE__ : Optional[int] = bleu_data[pair]['tgt'] SCREAMING_SNAKE_CASE__ : Any = tokenizer(a_ , return_tensors='pt' , truncation=a_ , padding='longest' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( input_ids=batch.input_ids , num_beams=8 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.batch_decode( a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_bleu(a_ , a_ ) print(a_ ) self.assertGreaterEqual(scores['bleu'] , a_ )
85
1
def _a ( lowercase__ : int = 60_08_51_47_51_43 ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Dict = int(lowercase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : int = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 SCREAMING_SNAKE_CASE__ : str = i while n % i == 0: SCREAMING_SNAKE_CASE__ : List[Any] = n // i i += 1 return int(lowercase__ ) if __name__ == "__main__": print(F"""{solution() = }""")
85
import os import pytest from attr import dataclass SCREAMING_SNAKE_CASE__ : int = "us-east-1" # defaults region @dataclass class snake_case : lowercase_ = 42 lowercase_ = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' lowercase_ = { 'task_name': 'mnli', 'per_device_train_batch_size': 16, 'per_device_eval_batch_size': 16, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 500, 'save_steps': 5_500, } lowercase_ = {**hyperparameters, 'max_steps': 1_000} @property def __lowercase( self : List[str] )-> str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return F'''{self.framework}-transfromers-test''' @property def __lowercase( self : int )-> str: """simple docstring""" return F'''./tests/sagemaker/scripts/{self.framework}''' @property def __lowercase( self : Tuple )-> str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def _a ( lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
85
1
import gc import unittest from diffusers import FlaxStableDiffusionInpaintPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class snake_case ( unittest.TestCase ): def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/sd2-inpaint/init_image.png' ) SCREAMING_SNAKE_CASE__ : List[str] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'xvjiarui/stable-diffusion-2-inpainting' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = FlaxStableDiffusionInpaintPipeline.from_pretrained(a_ , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = 'Face of a yellow cat, high resolution, sitting on a park bench' SCREAMING_SNAKE_CASE__ : List[str] = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE__ : Tuple = 50 SCREAMING_SNAKE_CASE__ : Union[str, Any] = jax.device_count() SCREAMING_SNAKE_CASE__ : Optional[Any] = num_samples * [prompt] SCREAMING_SNAKE_CASE__ : str = num_samples * [init_image] SCREAMING_SNAKE_CASE__ : Any = num_samples * [mask_image] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = pipeline.prepare_inputs(a_ , a_ , a_ ) # shard inputs and rng SCREAMING_SNAKE_CASE__ : Tuple = replicate(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = jax.random.split(a_ , jax.device_count() ) SCREAMING_SNAKE_CASE__ : int = shard(a_ ) SCREAMING_SNAKE_CASE__ : Dict = shard(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = shard(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = pipeline( a_ , a_ , a_ , a_ , a_ , a_ , jit=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = output.images.reshape(a_ , 512 , 512 , 3 ) SCREAMING_SNAKE_CASE__ : Tuple = images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE__ : Any = jnp.array( [0.361_1307, 0.3764_9736, 0.375_7408, 0.3821_3953, 0.3929_5167, 0.384_1631, 0.4155_4978, 0.413_7475, 0.421_7084] ) print(F'''output_slice: {output_slice}''' ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
85
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = FunnelTokenizer lowercase_ = FunnelTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : str = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase( self : Any , **a_ : Any )-> List[str]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Tuple , **a_ : List[Any] )-> List[Any]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : int = 'unwanted, running' return input_text, output_text def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(a_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [7, 4, 5, 10, 8, 9] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer('UNwant\u00E9d,running' ) SCREAMING_SNAKE_CASE__ : List[Any] = len(inputs['input_ids'] ) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running' ) self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len )
85
1
SCREAMING_SNAKE_CASE__ : Optional[int] = "0.21.0" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
85
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 SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json", # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case ( UpperCamelCase_ ): lowercase_ = 'levit' def __init__( self : str , a_ : Optional[Any]=224 , a_ : List[str]=3 , a_ : Any=3 , a_ : Any=2 , a_ : Tuple=1 , a_ : int=16 , a_ : Optional[int]=[128, 256, 384] , a_ : Dict=[4, 8, 12] , a_ : List[str]=[4, 4, 4] , a_ : Any=[16, 16, 16] , a_ : Dict=0 , a_ : Tuple=[2, 2, 2] , a_ : Union[str, Any]=[2, 2, 2] , a_ : Optional[Any]=0.02 , **a_ : str , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : Any = kernel_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = stride SCREAMING_SNAKE_CASE__ : Any = padding SCREAMING_SNAKE_CASE__ : Any = hidden_sizes SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = key_dim SCREAMING_SNAKE_CASE__ : int = drop_path_rate SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = attention_ratio SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.11' ) @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowercase( self : Any )-> float: """simple docstring""" return 1e-4
85
1
def _a ( lowercase__ : str ): '''simple docstring''' return "".join(chr(ord(lowercase__ ) - 32 ) if 'a' <= char <= 'z' else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
85
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : List[str] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : List[Any] , a_ : Tuple , a_ : Optional[Any]=0 )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : List[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'french fries' SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : List[str] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : Tuple = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : int = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = components['vae'] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : List[Any] , a_ : Dict=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : Tuple = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Tuple = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : List[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : int )-> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : Dict = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : List[Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] SCREAMING_SNAKE_CASE__ : Any = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
85
1
def _a ( lowercase__ : list ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = len(lowercase__ ) for _ in range(lowercase__ ): for i in range(_ % 2 , arr_size - 1 , 2 ): if arr[i + 1] < arr[i]: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = arr[i + 1], arr[i] return arr if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Optional[Any] = list(range(10, 0, -1)) print(F"""Original: {arr}. Sorted: {odd_even_transposition(arr)}""")
85
import math from collections.abc import Callable def _a ( lowercase__ : Callable[[float], float] , lowercase__ : float , lowercase__ : float ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : float = xa SCREAMING_SNAKE_CASE__ : float = xa while True: if x_n == x_na or function(lowercase__ ) == function(lowercase__ ): raise ZeroDivisionError('float division by zero, could not find root' ) SCREAMING_SNAKE_CASE__ : float = x_na - ( function(lowercase__ ) / ((function(lowercase__ ) - function(lowercase__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na SCREAMING_SNAKE_CASE__ : Dict = x_na SCREAMING_SNAKE_CASE__ : List[str] = x_na def _a ( lowercase__ : float ): '''simple docstring''' return math.pow(lowercase__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
85
1
from __future__ import annotations def _a ( lowercase__ : list[float] ): '''simple docstring''' if len(lowercase__ ) < 2: raise ValueError('Monogons and Digons are not polygons in the Euclidean space' ) if any(i <= 0 for i in nums ): raise ValueError('All values must be greater than 0' ) SCREAMING_SNAKE_CASE__ : Tuple = nums.copy() copy_nums.sort() return copy_nums[-1] < sum(copy_nums[:-1] ) if __name__ == "__main__": import doctest doctest.testmod()
85
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'AutoImageProcessor' lowercase_ = 'AutoTokenizer' def __init__( self : List[Any] , a_ : int , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self.image_processor def __call__( self : Tuple , a_ : str=None , a_ : List[Any]=None , a_ : Optional[Any]=None , **a_ : Dict )-> Tuple: """simple docstring""" if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : List[str] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : Dict , *a_ : Any , **a_ : Any )-> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Dict , *a_ : Union[str, Any] , **a_ : Optional[int] )-> Dict: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Any )-> Any: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
85
1
import torch from diffusers import DiffusionPipeline class snake_case ( UpperCamelCase_ ): def __init__( self : Any , a_ : Optional[int] , a_ : Dict )-> List[str]: """simple docstring""" super().__init__() self.register_modules(unet=a_ , scheduler=a_ ) def __call__( self : Optional[int] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = torch.randn( (1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , ) SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Tuple = self.unet(a_ , a_ ).sample SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.scheduler.step(a_ , a_ , a_ ).prev_sample SCREAMING_SNAKE_CASE__ : Union[str, Any] = scheduler_output - scheduler_output + torch.ones_like(a_ ) return result
85
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _a ( lowercase__ : int = 3 ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(lowercase__ ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumRegister(lowercase__ , 'qr' ) SCREAMING_SNAKE_CASE__ : int = ClassicalRegister(lowercase__ , 'cr' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumCircuit(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = number_of_qubits for i in range(lowercase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowercase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase__ , lowercase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowercase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowercase__ , lowercase__ ) # simulate with 10000 shots SCREAMING_SNAKE_CASE__ : Optional[int] = Aer.get_backend('qasm_simulator' ) SCREAMING_SNAKE_CASE__ : Tuple = execute(lowercase__ , lowercase__ , shots=1_00_00 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
85
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[str] = { "uw-madison/mra-base-512-4": "https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'mra' def __init__( self : int , a_ : Tuple=5_0265 , a_ : int=768 , a_ : int=12 , a_ : int=12 , a_ : List[str]=3072 , a_ : Tuple="gelu" , a_ : Any=0.1 , a_ : Union[str, Any]=0.1 , a_ : List[str]=512 , a_ : List[str]=1 , a_ : Optional[int]=0.02 , a_ : Dict=1e-5 , a_ : Dict="absolute" , a_ : Tuple=4 , a_ : List[Any]="full" , a_ : List[str]=0 , a_ : Tuple=0 , a_ : int=1 , a_ : int=0 , a_ : int=2 , **a_ : Union[str, Any] , )-> Tuple: """simple docstring""" super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE__ : str = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : int = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = initializer_range SCREAMING_SNAKE_CASE__ : Any = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = layer_norm_eps SCREAMING_SNAKE_CASE__ : Any = position_embedding_type SCREAMING_SNAKE_CASE__ : str = block_per_row SCREAMING_SNAKE_CASE__ : int = approx_mode SCREAMING_SNAKE_CASE__ : Tuple = initial_prior_first_n_blocks SCREAMING_SNAKE_CASE__ : str = initial_prior_diagonal_n_blocks
85
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.mean(1 ) # Centralize the data of class i SCREAMING_SNAKE_CASE__ : Optional[Any] = data - column_reshape(lowercase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowercase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : Any = np.dot(lowercase__ , centered_data.T ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = features.mean(1 ) SCREAMING_SNAKE_CASE__ : List[str] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.shape[1] SCREAMING_SNAKE_CASE__ : List[Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : str = device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' if features.any(): SCREAMING_SNAKE_CASE__ : Any = features.mean(1 ) # Center the dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = features - np.reshape(lowercase__ , (data_mean.size, 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(lowercase__ , centered_data.T ) / features.shape[1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = np.linalg.eigh(lowercase__ ) # Take all the columns in the reverse order (-1), and then takes only the first SCREAMING_SNAKE_CASE__ : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.dot(filtered_eigenvectors.T , lowercase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = eigh( covariance_between_classes(lowercase__ , lowercase__ , lowercase__ ) , covariance_within_classes(lowercase__ , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = eigenvectors[:, ::-1][:, :dimensions] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.svd(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = svd_matrix[:, 0:dimensions] SCREAMING_SNAKE_CASE__ : int = np.dot(filtered_svd_matrix.T , lowercase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 0, 0, 1, 1] ) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : Optional[int] = linear_discriminant_analysis( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : int = principal_component_analysis(lowercase__ , lowercase__ ) if not np.allclose(lowercase__ , lowercase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
85
1
from __future__ import annotations def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = [True] * limit SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Dict = False SCREAMING_SNAKE_CASE__ : int = True for i in range(3 , int(limit**0.5 + 1 ) , 2 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = i * 2 while index < limit: SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : Tuple = index + i SCREAMING_SNAKE_CASE__ : List[str] = [2] for i in range(3 , lowercase__ , 2 ): if is_prime[i]: primes.append(lowercase__ ) return primes def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = prime_sieve(lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 for i in range(len(lowercase__ ) ): for j in range(i + length , len(lowercase__ ) ): SCREAMING_SNAKE_CASE__ : int = sum(primes[i:j] ) if sol >= ceiling: break if sol in primes: SCREAMING_SNAKE_CASE__ : Any = j - i SCREAMING_SNAKE_CASE__ : int = sol return largest if __name__ == "__main__": print(F"""{solution() = }""")
85
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = "Hello world! cécé herlolip" SCREAMING_SNAKE_CASE__ : Dict = namedtuple( "BertAbsConfig", [ "temp_dir", "large", "use_bert_emb", "finetune_bert", "encoder", "share_emb", "max_pos", "enc_layers", "enc_hidden_size", "enc_heads", "enc_ff_size", "enc_dropout", "dec_layers", "dec_hidden_size", "dec_heads", "dec_ff_size", "dec_dropout", ], ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = BertAbsConfig( temp_dir='.' , finetune_bert=lowercase__ , large=lowercase__ , share_emb=lowercase__ , use_bert_emb=lowercase__ , encoder='bert' , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ , lambda lowercase__ , lowercase__ : storage ) SCREAMING_SNAKE_CASE__ : Any = AbsSummarizer(lowercase__ , torch.device('cpu' ) , lowercase__ ) original.eval() SCREAMING_SNAKE_CASE__ : List[Any] = BertAbsSummarizer(lowercase__ , torch.device('cpu' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('convert the model' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('Make sure that the models\' outputs are identical' ) SCREAMING_SNAKE_CASE__ : Any = BertTokenizer.from_pretrained('bert-base-uncased' ) # prepare the model inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode('This is sample éàalj\'-.' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor(lowercase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode('This is sample 3 éàalj\'-.' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor(lowercase__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE__ : int = encoder_input_ids SCREAMING_SNAKE_CASE__ : Any = decoder_input_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE__ : Optional[Any] = original(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = original.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = new_model( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = new_model.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.allclose(lowercase__ , lowercase__ , atol=1E-3 ) if are_identical: logging.info('all weights are equal up to 1e-3' ) else: raise ValueError('the weights are different. The new model is likely different from the original one.' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('saving the model\'s state dictionary' ) torch.save( new_model.state_dict() , './bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() parser.add_argument( "--bertabs_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model.", ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
85
1
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"): SCREAMING_SNAKE_CASE__ : Optional[int] = { "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: SCREAMING_SNAKE_CASE__ : Optional[int] = { "linear": PIL.Image.LINEAR, "bilinear": PIL.Image.BILINEAR, "bicubic": PIL.Image.BICUBIC, "lanczos": PIL.Image.LANCZOS, "nearest": PIL.Image.NEAREST, } def _a ( lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = (images / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE__ : List[Any] = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() SCREAMING_SNAKE_CASE__ : Union[str, Any] = numpy_to_pil(lowercase__ ) return images def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if images.ndim == 3: SCREAMING_SNAKE_CASE__ : Dict = images[None, ...] SCREAMING_SNAKE_CASE__ : List[str] = (images * 2_55).round().astype('uint8' ) if images.shape[-1] == 1: # special case for grayscale (single channel) images SCREAMING_SNAKE_CASE__ : List[Any] = [Image.fromarray(image.squeeze() , mode='L' ) for image in images] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [Image.fromarray(lowercase__ ) for image in images] return pil_images
85
from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case : def __init__( self : Tuple , a_ : int , a_ : Optional[int]=3 , a_ : Tuple=32 , a_ : Any=3 , a_ : Tuple=10 , a_ : Optional[int]=[10, 20, 30, 40] , a_ : List[Any]=[1, 1, 2, 1] , a_ : int=True , a_ : Optional[Any]=True , a_ : Any="relu" , a_ : int=3 , a_ : List[Any]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Tuple = embeddings_size SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : str = len(a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_config() return config, pixel_values, labels def __lowercase( self : str )-> str: """simple docstring""" 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 , ) def __lowercase( self : List[str] , a_ : int , a_ : Any , a_ : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFRegNetModel(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , training=a_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase( self : Union[str, Any] , a_ : Dict , a_ : int , a_ : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetForImageClassification(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ , training=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowercase_ = ( {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification} if is_tf_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self , config_class=a_ , has_text_modality=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" pass def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" def check_hidden_states_output(a_ : int , a_ : Union[str, Any] , a_ : Tuple ): SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(a_ , a_ ) , training=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(a_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE__ : List[Any] = layer_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True check_hidden_states_output(a_ , a_ , a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(a_ : str , a_ : Tuple , a_ : Optional[int] , a_ : Union[str, Any]={} ): SCREAMING_SNAKE_CASE__ : int = model(a_ , return_dict=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , return_dict=a_ , **a_ ).to_tuple() def recursive_check(a_ : List[Any] , a_ : int ): if isinstance(a_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a_ , a_ ): recursive_check(a_ , a_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(a_ , a_ ) ) , msg=( 'Tuple and dict output are not equal. Difference:' F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(a_ , a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def __lowercase( self : Any )-> List[str]: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFRegNetModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : List[Any] )-> int: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=a_ , return_tensors='tf' ) # forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ , training=a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , a_ , atol=1e-4 )
85
1
from random import randint from tempfile import TemporaryFile import numpy as np def _a ( lowercase__ : List[Any] , lowercase__ : List[Any] , lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = 0 if start < end: SCREAMING_SNAKE_CASE__ : List[str] = randint(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = a[end] SCREAMING_SNAKE_CASE__ : Tuple = a[pivot] SCREAMING_SNAKE_CASE__ : Optional[Any] = temp SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = _in_place_partition(lowercase__ , lowercase__ , lowercase__ ) count += _in_place_quick_sort(lowercase__ , lowercase__ , p - 1 ) count += _in_place_quick_sort(lowercase__ , p + 1 , lowercase__ ) return count def _a ( lowercase__ : Optional[Any] , lowercase__ : List[str] , lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = randint(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = a[end] SCREAMING_SNAKE_CASE__ : List[Any] = a[pivot] SCREAMING_SNAKE_CASE__ : Any = temp SCREAMING_SNAKE_CASE__ : Optional[int] = start - 1 for index in range(lowercase__ , lowercase__ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value SCREAMING_SNAKE_CASE__ : Any = new_pivot_index + 1 SCREAMING_SNAKE_CASE__ : List[Any] = a[new_pivot_index] SCREAMING_SNAKE_CASE__ : List[Any] = a[index] SCREAMING_SNAKE_CASE__ : Optional[int] = temp SCREAMING_SNAKE_CASE__ : Optional[int] = a[new_pivot_index + 1] SCREAMING_SNAKE_CASE__ : Union[str, Any] = a[end] SCREAMING_SNAKE_CASE__ : Dict = temp return new_pivot_index + 1, count SCREAMING_SNAKE_CASE__ : Union[str, Any] = TemporaryFile() SCREAMING_SNAKE_CASE__ : Any = 100 # 1000 elements are to be sorted SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = 0, 1 # mean and standard deviation SCREAMING_SNAKE_CASE__ : int = np.random.normal(mu, sigma, p) np.save(outfile, X) print("The array is") print(X) outfile.seek(0) # using the same array SCREAMING_SNAKE_CASE__ : int = np.load(outfile) SCREAMING_SNAKE_CASE__ : List[str] = len(M) - 1 SCREAMING_SNAKE_CASE__ : Any = _in_place_quick_sort(M, 0, r) print( "No of Comparisons for 100 elements selected from a standard normal distribution" "is :" ) print(z)
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__) def _a ( lowercase__ : List[str] , lowercase__ : List[str]=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''blocks.{i}.norm1.weight''', f'''deit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''blocks.{i}.norm1.bias''', f'''deit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append((f'''blocks.{i}.attn.proj.weight''', f'''deit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.attn.proj.bias''', f'''deit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''blocks.{i}.norm2.weight''', f'''deit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''blocks.{i}.norm2.bias''', f'''deit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.weight''', f'''deit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc1.bias''', f'''deit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.weight''', f'''deit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''blocks.{i}.mlp.fc2.bias''', f'''deit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ('cls_token', 'deit.embeddings.cls_token'), ('dist_token', 'deit.embeddings.distillation_token'), ('patch_embed.proj.weight', 'deit.embeddings.patch_embeddings.projection.weight'), ('patch_embed.proj.bias', 'deit.embeddings.patch_embeddings.projection.bias'), ('pos_embed', 'deit.embeddings.position_embeddings'), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ('pre_logits.fc.weight', 'pooler.dense.weight'), ('pre_logits.fc.bias', 'pooler.dense.bias'), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" SCREAMING_SNAKE_CASE__ : Tuple = [(pair[0], pair[1][4:]) if pair[1].startswith('deit' ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ('norm.weight', 'deit.layernorm.weight'), ('norm.bias', 'deit.layernorm.bias'), ('head.weight', 'cls_classifier.weight'), ('head.bias', 'cls_classifier.bias'), ('head_dist.weight', 'distillation_classifier.weight'), ('head_dist.bias', 'distillation_classifier.bias'), ] ) return rename_keys def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Optional[int]=False ): '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = '' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'deit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : str = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : List[Any] , lowercase__ : str , lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = val def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = 'http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ) return im @torch.no_grad() def _a ( lowercase__ : Any , lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = DeiTConfig() # all deit models have fine-tuned heads SCREAMING_SNAKE_CASE__ : Optional[Any] = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size SCREAMING_SNAKE_CASE__ : List[Any] = 10_00 SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[int] = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Dict = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Any = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : int = idalabel SCREAMING_SNAKE_CASE__ : Any = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = int(deit_name[-6:-4] ) SCREAMING_SNAKE_CASE__ : List[Any] = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith('tiny' ): SCREAMING_SNAKE_CASE__ : Optional[int] = 1_92 SCREAMING_SNAKE_CASE__ : str = 7_68 SCREAMING_SNAKE_CASE__ : Optional[int] = 12 SCREAMING_SNAKE_CASE__ : Optional[Any] = 3 elif deit_name[9:].startswith('small' ): SCREAMING_SNAKE_CASE__ : List[Any] = 3_84 SCREAMING_SNAKE_CASE__ : Dict = 15_36 SCREAMING_SNAKE_CASE__ : Dict = 12 SCREAMING_SNAKE_CASE__ : List[str] = 6 if deit_name[9:].startswith('base' ): pass elif deit_name[4:].startswith('large' ): SCREAMING_SNAKE_CASE__ : List[str] = 10_24 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 40_96 SCREAMING_SNAKE_CASE__ : List[str] = 24 SCREAMING_SNAKE_CASE__ : str = 16 # load original model from timm SCREAMING_SNAKE_CASE__ : Union[str, Any] = timm.create_model(lowercase__ , pretrained=lowercase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Optional[Any] = timm_model.state_dict() SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ , lowercase__ ) # load HuggingFace model SCREAMING_SNAKE_CASE__ : str = DeiTForImageClassificationWithTeacher(lowercase__ ).eval() model.load_state_dict(lowercase__ ) # Check outputs on an image, prepared by DeiTImageProcessor SCREAMING_SNAKE_CASE__ : Tuple = int( (2_56 / 2_24) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTImageProcessor(size=lowercase__ , crop_size=config.image_size ) SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(images=prepare_img() , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Any = encoding['pixel_values'] SCREAMING_SNAKE_CASE__ : Tuple = model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = timm_model(lowercase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowercase__ , outputs.logits , atol=1E-3 ) Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model {deit_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser() # Required parameters parser.add_argument( "--deit_name", default="vit_deit_base_distilled_patch16_224", type=str, help="Name of the DeiT timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
85
def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) if n == 0: return 0 SCREAMING_SNAKE_CASE__ : str = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : int = max( lowercase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase__ ) ) return max_revue def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : str = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : list , lowercase__ : list ): '''simple docstring''' if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: SCREAMING_SNAKE_CASE__ : List[str] = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Any = max( lowercase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = max_revenue return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. SCREAMING_SNAKE_CASE__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : int = 0 for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(lowercase__ , prices[j - 1] + max_rev[i - j] ) SCREAMING_SNAKE_CASE__ : Dict = max_revenue_i return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' if n < 0: SCREAMING_SNAKE_CASE__ : Tuple = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowercase__ ) if n > len(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = ( 'Each integral piece of rod must have a corresponding price. ' f'''Got n = {n} but length of prices = {len(lowercase__ )}''' ) raise ValueError(lowercase__ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [6, 10, 12, 15, 20, 23] SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. SCREAMING_SNAKE_CASE__ : Optional[Any] = 36 SCREAMING_SNAKE_CASE__ : Tuple = top_down_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = bottom_up_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = naive_cut_rod_recursive(lowercase__ , lowercase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
85
1
import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test sys.path.append(str(Path(__file__).parent.parent / "utils")) from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 SCREAMING_SNAKE_CASE__ : str = get_tests_dir("fixtures") class snake_case ( unittest.TestCase ): def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" # A mock response for an HTTP head request to emulate server down SCREAMING_SNAKE_CASE__ : Union[str, Any] = mock.Mock() SCREAMING_SNAKE_CASE__ : Union[str, Any] = 500 SCREAMING_SNAKE_CASE__ : int = {} SCREAMING_SNAKE_CASE__ : Union[str, Any] = HTTPError SCREAMING_SNAKE_CASE__ : str = {} # Download this model to make sure it's in the cache. SCREAMING_SNAKE_CASE__ : Optional[Any] = WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('requests.Session.request' , return_value=a_ ) as mock_head: SCREAMING_SNAKE_CASE__ : int = WavaVecaFeatureExtractor.from_pretrained('hf-internal-testing/tiny-random-wav2vec2' ) # This check we did call the fake head request mock_head.assert_called() def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" # This test is for deprecated behavior and can be removed in v5 SCREAMING_SNAKE_CASE__ : List[str] = WavaVecaFeatureExtractor.from_pretrained( 'https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json' ) @is_staging_test class snake_case ( unittest.TestCase ): @classmethod def __lowercase( cls : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = TOKEN HfFolder.save_token(a_ ) @classmethod def __lowercase( cls : str )-> Any: """simple docstring""" try: delete_repo(token=cls._token , repo_id='test-feature-extractor' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='valid_org/test-feature-extractor-org' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='test-dynamic-feature-extractor' ) except HTTPError: pass def __lowercase( self : Dict )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = WavaVecaFeatureExtractor.from_pretrained(a_ ) feature_extractor.push_to_hub('test-feature-extractor' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ : str = WavaVecaFeatureExtractor.from_pretrained(F'''{USER}/test-feature-extractor''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a_ , getattr(a_ , a_ ) ) # Reset repo delete_repo(token=self._token , repo_id='test-feature-extractor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( a_ , repo_id='test-feature-extractor' , push_to_hub=a_ , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ : Dict = WavaVecaFeatureExtractor.from_pretrained(F'''{USER}/test-feature-extractor''' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a_ , getattr(a_ , a_ ) ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = WavaVecaFeatureExtractor.from_pretrained(a_ ) feature_extractor.push_to_hub('valid_org/test-feature-extractor' , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ : int = WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a_ , getattr(a_ , a_ ) ) # Reset repo delete_repo(token=self._token , repo_id='valid_org/test-feature-extractor' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained( a_ , repo_id='valid_org/test-feature-extractor-org' , push_to_hub=a_ , use_auth_token=self._token ) SCREAMING_SNAKE_CASE__ : str = WavaVecaFeatureExtractor.from_pretrained('valid_org/test-feature-extractor-org' ) for k, v in feature_extractor.__dict__.items(): self.assertEqual(a_ , getattr(a_ , a_ ) ) def __lowercase( self : str )-> int: """simple docstring""" CustomFeatureExtractor.register_for_auto_class() SCREAMING_SNAKE_CASE__ : Any = CustomFeatureExtractor.from_pretrained(a_ ) feature_extractor.push_to_hub('test-dynamic-feature-extractor' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual( feature_extractor.auto_map , {'AutoFeatureExtractor': 'custom_feature_extraction.CustomFeatureExtractor'} , ) SCREAMING_SNAKE_CASE__ : Tuple = AutoFeatureExtractor.from_pretrained( F'''{USER}/test-dynamic-feature-extractor''' , trust_remote_code=a_ ) # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module self.assertEqual(new_feature_extractor.__class__.__name__ , 'CustomFeatureExtractor' )
85
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") SCREAMING_SNAKE_CASE__ : Any = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = CamembertTokenizer lowercase_ = CamembertTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Tuple )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Dict = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = '<pad>' SCREAMING_SNAKE_CASE__ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(a_ ) , 1004 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE__ : str = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=a_ , )
85
1
import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_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, _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, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class snake_case : def __init__( self : Optional[int] , a_ : Any , a_ : List[str]=100 , a_ : Dict=13 , a_ : str=30 , a_ : str=2 , a_ : Any=3 , a_ : int=True , a_ : str=True , a_ : Tuple=32 , a_ : Optional[Any]=4 , a_ : Optional[int]=4 , a_ : List[Any]=37 , a_ : str="gelu" , a_ : str=0.1 , a_ : Dict=0.1 , a_ : Union[str, Any]=10 , a_ : int=0.02 , a_ : Optional[Any]=3 , a_ : Tuple=None , a_ : Optional[int]=[0, 1, 2, 3] , )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = parent SCREAMING_SNAKE_CASE__ : int = 100 SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : Optional[int] = patch_size SCREAMING_SNAKE_CASE__ : str = num_channels SCREAMING_SNAKE_CASE__ : List[Any] = is_training SCREAMING_SNAKE_CASE__ : Tuple = use_labels SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : int = num_hidden_layers SCREAMING_SNAKE_CASE__ : Any = num_attention_heads SCREAMING_SNAKE_CASE__ : str = intermediate_size SCREAMING_SNAKE_CASE__ : str = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : str = scope SCREAMING_SNAKE_CASE__ : List[Any] = out_indices SCREAMING_SNAKE_CASE__ : Optional[int] = num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) SCREAMING_SNAKE_CASE__ : Optional[Any] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Any = num_patches + 1 def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : int = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : int = self.get_config() return config, pixel_values, labels, pixel_labels def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" return BeitConfig( vocab_size=self.vocab_size , 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 , out_indices=self.out_indices , ) def __lowercase( self : List[str] , a_ : str , a_ : Any , a_ : Tuple , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BeitModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[str] , a_ : List[str] , a_ : List[Any] , a_ : int , a_ : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BeitForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def __lowercase( self : Any , a_ : Any , a_ : Optional[int] , a_ : str , a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[Any] = BeitForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = BeitForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : Dict , a_ : Dict , a_ : Optional[int] , a_ : int , a_ : Optional[int] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE__ : Any = BeitForSemanticSegmentation(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model(a_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) SCREAMING_SNAKE_CASE__ : int = model(a_ , labels=a_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def __lowercase( self : Optional[int] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': BeitModel, 'image-classification': BeitForImageClassification, 'image-segmentation': BeitForSemanticSegmentation, } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : str )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = BeitModelTester(self ) SCREAMING_SNAKE_CASE__ : str = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Any )-> Dict: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='BEiT does not use inputs_embeds' ) def __lowercase( self : Optional[Any] )-> Union[str, Any]: """simple docstring""" pass @require_torch_multi_gpu @unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def __lowercase( self : int )-> Optional[Any]: """simple docstring""" pass def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Tuple = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : Optional[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Union[str, Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a_ ) def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*a_ ) def __lowercase( self : int )-> str: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(a_ ), BeitForMaskedImageModeling]: continue SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Dict = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : str = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(a_ ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Any = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss loss.backward() def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = _config_zero_init(a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Any = model_class(config=a_ ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @slow def __lowercase( self : Any )-> str: """simple docstring""" for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[str] = BeitModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : str )-> List[Any]: """simple docstring""" return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def __lowercase( self : Optional[int] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ).pixel_values.to(a_ ) # prepare bool_masked_pos SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.ones((1, 196) , dtype=torch.bool ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(pixel_values=a_ , bool_masked_pos=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : Tuple = torch.Size((1, 196, 8192) ) self.assertEqual(logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]] ).to(a_ ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , a_ , atol=1e-2 ) ) @slow def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ).to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Union[str, Any] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor([-1.2385, -1.0987, -1.0108] ).to(a_ ) self.assertTrue(torch.allclose(logits[0, :3] , a_ , atol=1e-4 ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 281 self.assertEqual(logits.argmax(-1 ).item() , a_ ) @slow def __lowercase( self : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ).to( a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.default_image_processor SCREAMING_SNAKE_CASE__ : Dict = prepare_img() SCREAMING_SNAKE_CASE__ : Tuple = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 2_1841) ) self.assertEqual(logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : str = torch.tensor([1.6881, -0.2787, 0.5901] ).to(a_ ) self.assertTrue(torch.allclose(logits[0, :3] , a_ , atol=1e-4 ) ) SCREAMING_SNAKE_CASE__ : List[Any] = 2396 self.assertEqual(logits.argmax(-1 ).item() , a_ ) @slow def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.to(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = BeitImageProcessor(do_resize=a_ , size=640 , do_center_crop=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) SCREAMING_SNAKE_CASE__ : Optional[int] = Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = outputs.logits # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 150, 160, 160) ) self.assertEqual(logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : str = version.parse(PIL.__version__ ) < version.parse('9.0.0' ) if is_pillow_less_than_a: SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [ [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]], [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]], [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]], ] , device=a_ , ) else: SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [ [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]], [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]], [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]], ] , device=a_ , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = BeitImageProcessor(do_resize=a_ , size=640 , do_center_crop=a_ ) SCREAMING_SNAKE_CASE__ : str = load_dataset('hf-internal-testing/fixtures_ade20k' , split='test' ) SCREAMING_SNAKE_CASE__ : Dict = Image.open(ds[0]['file'] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Dict = model(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = outputs.logits.detach().cpu() SCREAMING_SNAKE_CASE__ : int = image_processor.post_process_semantic_segmentation(outputs=a_ , target_sizes=[(500, 300)] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape , a_ ) SCREAMING_SNAKE_CASE__ : Dict = image_processor.post_process_semantic_segmentation(outputs=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.Size((160, 160) ) self.assertEqual(segmentation[0].shape , a_ )
85
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable SCREAMING_SNAKE_CASE__ : Any = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["DPTFeatureExtractor"] SCREAMING_SNAKE_CASE__ : Tuple = ["DPTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST", "DPTForDepthEstimation", "DPTForSemanticSegmentation", "DPTModel", "DPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
def _a ( lowercase__ : str ): '''simple docstring''' if n_term == "": return [] SCREAMING_SNAKE_CASE__ : list = [] for temp in range(int(lowercase__ ) ): series.append(f'''1/{temp + 1}''' if series else '1' ) return series if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Harmonic Series") print("Formula of Harmonic Series => 1+1/2+1/3 ..... 1/n") print(harmonic_series(nth_term))
85
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 SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : int = 8 , **a_ : Union[str, Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = do_rescale SCREAMING_SNAKE_CASE__ : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Dict = do_pad SCREAMING_SNAKE_CASE__ : Any = pad_size def __lowercase( self : str , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : str )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = get_image_size(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE__ : List[Any] = (old_width // size + 1) * size - old_width return pad(a_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a_ ) def __lowercase( self : Tuple , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Dict , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : List[str] = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE__ : List[str] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE__ : Tuple = make_list_of_images(a_ ) if not valid_images(a_ ): 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. SCREAMING_SNAKE_CASE__ : List[str] = [to_numpy_array(a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE__ : str = [self.pad(a_ , size=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
85
1
import argparse import requests import torch from PIL import Image from transformers import ViTMAEConfig, ViTMAEForPreTraining, ViTMAEImageProcessor def _a ( lowercase__ : int ): '''simple docstring''' if "cls_token" in name: SCREAMING_SNAKE_CASE__ : List[str] = name.replace('cls_token' , 'vit.embeddings.cls_token' ) if "mask_token" in name: SCREAMING_SNAKE_CASE__ : Any = name.replace('mask_token' , 'decoder.mask_token' ) if "decoder_pos_embed" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] = name.replace('decoder_pos_embed' , 'decoder.decoder_pos_embed' ) if "pos_embed" in name and "decoder" not in name: SCREAMING_SNAKE_CASE__ : Dict = name.replace('pos_embed' , 'vit.embeddings.position_embeddings' ) if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE__ : int = name.replace('patch_embed.proj' , 'vit.embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE__ : str = name.replace('patch_embed.norm' , 'vit.embeddings.norm' ) if "decoder_blocks" in name: SCREAMING_SNAKE_CASE__ : Tuple = name.replace('decoder_blocks' , 'decoder.decoder_layers' ) if "blocks" in name: SCREAMING_SNAKE_CASE__ : Tuple = name.replace('blocks' , 'vit.encoder.layer' ) if "attn.proj" in name: SCREAMING_SNAKE_CASE__ : Tuple = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: SCREAMING_SNAKE_CASE__ : List[str] = name.replace('attn' , 'attention.self' ) if "norm1" in name: SCREAMING_SNAKE_CASE__ : str = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: SCREAMING_SNAKE_CASE__ : List[str] = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: SCREAMING_SNAKE_CASE__ : Any = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: SCREAMING_SNAKE_CASE__ : Tuple = name.replace('mlp.fc2' , 'output.dense' ) if "decoder_embed" in name: SCREAMING_SNAKE_CASE__ : List[str] = name.replace('decoder_embed' , 'decoder.decoder_embed' ) if "decoder_norm" in name: SCREAMING_SNAKE_CASE__ : Tuple = name.replace('decoder_norm' , 'decoder.decoder_norm' ) if "decoder_pred" in name: SCREAMING_SNAKE_CASE__ : Optional[Any] = name.replace('decoder_pred' , 'decoder.decoder_pred' ) if "norm.weight" in name and "decoder" not in name: SCREAMING_SNAKE_CASE__ : Optional[Any] = name.replace('norm.weight' , 'vit.layernorm.weight' ) if "norm.bias" in name and "decoder" not in name: SCREAMING_SNAKE_CASE__ : List[str] = name.replace('norm.bias' , 'vit.layernorm.bias' ) return name def _a ( lowercase__ : Tuple , lowercase__ : List[Any] ): '''simple docstring''' for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ : Optional[Any] = orig_state_dict.pop(lowercase__ ) if "qkv" in key: SCREAMING_SNAKE_CASE__ : str = key.split('.' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = int(key_split[1] ) if "decoder_blocks" in key: SCREAMING_SNAKE_CASE__ : Any = config.decoder_hidden_size SCREAMING_SNAKE_CASE__ : List[str] = 'decoder.decoder_layers.' if "weight" in key: SCREAMING_SNAKE_CASE__ : List[Any] = val[:dim, :] SCREAMING_SNAKE_CASE__ : Any = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE__ : Optional[Any] = val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE__ : Union[str, Any] = val[:dim] SCREAMING_SNAKE_CASE__ : Optional[Any] = val[dim : dim * 2] SCREAMING_SNAKE_CASE__ : Dict = val[-dim:] else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = config.hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'vit.encoder.layer.' if "weight" in key: SCREAMING_SNAKE_CASE__ : str = val[:dim, :] SCREAMING_SNAKE_CASE__ : Dict = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE__ : int = val[-dim:, :] elif "bias" in key: SCREAMING_SNAKE_CASE__ : Optional[int] = val[:dim] SCREAMING_SNAKE_CASE__ : List[str] = val[dim : dim * 2] SCREAMING_SNAKE_CASE__ : Union[str, Any] = val[-dim:] else: SCREAMING_SNAKE_CASE__ : int = val return orig_state_dict def _a ( lowercase__ : str , lowercase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = ViTMAEConfig() if "large" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = 10_24 SCREAMING_SNAKE_CASE__ : List[str] = 40_96 SCREAMING_SNAKE_CASE__ : int = 24 SCREAMING_SNAKE_CASE__ : Optional[int] = 16 elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 14 SCREAMING_SNAKE_CASE__ : Dict = 12_80 SCREAMING_SNAKE_CASE__ : List[Any] = 51_20 SCREAMING_SNAKE_CASE__ : Optional[Any] = 32 SCREAMING_SNAKE_CASE__ : Optional[Any] = 16 SCREAMING_SNAKE_CASE__ : Optional[int] = ViTMAEForPreTraining(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['model'] SCREAMING_SNAKE_CASE__ : List[str] = ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE__ : List[Any] = convert_state_dict(lowercase__ , lowercase__ ) model.load_state_dict(lowercase__ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = 'https://user-images.githubusercontent.com/11435359/147738734-196fd92f-9260-48d5-ba7e-bf103d29364d.jpg' SCREAMING_SNAKE_CASE__ : Dict = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : str = ViTMAEImageProcessor(size=config.image_size ) SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(images=lowercase__ , return_tensors='pt' ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = outputs.logits if "large" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-0.7309, -0.7128, -1.0169], [-1.0161, -0.9058, -1.1878], [-1.0478, -0.9411, -1.1911]] ) elif "huge" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[-1.1599, -0.9199, -1.2221], [-1.1952, -0.9269, -1.2307], [-1.2143, -0.9337, -1.2262]] ) else: SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[-0.9192, -0.8481, -1.1259], [-1.1349, -1.0034, -1.2599], [-1.1757, -1.0429, -1.2726]] ) # verify logits assert torch.allclose(logits[0, :3, :3] , lowercase__ , atol=1E-4 ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://dl.fbaipublicfiles.com/mae/visualize/mae_visualize_vit_base.pth", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args() convert_vit_mae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
85
from pathlib import Path import numpy as np from PIL import Image def _a ( lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return (gray > 1_27) & (gray <= 2_55) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros_like(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE__ : Optional[Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE__ : List[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE__ : List[str] = int(summation > 0 ) return output if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE__ : int = Path(__file__).resolve().parent / "image_data" / "lena.jpg" SCREAMING_SNAKE_CASE__ : int = np.array(Image.open(lena_path)) # kernel to be applied SCREAMING_SNAKE_CASE__ : str = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) SCREAMING_SNAKE_CASE__ : Optional[int] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image SCREAMING_SNAKE_CASE__ : Optional[int] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
85
1
from __future__ import annotations SCREAMING_SNAKE_CASE__ : str = list[list[int]] # assigning initial values to the grid SCREAMING_SNAKE_CASE__ : Matrix = [ [3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] # a grid with no solution SCREAMING_SNAKE_CASE__ : Matrix = [ [5, 0, 6, 5, 0, 8, 4, 0, 3], [5, 2, 0, 0, 0, 0, 0, 0, 2], [1, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0], ] def _a ( lowercase__ : Matrix , lowercase__ : int , lowercase__ : int , lowercase__ : int ): '''simple docstring''' for i in range(9 ): if grid[row][i] == n or grid[i][column] == n: return False for i in range(3 ): for j in range(3 ): if grid[(row - row % 3) + i][(column - column % 3) + j] == n: return False return True def _a ( lowercase__ : Matrix ): '''simple docstring''' for i in range(9 ): for j in range(9 ): if grid[i][j] == 0: return i, j return None def _a ( lowercase__ : Matrix ): '''simple docstring''' if location := find_empty_location(lowercase__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = location else: # If the location is ``None``, then the grid is solved. return grid for digit in range(1 , 10 ): if is_safe(lowercase__ , lowercase__ , lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = digit if sudoku(lowercase__ ) is not None: return grid SCREAMING_SNAKE_CASE__ : Tuple = 0 return None def _a ( lowercase__ : Matrix ): '''simple docstring''' for row in grid: for cell in row: print(lowercase__ , end=' ' ) print() if __name__ == "__main__": # make a copy of grid so that you can compare with the unmodified grid for example_grid in (initial_grid, no_solution): print("\nExample grid:\n" + "=" * 20) print_solution(example_grid) print("\nExample grid solution:") SCREAMING_SNAKE_CASE__ : List[Any] = sudoku(example_grid) if solution is not None: print_solution(solution) else: print("Cannot find a solution.")
85
def _a ( lowercase__ : int = 60_08_51_47_51_43 ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Dict = int(lowercase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : int = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 SCREAMING_SNAKE_CASE__ : str = i while n % i == 0: SCREAMING_SNAKE_CASE__ : List[Any] = n // i i += 1 return int(lowercase__ ) if __name__ == "__main__": print(F"""{solution() = }""")
85
1
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : List[str] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : List[Any] , a_ : Tuple , a_ : Optional[Any]=0 )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : List[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'french fries' SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : List[str] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : Tuple = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : int = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = components['vae'] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : List[Any] , a_ : Dict=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : Tuple = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Tuple = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : List[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : int )-> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : Dict = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : List[Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] SCREAMING_SNAKE_CASE__ : Any = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
85
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = int(lowercase__ ) if n_element < 1: SCREAMING_SNAKE_CASE__ : Tuple = ValueError('a should be a positive number' ) raise my_error SCREAMING_SNAKE_CASE__ : Any = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = (0, 0, 0) SCREAMING_SNAKE_CASE__ : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") SCREAMING_SNAKE_CASE__ : int = hamming(int(n)) print("-----------------------------------------------------") print(F"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
85
1
import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node SCREAMING_SNAKE_CASE__ : Any = 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = 3 class snake_case ( UpperCamelCase_ ): pass def _a ( lowercase__ : List[str] ): '''simple docstring''' for shard in shards: for i in range(lowercase__ ): yield {"i": i, "shard": shard} def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = int(os.environ['RANK'] ) SCREAMING_SNAKE_CASE__ : List[Any] = int(os.environ['WORLD_SIZE'] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ArgumentParser() parser.add_argument('--streaming' , type=lowercase__ ) parser.add_argument('--local_rank' , type=lowercase__ ) parser.add_argument('--num_workers' , type=lowercase__ , default=0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : List[str] = args.streaming SCREAMING_SNAKE_CASE__ : int = args.num_workers SCREAMING_SNAKE_CASE__ : Optional[int] = {'shards': [f'''shard_{shard_idx}''' for shard_idx in range(lowercase__ )]} SCREAMING_SNAKE_CASE__ : Any = IterableDataset.from_generator(lowercase__ , gen_kwargs=lowercase__ ) if not streaming: SCREAMING_SNAKE_CASE__ : int = Dataset.from_list(list(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = split_dataset_by_node(lowercase__ , rank=lowercase__ , world_size=lowercase__ ) SCREAMING_SNAKE_CASE__ : str = torch.utils.data.DataLoader(lowercase__ , num_workers=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = NUM_SHARDS * NUM_ITEMS_PER_SHARD SCREAMING_SNAKE_CASE__ : Tuple = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) SCREAMING_SNAKE_CASE__ : List[str] = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(f'''local_size {local_size} != expected_local_size {expected_local_size}''' ) if __name__ == "__main__": main()
85
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) if n == 0: return 0 SCREAMING_SNAKE_CASE__ : str = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : int = max( lowercase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase__ ) ) return max_revue def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : str = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : list , lowercase__ : list ): '''simple docstring''' if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: SCREAMING_SNAKE_CASE__ : List[str] = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Any = max( lowercase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = max_revenue return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. SCREAMING_SNAKE_CASE__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : int = 0 for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(lowercase__ , prices[j - 1] + max_rev[i - j] ) SCREAMING_SNAKE_CASE__ : Dict = max_revenue_i return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' if n < 0: SCREAMING_SNAKE_CASE__ : Tuple = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowercase__ ) if n > len(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = ( 'Each integral piece of rod must have a corresponding price. ' f'''Got n = {n} but length of prices = {len(lowercase__ )}''' ) raise ValueError(lowercase__ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [6, 10, 12, 15, 20, 23] SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. SCREAMING_SNAKE_CASE__ : Optional[Any] = 36 SCREAMING_SNAKE_CASE__ : Tuple = top_down_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = bottom_up_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = naive_cut_rod_recursive(lowercase__ , lowercase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : str = { "EleutherAI/gpt-neo-1.3B": "https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json", # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class snake_case ( UpperCamelCase_ ): lowercase_ = 'gpt_neo' lowercase_ = ['past_key_values'] lowercase_ = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'} def __init__( self : List[Any] , a_ : Union[str, Any]=5_0257 , a_ : Any=2048 , a_ : Dict=2048 , a_ : Optional[Any]=24 , a_ : List[str]=[[["global", "local"], 12]] , a_ : List[Any]=16 , a_ : List[Any]=None , a_ : Tuple=256 , a_ : List[Any]="gelu_new" , a_ : Optional[Any]=0.0 , a_ : Optional[Any]=0.0 , a_ : Dict=0.0 , a_ : Any=0.1 , a_ : List[Any]=1e-5 , a_ : List[str]=0.02 , a_ : List[str]=True , a_ : Tuple=5_0256 , a_ : str=5_0256 , **a_ : str , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : int = num_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_heads SCREAMING_SNAKE_CASE__ : Tuple = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = window_size SCREAMING_SNAKE_CASE__ : str = activation_function SCREAMING_SNAKE_CASE__ : List[str] = resid_dropout SCREAMING_SNAKE_CASE__ : str = embed_dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = classifier_dropout SCREAMING_SNAKE_CASE__ : Dict = layer_norm_epsilon SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = use_cache SCREAMING_SNAKE_CASE__ : Union[str, Any] = bos_token_id SCREAMING_SNAKE_CASE__ : Optional[Any] = eos_token_id SCREAMING_SNAKE_CASE__ : Union[str, Any] = attention_types SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.expand_attention_types_params(a_ ) if len(self.attention_layers ) != self.num_layers: raise ValueError( 'Configuration for convolutional module is incorrect. ' 'It is required that `len(config.attention_layers)` == `config.num_layers` ' F'''but is `len(config.attention_layers) = {len(self.attention_layers )}`, ''' F'''`config.num_layers = {self.num_layers}`. ''' '`config.attention_layers` is prepared using `config.attention_types`. ' 'Please verify the value of `config.attention_types` argument.' ) super().__init__(bos_token_id=a_ , eos_token_id=a_ , **a_ ) @staticmethod def __lowercase( a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def _a ( lowercase__ : List[str] , lowercase__ : str , lowercase__ : Optional[int] , lowercase__ : str ): '''simple docstring''' import torch SCREAMING_SNAKE_CASE__ : Any = input.size() SCREAMING_SNAKE_CASE__ : Dict = len(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = shape[dimension] SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(0 , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = torch.div(sizedim - size , lowercase__ , rounding_mode='floor' ) + 1 SCREAMING_SNAKE_CASE__ : int = torch.arange(lowercase__ ) + low_indices[:min_length][:, None] SCREAMING_SNAKE_CASE__ : Any = [slice(lowercase__ )] * rank SCREAMING_SNAKE_CASE__ : List[str] = indices SCREAMING_SNAKE_CASE__ : Tuple = input[s] SCREAMING_SNAKE_CASE__ : List[str] = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(lowercase__ ) def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' import torch SCREAMING_SNAKE_CASE__ : Any = torch.arange(1 , lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = torch.remainder(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = remainders == 0 SCREAMING_SNAKE_CASE__ : str = candidates[divisor_indices] SCREAMING_SNAKE_CASE__ : Any = torch.max(lowercase__ ) return largest_divisor, torch.div(lowercase__ , lowercase__ , rounding_mode='floor' ) class snake_case ( UpperCamelCase_ ): @property def __lowercase( self : Optional[int] )-> Mapping[str, Mapping[int, str]]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} ) if self.use_past: self.fill_with_past_key_values_(a_ , direction='inputs' ) SCREAMING_SNAKE_CASE__ : List[Any] = {0: 'batch', 1: 'past_sequence + sequence'} else: SCREAMING_SNAKE_CASE__ : str = {0: 'batch', 1: 'sequence'} return common_inputs @property def __lowercase( self : str )-> int: """simple docstring""" return self._config.num_heads def __lowercase( self : Optional[int] , a_ : PreTrainedTokenizer , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional[TensorType] = None , )-> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super(a_ , self ).generate_dummy_inputs( a_ , batch_size=a_ , seq_length=a_ , is_pair=a_ , framework=a_ ) # We need to order the input in the way they appears in the forward() SCREAMING_SNAKE_CASE__ : Optional[Any] = OrderedDict({'input_ids': common_inputs['input_ids']} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.' ) else: import torch SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Tuple = common_inputs['input_ids'].shape # Not using the same length for past_key_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = seqlen + 2 SCREAMING_SNAKE_CASE__ : str = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) SCREAMING_SNAKE_CASE__ : Any = [ (torch.zeros(a_ ), torch.zeros(a_ )) for _ in range(self.num_layers ) ] SCREAMING_SNAKE_CASE__ : Optional[Any] = common_inputs['attention_mask'] if self.use_past: SCREAMING_SNAKE_CASE__ : Tuple = ordered_inputs['attention_mask'].dtype SCREAMING_SNAKE_CASE__ : List[str] = torch.cat( [ordered_inputs['attention_mask'], torch.ones(a_ , a_ , dtype=a_ )] , dim=1 ) return ordered_inputs @property def __lowercase( self : Dict )-> int: """simple docstring""" return 13
85
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs SCREAMING_SNAKE_CASE__ : int = imread(r"digital_image_processing/image_data/lena_small.jpg") SCREAMING_SNAKE_CASE__ : List[Any] = cvtColor(img, COLOR_BGR2GRAY) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = cn.convert_to_negative(lowercase__ ) # assert negative_img array for at least one True assert negative_img.any() def _a ( ): '''simple docstring''' with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowercase__ , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ : List[str] = canny.canny(lowercase__ ) # assert canny array for at least one True assert canny_array.any() def _a ( ): '''simple docstring''' assert gg.gaussian_filter(lowercase__ , 5 , sigma=0.9 ).all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) SCREAMING_SNAKE_CASE__ : Tuple = conv.img_convolve(lowercase__ , lowercase__ ).astype(lowercase__ ) assert res.any() def _a ( ): '''simple docstring''' assert med.median_filter(lowercase__ , 3 ).any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = sob.sobel_filter(lowercase__ ) assert grad.any() and theta.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = sp.make_sepia(lowercase__ , 20 ) assert sepia.all() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = bs.Burkes(imread(lowercase__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = rs.NearestNeighbour(imread(lowercase__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ : Dict = imread(lowercase__ , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ : List[Any] = lbp.get_neighbors_pixel( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): SCREAMING_SNAKE_CASE__ : str = lbp.local_binary_value(lowercase__ , lowercase__ , lowercase__ ) assert lbp_image.any()
85
1
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case : def __init__( self : str , a_ : Dict , a_ : Any=13 , a_ : Optional[int]=32 , a_ : Tuple=3 , a_ : Optional[int]=4 , a_ : Optional[int]=[10, 20, 30, 40] , a_ : List[str]=[2, 2, 3, 2] , a_ : Tuple=True , a_ : Optional[Any]=True , a_ : Dict=37 , a_ : Dict="gelu" , a_ : List[Any]=10 , a_ : Optional[int]=0.02 , a_ : int=["stage2", "stage3", "stage4"] , a_ : Any=3 , a_ : Optional[int]=None , )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE__ : List[Any] = image_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : List[Any] = num_stages SCREAMING_SNAKE_CASE__ : List[Any] = hidden_sizes SCREAMING_SNAKE_CASE__ : str = depths SCREAMING_SNAKE_CASE__ : Tuple = is_training SCREAMING_SNAKE_CASE__ : str = use_labels SCREAMING_SNAKE_CASE__ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_act SCREAMING_SNAKE_CASE__ : Optional[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Any = initializer_range SCREAMING_SNAKE_CASE__ : str = out_features SCREAMING_SNAKE_CASE__ : List[str] = num_labels SCREAMING_SNAKE_CASE__ : str = scope SCREAMING_SNAKE_CASE__ : List[Any] = num_stages def __lowercase( self : Optional[int] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Any = self.get_config() return config, pixel_values, labels def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def __lowercase( self : Tuple )-> Any: """simple docstring""" return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=a_ , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=a_ , loss_ignore_index=255 , num_labels=self.num_labels , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : List[Any] , a_ : List[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = UperNetForSemanticSegmentation(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __lowercase( self : Optional[int] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Union[str, Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : int = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (UperNetForSemanticSegmentation,) if is_torch_available() else () lowercase_ = {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {} lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : int )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = UperNetModelTester(self ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" 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 __lowercase( self : Dict )-> Any: """simple docstring""" return def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : Tuple = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : int = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*a_ ) @unittest.skip(reason='UperNet does not use inputs_embeds' ) def __lowercase( self : Dict )-> Optional[Any]: """simple docstring""" pass @unittest.skip(reason='UperNet does not support input and output embeddings' ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" pass @unittest.skip(reason='UperNet does not have a base model' ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" pass @unittest.skip(reason='UperNet does not have a base model' ) def __lowercase( self : int )-> List[Any]: """simple docstring""" pass @require_torch_multi_gpu @unittest.skip(reason='UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def __lowercase( self : Optional[int] )-> List[str]: """simple docstring""" pass def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" def check_hidden_states_output(a_ : Tuple , a_ : Dict , a_ : str ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = model(**self._prepare_for_class(a_ , a_ ) ) SCREAMING_SNAKE_CASE__ : int = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(a_ ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(a_ , a_ , a_ ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Tuple = _config_zero_init(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = _config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(config=a_ ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @unittest.skip(reason='UperNet does not have tied weights' ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" pass @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = UperNetForSemanticSegmentation.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = hf_hub_download( repo_id='hf-internal-testing/fixtures_ade20k' , repo_type='dataset' , filename='ADE_val_00000001.jpg' ) SCREAMING_SNAKE_CASE__ : Any = Image.open(lowercase__ ).convert('RGB' ) return image @require_torch @require_vision @slow class snake_case ( unittest.TestCase ): def __lowercase( self : List[str] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny' ) SCREAMING_SNAKE_CASE__ : List[str] = UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny' ).to(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : str = processor(images=a_ , return_tensors='pt' ).to(a_ ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = model(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , a_ , atol=1e-4 ) ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny' ) SCREAMING_SNAKE_CASE__ : str = UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny' ).to(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = processor(images=a_ , return_tensors='pt' ).to(a_ ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(**a_ ) SCREAMING_SNAKE_CASE__ : int = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , a_ , atol=1e-4 ) )
85
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu SCREAMING_SNAKE_CASE__ : Any = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: SCREAMING_SNAKE_CASE__ : Tuple = json.load(f) @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : List[str] , a_ : Any )-> str: """simple docstring""" return FSMTTokenizer.from_pretrained(a_ ) def __lowercase( self : int , a_ : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FSMTForConditionalGeneration.from_pretrained(a_ ).to(a_ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['en-ru', 26.0], ['ru-en', 22.0], ['en-de', 22.0], ['de-en', 29.0], ] ) @slow def __lowercase( self : int , a_ : Optional[int] , a_ : str )-> List[str]: """simple docstring""" # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality SCREAMING_SNAKE_CASE__ : Any = F'''facebook/wmt19-{pair}''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_model(a_ ) SCREAMING_SNAKE_CASE__ : int = bleu_data[pair]['src'] SCREAMING_SNAKE_CASE__ : Optional[int] = bleu_data[pair]['tgt'] SCREAMING_SNAKE_CASE__ : Any = tokenizer(a_ , return_tensors='pt' , truncation=a_ , padding='longest' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( input_ids=batch.input_ids , num_beams=8 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.batch_decode( a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_bleu(a_ , a_ ) print(a_ ) self.assertGreaterEqual(scores['bleu'] , a_ )
85
1
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def _a ( lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor', ] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = emb.weight.shape SCREAMING_SNAKE_CASE__ : str = nn.Linear(lowercase__ , lowercase__ , bias=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = emb.weight.data return lin_layer def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = torch.load(lowercase__ , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = mam_aaa['args'] or mam_aaa['cfg']['model'] SCREAMING_SNAKE_CASE__ : Tuple = mam_aaa['model'] remove_ignore_keys_(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = state_dict['encoder.embed_tokens.weight'].shape[0] SCREAMING_SNAKE_CASE__ : str = MaMaaaConfig( vocab_size=lowercase__ , max_position_embeddings=10_24 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function='relu' , ) SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict['decoder.embed_tokens.weight'] SCREAMING_SNAKE_CASE__ : int = MaMaaaForConditionalGeneration(lowercase__ ) model.model.load_state_dict(lowercase__ , strict=lowercase__ ) SCREAMING_SNAKE_CASE__ : str = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument("fairseq_path", type=str, help="path to a model.pt on local filesystem.") parser.add_argument("pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") SCREAMING_SNAKE_CASE__ : Any = parser.parse_args() SCREAMING_SNAKE_CASE__ : Union[str, Any] = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
85
import os import pytest from attr import dataclass SCREAMING_SNAKE_CASE__ : int = "us-east-1" # defaults region @dataclass class snake_case : lowercase_ = 42 lowercase_ = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' lowercase_ = { 'task_name': 'mnli', 'per_device_train_batch_size': 16, 'per_device_eval_batch_size': 16, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 500, 'save_steps': 5_500, } lowercase_ = {**hyperparameters, 'max_steps': 1_000} @property def __lowercase( self : List[str] )-> str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return F'''{self.framework}-transfromers-test''' @property def __lowercase( self : int )-> str: """simple docstring""" return F'''./tests/sagemaker/scripts/{self.framework}''' @property def __lowercase( self : Tuple )-> str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def _a ( lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
85
1
import qiskit def _a ( lowercase__ : int = 2 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = qubits # Using Aer's simulator SCREAMING_SNAKE_CASE__ : Optional[Any] = qiskit.Aer.get_backend('aer_simulator' ) # Creating a Quantum Circuit acting on the q register SCREAMING_SNAKE_CASE__ : Dict = qiskit.QuantumCircuit(lowercase__ , lowercase__ ) # Adding a H gate on qubit 0 (now q0 in superposition) circuit.h(0 ) for i in range(1 , lowercase__ ): # Adding CX (CNOT) gate circuit.cx(i - 1 , lowercase__ ) # Mapping the quantum measurement to the classical bits circuit.measure(list(range(lowercase__ ) ) , list(range(lowercase__ ) ) ) # Now measuring any one qubit would affect other qubits to collapse # their super position and have same state as the measured one. # Executing the circuit on the simulator SCREAMING_SNAKE_CASE__ : str = qiskit.execute(lowercase__ , lowercase__ , shots=10_00 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print(F"""Total count for various states are: {quantum_entanglement(3)}""")
85
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = FunnelTokenizer lowercase_ = FunnelTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : str = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase( self : Any , **a_ : Any )-> List[str]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Tuple , **a_ : List[Any] )-> List[Any]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : int = 'unwanted, running' return input_text, output_text def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(a_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [7, 4, 5, 10, 8, 9] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer('UNwant\u00E9d,running' ) SCREAMING_SNAKE_CASE__ : List[Any] = len(inputs['input_ids'] ) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running' ) self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len )
85
1
SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n" SCREAMING_SNAKE_CASE__ : List[Any] = [{"type": "code", "content": INSTALL_CONTENT}] SCREAMING_SNAKE_CASE__ : str = { "{processor_class}": "FakeProcessorClass", "{model_class}": "FakeModelClass", "{object_class}": "FakeObjectClass", }
85
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 SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json", # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case ( UpperCamelCase_ ): lowercase_ = 'levit' def __init__( self : str , a_ : Optional[Any]=224 , a_ : List[str]=3 , a_ : Any=3 , a_ : Any=2 , a_ : Tuple=1 , a_ : int=16 , a_ : Optional[int]=[128, 256, 384] , a_ : Dict=[4, 8, 12] , a_ : List[str]=[4, 4, 4] , a_ : Any=[16, 16, 16] , a_ : Dict=0 , a_ : Tuple=[2, 2, 2] , a_ : Union[str, Any]=[2, 2, 2] , a_ : Optional[Any]=0.02 , **a_ : str , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : Any = kernel_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = stride SCREAMING_SNAKE_CASE__ : Any = padding SCREAMING_SNAKE_CASE__ : Any = hidden_sizes SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = key_dim SCREAMING_SNAKE_CASE__ : int = drop_path_rate SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = attention_ratio SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.11' ) @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowercase( self : Any )-> float: """simple docstring""" return 1e-4
85
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "studio-ousia/luke-base": "https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json", "studio-ousia/luke-large": "https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'luke' def __init__( self : Optional[int] , a_ : Tuple=5_0267 , a_ : Any=50_0000 , a_ : Dict=768 , a_ : Union[str, Any]=256 , a_ : Dict=12 , a_ : Any=12 , a_ : List[str]=3072 , a_ : List[Any]="gelu" , a_ : int=0.1 , a_ : int=0.1 , a_ : Tuple=512 , a_ : Dict=2 , a_ : List[Any]=0.02 , a_ : List[str]=1e-1_2 , a_ : Any=True , a_ : List[Any]=None , a_ : Any=1 , a_ : Optional[Any]=0 , a_ : Optional[Any]=2 , **a_ : Union[str, Any] , )-> Tuple: """simple docstring""" super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : List[Any] = entity_vocab_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_size SCREAMING_SNAKE_CASE__ : List[str] = entity_emb_size SCREAMING_SNAKE_CASE__ : Any = num_hidden_layers SCREAMING_SNAKE_CASE__ : str = num_attention_heads SCREAMING_SNAKE_CASE__ : str = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : int = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Tuple = use_entity_aware_attention SCREAMING_SNAKE_CASE__ : List[str] = classifier_dropout
85
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : List[str] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : List[Any] , a_ : Tuple , a_ : Optional[Any]=0 )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : List[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'french fries' SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : List[str] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : Tuple = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : int = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = components['vae'] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : List[Any] , a_ : Dict=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : Tuple = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Tuple = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : List[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : int )-> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : Dict = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : List[Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] SCREAMING_SNAKE_CASE__ : Any = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
85
1
from ....utils import logging SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): def __init__( self : Tuple , a_ : str , a_ : str=None , a_ : int=2048 )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = config.__dict__ SCREAMING_SNAKE_CASE__ : List[str] = modal_hidden_size if num_labels: SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels
85
import math from collections.abc import Callable def _a ( lowercase__ : Callable[[float], float] , lowercase__ : float , lowercase__ : float ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : float = xa SCREAMING_SNAKE_CASE__ : float = xa while True: if x_n == x_na or function(lowercase__ ) == function(lowercase__ ): raise ZeroDivisionError('float division by zero, could not find root' ) SCREAMING_SNAKE_CASE__ : float = x_na - ( function(lowercase__ ) / ((function(lowercase__ ) - function(lowercase__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na SCREAMING_SNAKE_CASE__ : Dict = x_na SCREAMING_SNAKE_CASE__ : List[str] = x_na def _a ( lowercase__ : float ): '''simple docstring''' return math.pow(lowercase__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
85
1
import faiss # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import requests # noqa: F401 # Here to have a nice missing dependency error message early on import sklearn # noqa: F401 # Here to have a nice missing dependency error message early on import tqdm # noqa: F401 # Here to have a nice missing dependency error message early on from mauve import compute_mauve # From: mauve-text import datasets SCREAMING_SNAKE_CASE__ : Optional[int] = "\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n booktitle = {NeurIPS},\n year = {2021}\n}\n\n" SCREAMING_SNAKE_CASE__ : Tuple = "\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n predictions: list of generated text to score. Each predictions\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\nOptional Args:\n num_buckets: the size of the histogram to quantize P and Q. Options: 'auto' (default) or an integer\n pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n kmeans_max_iter: maximum number of k-means iterations. Default 500\n featurize_model_name: name of the model from which features are obtained. Default 'gpt2-large' Use one of ['gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'].\n device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n max_text_length: maximum number of tokens to consider. Default 1024\n divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n mauve_scaling_factor: \"c\" from the paper. Default 5.\n verbose: If True (default), print running time updates\n seed: random seed to initialize k-means cluster assignments.\nReturns:\n mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n q_hist: same as above, but with q_text.\nExamples:\n\n >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n >>> import datasets\n >>> mauve = datasets.load_metric('mauve')\n >>> predictions = [\"hello there\", \"general kenobi\"]\n >>> references = [\"hello there\", \"general kenobi\"]\n >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n >>> print(out.mauve) # doctest: +SKIP\n 1.0\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): def __lowercase( self : int )-> Tuple: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='https://github.com/krishnap25/mauve' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/krishnap25/mauve'] , reference_urls=[ 'https://arxiv.org/abs/2102.01454', 'https://github.com/krishnap25/mauve', ] , ) def __lowercase( self : Optional[int] , a_ : int , a_ : Union[str, Any] , a_ : Optional[int]=None , a_ : Union[str, Any]=None , a_ : Tuple=None , a_ : int=None , a_ : Any="auto" , a_ : List[Any]=-1 , a_ : str=0.9 , a_ : str=5 , a_ : List[Any]=500 , a_ : Dict="gpt2-large" , a_ : Tuple=-1 , a_ : List[Any]=1024 , a_ : Dict=25 , a_ : Optional[int]=5 , a_ : Any=True , a_ : List[str]=25 , )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = compute_mauve( p_text=a_ , q_text=a_ , p_features=a_ , q_features=a_ , p_tokens=a_ , q_tokens=a_ , num_buckets=a_ , pca_max_data=a_ , kmeans_explained_var=a_ , kmeans_num_redo=a_ , kmeans_max_iter=a_ , featurize_model_name=a_ , device_id=a_ , max_text_length=a_ , divergence_curve_discretization_size=a_ , mauve_scaling_factor=a_ , verbose=a_ , seed=a_ , ) return out
85
from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'AutoImageProcessor' lowercase_ = 'AutoTokenizer' def __init__( self : List[Any] , a_ : int , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self.image_processor def __call__( self : Tuple , a_ : str=None , a_ : List[Any]=None , a_ : Optional[Any]=None , **a_ : Dict )-> Tuple: """simple docstring""" if text is None and images is None: raise ValueError('You have to specify either text or images. Both cannot be none.' ) if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer(a_ , return_tensors=a_ , **a_ ) if images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : List[str] = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : Dict , *a_ : Any , **a_ : Any )-> List[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Dict , *a_ : Union[str, Any] , **a_ : Optional[int] )-> Dict: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Any )-> Any: """simple docstring""" return ["input_ids", "attention_mask", "pixel_values"]
85
1
def _a ( lowercase__ : int = 2_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = [1, 2, 5, 10, 20, 50, 1_00, 2_00] SCREAMING_SNAKE_CASE__ : int = [0] * (pence + 1) SCREAMING_SNAKE_CASE__ : Dict = 1 # base case: 1 way to make 0 pence for coin in coins: for i in range(lowercase__ , pence + 1 , 1 ): number_of_ways[i] += number_of_ways[i - coin] return number_of_ways[pence] if __name__ == "__main__": assert solution(200) == 7_3682
85
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def _a ( lowercase__ : int = 3 ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(lowercase__ ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumRegister(lowercase__ , 'qr' ) SCREAMING_SNAKE_CASE__ : int = ClassicalRegister(lowercase__ , 'cr' ) SCREAMING_SNAKE_CASE__ : Tuple = QuantumCircuit(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = number_of_qubits for i in range(lowercase__ ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(lowercase__ ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , lowercase__ , lowercase__ ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(lowercase__ , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(lowercase__ , lowercase__ ) # simulate with 10000 shots SCREAMING_SNAKE_CASE__ : Optional[int] = Aer.get_backend('qasm_simulator' ) SCREAMING_SNAKE_CASE__ : Tuple = execute(lowercase__ , lowercase__ , shots=1_00_00 ) return job.result().get_counts(lowercase__ ) if __name__ == "__main__": print( F"""Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}""" )
85
1
from __future__ import annotations import bisect def _a ( lowercase__ : list[int] , lowercase__ : int , lowercase__ : int = 0 , lowercase__ : int = -1 ): '''simple docstring''' if hi < 0: SCREAMING_SNAKE_CASE__ : str = len(lowercase__ ) while lo < hi: SCREAMING_SNAKE_CASE__ : Optional[Any] = lo + (hi - lo) // 2 if sorted_collection[mid] < item: SCREAMING_SNAKE_CASE__ : Tuple = mid + 1 else: SCREAMING_SNAKE_CASE__ : str = mid return lo def _a ( lowercase__ : list[int] , lowercase__ : int , lowercase__ : int = 0 , lowercase__ : int = -1 ): '''simple docstring''' if hi < 0: SCREAMING_SNAKE_CASE__ : str = len(lowercase__ ) while lo < hi: SCREAMING_SNAKE_CASE__ : Any = lo + (hi - lo) // 2 if sorted_collection[mid] <= item: SCREAMING_SNAKE_CASE__ : int = mid + 1 else: SCREAMING_SNAKE_CASE__ : List[str] = mid return lo def _a ( lowercase__ : list[int] , lowercase__ : int , lowercase__ : int = 0 , lowercase__ : int = -1 ): '''simple docstring''' sorted_collection.insert(bisect_left(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) , lowercase__ ) def _a ( lowercase__ : list[int] , lowercase__ : int , lowercase__ : int = 0 , lowercase__ : int = -1 ): '''simple docstring''' sorted_collection.insert(bisect_right(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) , lowercase__ ) def _a ( lowercase__ : list[int] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : str = len(lowercase__ ) - 1 while left <= right: SCREAMING_SNAKE_CASE__ : Tuple = left + (right - left) // 2 SCREAMING_SNAKE_CASE__ : List[str] = sorted_collection[midpoint] if current_item == item: return midpoint elif item < current_item: SCREAMING_SNAKE_CASE__ : List[str] = midpoint - 1 else: SCREAMING_SNAKE_CASE__ : Tuple = midpoint + 1 return None def _a ( lowercase__ : list[int] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = bisect.bisect_left(lowercase__ , lowercase__ ) if index != len(lowercase__ ) and sorted_collection[index] == item: return index return None def _a ( lowercase__ : list[int] , lowercase__ : int , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if right < left: return None SCREAMING_SNAKE_CASE__ : Dict = left + (right - left) // 2 if sorted_collection[midpoint] == item: return midpoint elif sorted_collection[midpoint] > item: return binary_search_by_recursion(lowercase__ , lowercase__ , lowercase__ , midpoint - 1 ) else: return binary_search_by_recursion(lowercase__ , lowercase__ , midpoint + 1 , lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = input("Enter numbers separated by comma:\n").strip() SCREAMING_SNAKE_CASE__ : Union[str, Any] = sorted(int(item) for item in user_input.split(",")) SCREAMING_SNAKE_CASE__ : Optional[Any] = int(input("Enter a single number to be found in the list:\n")) SCREAMING_SNAKE_CASE__ : Optional[Any] = binary_search(collection, target) if result is None: print(F"""{target} was not found in {collection}.""") else: print(F"""{target} was found at position {result} in {collection}.""")
85
import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="%(message)s") def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return input_array.reshape((input_array.size, 1) ) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : int = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.mean(1 ) # Centralize the data of class i SCREAMING_SNAKE_CASE__ : Optional[Any] = data - column_reshape(lowercase__ ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(lowercase__ , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : Any = np.dot(lowercase__ , centered_data.T ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = features.mean(1 ) SCREAMING_SNAKE_CASE__ : List[str] = np.nan for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = features[:, labels == i] SCREAMING_SNAKE_CASE__ : int = data.shape[1] SCREAMING_SNAKE_CASE__ : List[Any] = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) SCREAMING_SNAKE_CASE__ : str = device_data * np.dot( column_reshape(lowercase__ ) - column_reshape(lowercase__ ) , (column_reshape(lowercase__ ) - column_reshape(lowercase__ )).T , ) return covariance_sum / features.shape[1] def _a ( lowercase__ : np.ndarray , lowercase__ : int ): '''simple docstring''' if features.any(): SCREAMING_SNAKE_CASE__ : Any = features.mean(1 ) # Center the dataset SCREAMING_SNAKE_CASE__ : Optional[Any] = features - np.reshape(lowercase__ , (data_mean.size, 1) ) SCREAMING_SNAKE_CASE__ : List[Any] = np.dot(lowercase__ , centered_data.T ) / features.shape[1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = np.linalg.eigh(lowercase__ ) # Take all the columns in the reverse order (-1), and then takes only the first SCREAMING_SNAKE_CASE__ : List[Any] = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.dot(filtered_eigenvectors.T , lowercase__ ) logging.info('Principal Component Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert classes > dimensions # Check if features have been already loaded if features.any: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = eigh( covariance_between_classes(lowercase__ , lowercase__ , lowercase__ ) , covariance_within_classes(lowercase__ , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = eigenvectors[:, ::-1][:, :dimensions] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = np.linalg.svd(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = svd_matrix[:, 0:dimensions] SCREAMING_SNAKE_CASE__ : int = np.dot(filtered_svd_matrix.T , lowercase__ ) logging.info('Linear Discriminant Analysis computed' ) return projected_data else: logging.basicConfig(level=logging.ERROR , format='%(message)s' , force=lowercase__ ) logging.error('Dataset empty' ) raise AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) SCREAMING_SNAKE_CASE__ : Tuple = np.array([0, 0, 0, 1, 1] ) SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : Dict = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : Optional[int] = linear_discriminant_analysis( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) if isinstance(lowercase__ , np.ndarray ): raise AssertionError( 'Did not raise AssertionError for dimensions > classes' ) assert error_info.type is AssertionError def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([[6.92820323, 8.66025404, 10.39230485], [3.0, 3.0, 3.0]] ) with pytest.raises(lowercase__ ) as error_info: SCREAMING_SNAKE_CASE__ : int = principal_component_analysis(lowercase__ , lowercase__ ) if not np.allclose(lowercase__ , lowercase__ ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
85
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "microsoft/markuplm-base": "https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json", "microsoft/markuplm-large": "https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'markuplm' def __init__( self : List[Any] , a_ : List[Any]=3_0522 , a_ : int=768 , a_ : Union[str, Any]=12 , a_ : str=12 , a_ : Any=3072 , a_ : Tuple="gelu" , a_ : Any=0.1 , a_ : Optional[Any]=0.1 , a_ : Optional[Any]=512 , a_ : int=2 , a_ : List[Any]=0.02 , a_ : str=1e-1_2 , a_ : Optional[int]=0 , a_ : List[str]=0 , a_ : Optional[Any]=2 , a_ : str=256 , a_ : List[str]=1024 , a_ : Optional[int]=216 , a_ : Tuple=1001 , a_ : Any=32 , a_ : Optional[int]=50 , a_ : Optional[int]="absolute" , a_ : Optional[int]=True , a_ : str=None , **a_ : Tuple , )-> Optional[Any]: """simple docstring""" super().__init__( pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ , ) SCREAMING_SNAKE_CASE__ : int = vocab_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_size SCREAMING_SNAKE_CASE__ : Any = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Dict = type_vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = initializer_range SCREAMING_SNAKE_CASE__ : Any = layer_norm_eps SCREAMING_SNAKE_CASE__ : str = position_embedding_type SCREAMING_SNAKE_CASE__ : Any = use_cache SCREAMING_SNAKE_CASE__ : Optional[int] = classifier_dropout # additional properties SCREAMING_SNAKE_CASE__ : Optional[Any] = max_depth SCREAMING_SNAKE_CASE__ : Tuple = max_xpath_tag_unit_embeddings SCREAMING_SNAKE_CASE__ : int = max_xpath_subs_unit_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = tag_pad_id SCREAMING_SNAKE_CASE__ : str = subs_pad_id SCREAMING_SNAKE_CASE__ : Optional[int] = xpath_unit_hidden_size
85
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = "Hello world! cécé herlolip" SCREAMING_SNAKE_CASE__ : Dict = namedtuple( "BertAbsConfig", [ "temp_dir", "large", "use_bert_emb", "finetune_bert", "encoder", "share_emb", "max_pos", "enc_layers", "enc_hidden_size", "enc_heads", "enc_ff_size", "enc_dropout", "dec_layers", "dec_hidden_size", "dec_heads", "dec_ff_size", "dec_dropout", ], ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = BertAbsConfig( temp_dir='.' , finetune_bert=lowercase__ , large=lowercase__ , share_emb=lowercase__ , use_bert_emb=lowercase__ , encoder='bert' , max_pos=5_12 , enc_layers=6 , enc_hidden_size=5_12 , enc_heads=8 , enc_ff_size=5_12 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=7_68 , dec_heads=8 , dec_ff_size=20_48 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ , lambda lowercase__ , lowercase__ : storage ) SCREAMING_SNAKE_CASE__ : Any = AbsSummarizer(lowercase__ , torch.device('cpu' ) , lowercase__ ) original.eval() SCREAMING_SNAKE_CASE__ : List[Any] = BertAbsSummarizer(lowercase__ , torch.device('cpu' ) ) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info('convert the model' ) new_model.bert.load_state_dict(original.bert.state_dict() ) new_model.decoder.load_state_dict(original.decoder.state_dict() ) new_model.generator.load_state_dict(original.generator.state_dict() ) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info('Make sure that the models\' outputs are identical' ) SCREAMING_SNAKE_CASE__ : Any = BertTokenizer.from_pretrained('bert-base-uncased' ) # prepare the model inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer.encode('This is sample éàalj\'-.' ) encoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor(lowercase__ ).unsqueeze(0 ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.encode('This is sample 3 éàalj\'-.' ) decoder_input_ids.extend([tokenizer.pad_token_id] * (5_12 - len(lowercase__ )) ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor(lowercase__ ).unsqueeze(0 ) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight ) ) == 0 # forward pass SCREAMING_SNAKE_CASE__ : int = encoder_input_ids SCREAMING_SNAKE_CASE__ : Any = decoder_input_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None # The original model does not apply the geneator layer immediatly but rather in # the beam search (where it combines softmax + linear layer). Since we already # apply the softmax in our generation process we only apply the linear layer here. # We make sure that the outputs of the full stack are identical SCREAMING_SNAKE_CASE__ : Optional[Any] = original(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = original.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = new_model( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = new_model.generator(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = torch.max(torch.abs(output_converted_model - output_original_model ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.max(torch.abs(output_converted_generator - output_original_generator ) ).item() print('Maximum absolute difference beween weights: {:.2f}'.format(lowercase__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.allclose(lowercase__ , lowercase__ , atol=1E-3 ) if are_identical: logging.info('all weights are equal up to 1e-3' ) else: raise ValueError('the weights are different. The new model is likely different from the original one.' ) # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info('saving the model\'s state dictionary' ) torch.save( new_model.state_dict() , './bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() parser.add_argument( "--bertabs_checkpoint_path", default=None, type=str, required=True, help="Path the official PyTorch dump.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the output PyTorch model.", ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
85
1
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 SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : int = 8 , **a_ : Union[str, Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = do_rescale SCREAMING_SNAKE_CASE__ : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Dict = do_pad SCREAMING_SNAKE_CASE__ : Any = pad_size def __lowercase( self : str , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : str )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = get_image_size(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE__ : List[Any] = (old_width // size + 1) * size - old_width return pad(a_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a_ ) def __lowercase( self : Tuple , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Dict , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : List[str] = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE__ : List[str] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE__ : Tuple = make_list_of_images(a_ ) if not valid_images(a_ ): 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. SCREAMING_SNAKE_CASE__ : List[str] = [to_numpy_array(a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE__ : str = [self.pad(a_ , size=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
85
from __future__ import annotations import inspect import unittest from typing import List, Tuple from transformers import RegNetConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case : def __init__( self : Tuple , a_ : int , a_ : Optional[int]=3 , a_ : Tuple=32 , a_ : Any=3 , a_ : Tuple=10 , a_ : Optional[int]=[10, 20, 30, 40] , a_ : List[Any]=[1, 1, 2, 1] , a_ : int=True , a_ : Optional[Any]=True , a_ : Any="relu" , a_ : int=3 , a_ : List[Any]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : Tuple = embeddings_size SCREAMING_SNAKE_CASE__ : str = hidden_sizes SCREAMING_SNAKE_CASE__ : Optional[int] = depths SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = scope SCREAMING_SNAKE_CASE__ : str = len(a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_config() return config, pixel_values, labels def __lowercase( self : str )-> str: """simple docstring""" 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 , ) def __lowercase( self : List[str] , a_ : int , a_ : Any , a_ : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = TFRegNetModel(config=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , training=a_ ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def __lowercase( self : Union[str, Any] , a_ : Dict , a_ : int , a_ : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_labels SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetForImageClassification(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ , training=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_tf class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else () lowercase_ = ( {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification} if is_tf_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = TFRegNetModelTester(self ) SCREAMING_SNAKE_CASE__ : int = ConfigTester(self , config_class=a_ , has_text_modality=a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" return @unittest.skip(reason='RegNet does not use inputs_embeds' ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" super().test_keras_fit() @unittest.skip(reason='RegNet does not support input and output embeddings' ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" pass def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : List[Any] = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[int] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" def check_hidden_states_output(a_ : int , a_ : Union[str, Any] , a_ : Tuple ): SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(**self._prepare_for_class(a_ , a_ ) , training=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(a_ ) , expected_num_stages + 1 ) # RegNet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Dict = ['basic', 'bottleneck'] for model_class in self.all_model_classes: for layer_type in layers_type: SCREAMING_SNAKE_CASE__ : List[Any] = layer_type SCREAMING_SNAKE_CASE__ : Union[str, Any] = True check_hidden_states_output(a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True check_hidden_states_output(a_ , a_ , a_ ) def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() def check_equivalence(a_ : str , a_ : Tuple , a_ : Optional[int] , a_ : Union[str, Any]={} ): SCREAMING_SNAKE_CASE__ : int = model(a_ , return_dict=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , return_dict=a_ , **a_ ).to_tuple() def recursive_check(a_ : List[Any] , a_ : int ): if isinstance(a_ , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a_ , a_ ): recursive_check(a_ , a_ ) elif tuple_object is None: return else: self.assertTrue( all(tf.equal(a_ , a_ ) ) , msg=( 'Tuple and dict output are not equal. Difference:' F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}''' ) , ) recursive_check(a_ , a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self._prepare_for_class(a_ , a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) check_equivalence(a_ , a_ , a_ , {'output_hidden_states': True} ) def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def __lowercase( self : Any )-> List[str]: """simple docstring""" for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[int] = TFRegNetModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_tf @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : List[Any] )-> int: """simple docstring""" return ( AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : Any = prepare_img() SCREAMING_SNAKE_CASE__ : str = image_processor(images=a_ , return_tensors='tf' ) # forward pass SCREAMING_SNAKE_CASE__ : Tuple = model(**a_ , training=a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Optional[int] = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = tf.constant([-0.4180, -1.5051, -3.4836] ) tf.debugging.assert_near(outputs.logits[0, :3] , a_ , atol=1e-4 )
85
1
from typing import List, Optional, Union import numpy as np import tensorflow as tf from .utils import logging SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[tf.Tensor, np.ndarray] ): '''simple docstring''' if isinstance(lowercase__ , np.ndarray ): return list(tensor.shape ) SCREAMING_SNAKE_CASE__ : str = tf.shape(lowercase__ ) if tensor.shape == tf.TensorShape(lowercase__ ): return dynamic SCREAMING_SNAKE_CASE__ : Optional[Any] = tensor.shape.as_list() return [dynamic[i] if s is None else s for i, s in enumerate(lowercase__ )] def _a ( lowercase__ : tf.Tensor , lowercase__ : Optional[int] = None , lowercase__ : Optional[str] = None ): '''simple docstring''' return tf.nn.softmax(logits=logits + 1E-9 , axis=lowercase__ , name=lowercase__ ) def _a ( lowercase__ : List[Any] , lowercase__ : Optional[int] , lowercase__ : Tuple , lowercase__ : Optional[Any]=1E-5 , lowercase__ : Union[str, Any]=-1 ): '''simple docstring''' if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(lowercase__ , lowercase__ ): raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.' ) # Get mean and variance on the axis to be normalized SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = tf.nn.moments(lowercase__ , axes=[axis] , keepdims=lowercase__ ) if axis != -1: # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions # on every dimension except axis SCREAMING_SNAKE_CASE__ : List[Any] = [1] * inputs.shape.rank SCREAMING_SNAKE_CASE__ : Dict = shape_list(lowercase__ )[axis] SCREAMING_SNAKE_CASE__ : Optional[int] = tf.reshape(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tf.reshape(lowercase__ , lowercase__ ) # Compute layer normalization using the batch_normalization # function. SCREAMING_SNAKE_CASE__ : Optional[int] = tf.nn.batch_normalization( lowercase__ , lowercase__ , lowercase__ , offset=lowercase__ , scale=lowercase__ , variance_epsilon=lowercase__ , ) return outputs def _a ( lowercase__ : List[Any] , lowercase__ : Dict=0 , lowercase__ : List[Any]=-1 ): '''simple docstring''' if end_dim < 0: end_dim += input.shape.rank if start_dim < 0: start_dim += input.shape.rank if start_dim == end_dim: return input SCREAMING_SNAKE_CASE__ : str = tf.shape(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] ) SCREAMING_SNAKE_CASE__ : List[Any] = tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]] , axis=0 ) return tf.reshape(lowercase__ , lowercase__ ) def _a ( lowercase__ : tf.Tensor ): '''simple docstring''' if not isinstance(lowercase__ , tf.Tensor ): SCREAMING_SNAKE_CASE__ : Optional[int] = tf.convert_to_tensor(lowercase__ ) # Catches stray NumPy inputs if encoder_attention_mask.shape.rank == 3: SCREAMING_SNAKE_CASE__ : str = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.shape.rank == 2: SCREAMING_SNAKE_CASE__ : Any = encoder_attention_mask[:, None, None, :] # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow # /transformer/transformer_layers.py#L270 # encoder_extended_attention_mask = (encoder_extended_attention_mask == # encoder_extended_attention_mask.transpose(-1, -2)) SCREAMING_SNAKE_CASE__ : Any = ( tf.cast(1 , encoder_attention_mask.dtype ) - encoder_extended_attention_mask ) * encoder_extended_attention_mask.dtype.min return encoder_extended_attention_mask def _a ( lowercase__ : tf.Tensor , lowercase__ : int , lowercase__ : str = "input_ids" ): '''simple docstring''' tf.debugging.assert_less( lowercase__ , tf.cast(lowercase__ , dtype=tensor.dtype ) , message=( f'''The maximum value of {tensor_name} ({tf.math.reduce_max(lowercase__ )}) must be smaller than the embedding ''' f'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.''' ) , ) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any] , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 6_45_12 # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT` # because in that case even chunking the array would not make the saving # possible. SCREAMING_SNAKE_CASE__ : str = [x for x in data if len(lowercase__ ) > HDF5_OBJECT_HEADER_LIMIT] # Expecting this to never be true. if bad_attributes: raise RuntimeError( 'The following attributes cannot be saved to HDF5 file because ' f'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} ''' f'''bytes: {bad_attributes}''' ) SCREAMING_SNAKE_CASE__ : Any = np.asarray(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array_split(lowercase__ , lowercase__ ) # This will never loop forever thanks to the test above. while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data ): num_chunks += 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array_split(lowercase__ , lowercase__ ) if num_chunks > 1: for chunk_id, chunk_data in enumerate(lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = chunk_data else: SCREAMING_SNAKE_CASE__ : Tuple = data def _a ( lowercase__ : List[Any] , lowercase__ : int ): '''simple docstring''' if name in group.attrs: SCREAMING_SNAKE_CASE__ : Dict = [n.decode('utf8' ) if hasattr(lowercase__ , 'decode' ) else n for n in group.attrs[name]] else: SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = 0 while "%s%d" % (name, chunk_id) in group.attrs: data.extend( [n.decode('utf8' ) if hasattr(lowercase__ , 'decode' ) else n for n in group.attrs['%s%d' % (name, chunk_id)]] ) chunk_id += 1 return data def _a ( lowercase__ : Optional[int] ): '''simple docstring''' def _expand_single_ad_tensor(lowercase__ : Optional[int] ): if isinstance(lowercase__ , tf.Tensor ) and t.shape.rank == 1: return tf.expand_dims(lowercase__ , axis=-1 ) return t return tf.nest.map_structure(_expand_single_ad_tensor , lowercase__ )
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Tuple = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = int(lowercase__ ) if n_element < 1: SCREAMING_SNAKE_CASE__ : Tuple = ValueError('a should be a positive number' ) raise my_error SCREAMING_SNAKE_CASE__ : Any = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = (0, 0, 0) SCREAMING_SNAKE_CASE__ : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") SCREAMING_SNAKE_CASE__ : int = hamming(int(n)) print("-----------------------------------------------------") print(F"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
85
def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) if n == 0: return 0 SCREAMING_SNAKE_CASE__ : str = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : int = max( lowercase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase__ ) ) return max_revue def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : str = [float('-inf' ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : list , lowercase__ : list ): '''simple docstring''' if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: SCREAMING_SNAKE_CASE__ : List[str] = float('-inf' ) for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Any = max( lowercase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase__ , lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : Tuple = max_revenue return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' _enforce_args(lowercase__ , lowercase__ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. SCREAMING_SNAKE_CASE__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )] SCREAMING_SNAKE_CASE__ : int = 0 for i in range(1 , n + 1 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rev[i] for j in range(1 , i + 1 ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(lowercase__ , prices[j - 1] + max_rev[i - j] ) SCREAMING_SNAKE_CASE__ : Dict = max_revenue_i return max_rev[n] def _a ( lowercase__ : int , lowercase__ : list ): '''simple docstring''' if n < 0: SCREAMING_SNAKE_CASE__ : Tuple = f'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(lowercase__ ) if n > len(lowercase__ ): SCREAMING_SNAKE_CASE__ : Tuple = ( 'Each integral piece of rod must have a corresponding price. ' f'''Got n = {n} but length of prices = {len(lowercase__ )}''' ) raise ValueError(lowercase__ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [6, 10, 12, 15, 20, 23] SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. SCREAMING_SNAKE_CASE__ : Optional[Any] = 36 SCREAMING_SNAKE_CASE__ : Tuple = top_down_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = bottom_up_cut_rod(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = naive_cut_rod_recursive(lowercase__ , lowercase__ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
85
1
from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration SCREAMING_SNAKE_CASE__ : List[str] = HfArgumentParser(InitializationArguments) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args() # Load codeparrot tokenizer trained for Python code tokenization SCREAMING_SNAKE_CASE__ : int = AutoTokenizer.from_pretrained(args.tokenizer_name) # Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks SCREAMING_SNAKE_CASE__ : Optional[int] = { "vocab_size": len(tokenizer), "scale_attn_by_inverse_layer_idx": True, "reorder_and_upcast_attn": True, } # Load model config (GPT-2 large in this case) SCREAMING_SNAKE_CASE__ : Any = AutoConfig.from_pretrained(args.config_name, **config_kwargs) # Initialize new model with config SCREAMING_SNAKE_CASE__ : Tuple = AutoModelForCausalLM.from_config(config) # Save model to the hub model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
85
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_tests_dir("fixtures/test_sentencepiece.model") SCREAMING_SNAKE_CASE__ : Optional[int] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") SCREAMING_SNAKE_CASE__ : Any = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = CamembertTokenizer lowercase_ = CamembertTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Tuple )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Dict = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = '<pad>' SCREAMING_SNAKE_CASE__ : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>NOTUSED' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(a_ ) , 1004 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1005 ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = CamembertTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : int = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : str = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.convert_ids_to_tokens(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Tuple = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : str = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 2_7575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 2_2804, 1_8818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 1_0326, 24, 2267, 20, 416, 5072, 1_5612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. SCREAMING_SNAKE_CASE__ : str = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='camembert-base' , revision='3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf' , sequences=a_ , )
85
1
import os import unittest from huggingface_hub.utils import are_progress_bars_disabled import transformers.models.bart.tokenization_bart from transformers import logging from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context from transformers.utils.logging import disable_progress_bar, enable_progress_bar class snake_case ( unittest.TestCase ): def __lowercase( self : Dict )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = logging.get_logger() # the current default level is logging.WARNING SCREAMING_SNAKE_CASE__ : Tuple = logging.get_verbosity() logging.set_verbosity_error() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_warning() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_info() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) logging.set_verbosity_debug() self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity() ) # restore to the original level logging.set_verbosity(a_ ) def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_verbosity() SCREAMING_SNAKE_CASE__ : Optional[int] = logging.get_logger('transformers.models.bart.tokenization_bart' ) SCREAMING_SNAKE_CASE__ : Any = 'Testing 1, 2, 3' # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) if level_origin <= logging.WARNING: with CaptureLogger(a_ ) as cl: logger.warning(a_ ) self.assertEqual(cl.out , msg + '\n' ) # this is setting the level for all of `transformers.*` loggers logging.set_verbosity_error() # should not be able to log warnings with CaptureLogger(a_ ) as cl: logger.warning(a_ ) self.assertEqual(cl.out , '' ) # should be able to log warnings again logging.set_verbosity_warning() with CaptureLogger(a_ ) as cl: logger.warning(a_ ) self.assertEqual(cl.out , msg + '\n' ) # restore to the original level logging.set_verbosity(a_ ) @mockenv(TRANSFORMERS_VERBOSITY='error' ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() # this action activates the env var SCREAMING_SNAKE_CASE__ : int = logging.get_logger('transformers.models.bart.tokenization_bart' ) SCREAMING_SNAKE_CASE__ : int = os.getenv('TRANSFORMERS_VERBOSITY' , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.log_levels[env_level_str] SCREAMING_SNAKE_CASE__ : str = logging.get_verbosity() self.assertEqual( a_ , a_ , F'''TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}''' , ) # restore to the original level SCREAMING_SNAKE_CASE__ : List[Any] = '' transformers.utils.logging._reset_library_root_logger() @mockenv(TRANSFORMERS_VERBOSITY='super-error' ) def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" # reset for the env var to take effect, next time some logger call is made transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE__ : int = logging.logging.getLogger() with CaptureLogger(a_ ) as cl: # this action activates the env var logging.get_logger('transformers.models.bart.tokenization_bart' ) self.assertIn('Unknown option TRANSFORMERS_VERBOSITY=super-error' , cl.out ) # no need to restore as nothing was changed def __lowercase( self : int )-> Tuple: """simple docstring""" # testing `logger.warning_advice()` transformers.utils.logging._reset_library_root_logger() SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger('transformers.models.bart.tokenization_bart' ) SCREAMING_SNAKE_CASE__ : Dict = 'Testing 1, 2, 3' with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='1' ): # nothing should be logged as env var disables this method with CaptureLogger(a_ ) as cl: logger.warning_advice(a_ ) self.assertEqual(cl.out , '' ) with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='' ): # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset with CaptureLogger(a_ ) as cl: logger.warning_advice(a_ ) self.assertEqual(cl.out , msg + '\n' ) def _a ( ): '''simple docstring''' disable_progress_bar() assert are_progress_bars_disabled() enable_progress_bar() assert not are_progress_bars_disabled()
85
from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available from ...utils import OptionalDependencyNotAvailable SCREAMING_SNAKE_CASE__ : Any = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["DPTFeatureExtractor"] SCREAMING_SNAKE_CASE__ : Tuple = ["DPTImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[Any] = [ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST", "DPTForDepthEstimation", "DPTForSemanticSegmentation", "DPTModel", "DPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_dpt import DPTFeatureExtractor from .image_processing_dpt import DPTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dpt import ( DPT_PRETRAINED_MODEL_ARCHIVE_LIST, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel, DPTPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
85
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 SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : int = 8 , **a_ : Union[str, Any] , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = do_rescale SCREAMING_SNAKE_CASE__ : Union[str, Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Dict = do_pad SCREAMING_SNAKE_CASE__ : Any = pad_size def __lowercase( self : str , a_ : np.ndarray , a_ : float , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : str )-> np.ndarray: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : Any , a_ : np.ndarray , a_ : int , a_ : Optional[Union[str, ChannelDimension]] = None )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = get_image_size(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = (old_height // size + 1) * size - old_height SCREAMING_SNAKE_CASE__ : List[Any] = (old_width // size + 1) * size - old_width return pad(a_ , ((0, pad_height), (0, pad_width)) , mode='symmetric' , data_format=a_ ) def __lowercase( self : Tuple , a_ : ImageInput , a_ : Optional[bool] = None , a_ : Optional[float] = None , a_ : Optional[bool] = None , a_ : Optional[int] = None , a_ : Optional[Union[str, TensorType]] = None , a_ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **a_ : Dict , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : List[str] = do_pad if do_pad is not None else self.do_pad SCREAMING_SNAKE_CASE__ : List[str] = pad_size if pad_size is not None else self.pad_size SCREAMING_SNAKE_CASE__ : Tuple = make_list_of_images(a_ ) if not valid_images(a_ ): 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. SCREAMING_SNAKE_CASE__ : List[str] = [to_numpy_array(a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] if do_pad: SCREAMING_SNAKE_CASE__ : str = [self.pad(a_ , size=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ )
85
1
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ : List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'deta' lowercase_ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Union[str, Any] , a_ : Dict=None , a_ : Tuple=900 , a_ : Any=2048 , a_ : List[str]=6 , a_ : int=2048 , a_ : Union[str, Any]=8 , a_ : List[Any]=6 , a_ : List[Any]=1024 , a_ : Union[str, Any]=8 , a_ : List[Any]=0.0 , a_ : List[Any]=True , a_ : str="relu" , a_ : Any=256 , a_ : Optional[Any]=0.1 , a_ : Dict=0.0 , a_ : Union[str, Any]=0.0 , a_ : Optional[int]=0.02 , a_ : Optional[Any]=1.0 , a_ : Dict=True , a_ : int=False , a_ : List[str]="sine" , a_ : Dict=5 , a_ : Tuple=4 , a_ : Union[str, Any]=4 , a_ : Dict=True , a_ : str=300 , a_ : Union[str, Any]=True , a_ : List[Any]=True , a_ : List[Any]=1 , a_ : List[str]=5 , a_ : Optional[int]=2 , a_ : List[str]=1 , a_ : Dict=1 , a_ : List[str]=5 , a_ : List[Any]=2 , a_ : Union[str, Any]=0.1 , a_ : int=0.25 , **a_ : List[str] , )-> int: """simple docstring""" if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) SCREAMING_SNAKE_CASE__ : Optional[int] = CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : Optional[int] = backbone_config.pop('model_type' ) SCREAMING_SNAKE_CASE__ : Dict = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE__ : List[Any] = config_class.from_dict(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = backbone_config SCREAMING_SNAKE_CASE__ : Any = num_queries SCREAMING_SNAKE_CASE__ : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Tuple = d_model SCREAMING_SNAKE_CASE__ : Optional[Any] = encoder_ffn_dim SCREAMING_SNAKE_CASE__ : Union[str, Any] = encoder_layers SCREAMING_SNAKE_CASE__ : str = encoder_attention_heads SCREAMING_SNAKE_CASE__ : str = decoder_ffn_dim SCREAMING_SNAKE_CASE__ : List[Any] = decoder_layers SCREAMING_SNAKE_CASE__ : List[Any] = decoder_attention_heads SCREAMING_SNAKE_CASE__ : str = dropout SCREAMING_SNAKE_CASE__ : Dict = attention_dropout SCREAMING_SNAKE_CASE__ : Optional[int] = activation_dropout SCREAMING_SNAKE_CASE__ : int = activation_function SCREAMING_SNAKE_CASE__ : List[Any] = init_std SCREAMING_SNAKE_CASE__ : List[Any] = init_xavier_std SCREAMING_SNAKE_CASE__ : str = encoder_layerdrop SCREAMING_SNAKE_CASE__ : List[str] = auxiliary_loss SCREAMING_SNAKE_CASE__ : Tuple = position_embedding_type # deformable attributes SCREAMING_SNAKE_CASE__ : List[Any] = num_feature_levels SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_n_points SCREAMING_SNAKE_CASE__ : Optional[Any] = decoder_n_points SCREAMING_SNAKE_CASE__ : Any = two_stage SCREAMING_SNAKE_CASE__ : Union[str, Any] = two_stage_num_proposals SCREAMING_SNAKE_CASE__ : Any = with_box_refine SCREAMING_SNAKE_CASE__ : Union[str, Any] = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher SCREAMING_SNAKE_CASE__ : Dict = class_cost SCREAMING_SNAKE_CASE__ : Optional[int] = bbox_cost SCREAMING_SNAKE_CASE__ : int = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE__ : Any = mask_loss_coefficient SCREAMING_SNAKE_CASE__ : Optional[int] = dice_loss_coefficient SCREAMING_SNAKE_CASE__ : int = bbox_loss_coefficient SCREAMING_SNAKE_CASE__ : Optional[int] = giou_loss_coefficient SCREAMING_SNAKE_CASE__ : str = eos_coefficient SCREAMING_SNAKE_CASE__ : List[str] = focal_alpha super().__init__(is_encoder_decoder=a_ , **a_ ) @property def __lowercase( self : Optional[int] )-> int: """simple docstring""" return self.encoder_attention_heads @property def __lowercase( self : Optional[Any] )-> int: """simple docstring""" return self.d_model def __lowercase( self : Optional[int] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ : Tuple = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE__ : Dict = self.__class__.model_type return output
85
from pathlib import Path import numpy as np from PIL import Image def _a ( lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] return 0.2989 * r + 0.5870 * g + 0.1140 * b def _a ( lowercase__ : np.ndarray ): '''simple docstring''' return (gray > 1_27) & (gray <= 2_55) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = np.zeros_like(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = np.zeros( (image.shape[0] + kernel.shape[0] - 1, image.shape[1] + kernel.shape[1] - 1) ) # Copy image to padded image SCREAMING_SNAKE_CASE__ : Optional[Any] = image # Iterate over image & apply kernel for x in range(image.shape[1] ): for y in range(image.shape[0] ): SCREAMING_SNAKE_CASE__ : List[Any] = ( kernel * image_padded[y : y + kernel.shape[0], x : x + kernel.shape[1]] ).sum() SCREAMING_SNAKE_CASE__ : List[str] = int(summation > 0 ) return output if __name__ == "__main__": # read original image SCREAMING_SNAKE_CASE__ : int = Path(__file__).resolve().parent / "image_data" / "lena.jpg" SCREAMING_SNAKE_CASE__ : int = np.array(Image.open(lena_path)) # kernel to be applied SCREAMING_SNAKE_CASE__ : str = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) SCREAMING_SNAKE_CASE__ : Optional[int] = dilation(gray_to_binary(rgb_to_gray(lena)), structuring_element) # Save the output image SCREAMING_SNAKE_CASE__ : Optional[int] = Image.fromarray(output).convert("RGB") pil_img.save("result_dilation.png")
85
1
from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'BlipImageProcessor' lowercase_ = 'AutoTokenizer' def __init__( self : Optional[int] , a_ : Union[str, Any] , a_ : List[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = False super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.image_processor def __call__( self : List[Any] , a_ : ImageInput = None , a_ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , a_ : bool = True , a_ : Union[bool, str, PaddingStrategy] = False , a_ : Union[bool, str, TruncationStrategy] = None , a_ : Optional[int] = None , a_ : int = 0 , a_ : Optional[int] = None , a_ : Optional[bool] = None , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = True , a_ : Optional[Union[str, TensorType]] = None , **a_ : int , )-> BatchEncoding: """simple docstring""" if images is None and text is None: raise ValueError('You have to specify either images or text.' ) # Get only text if images is None: SCREAMING_SNAKE_CASE__ : int = self.tokenizer SCREAMING_SNAKE_CASE__ : Dict = self.tokenizer( text=a_ , add_special_tokens=a_ , padding=a_ , truncation=a_ , max_length=a_ , stride=a_ , pad_to_multiple_of=a_ , return_attention_mask=a_ , return_overflowing_tokens=a_ , return_special_tokens_mask=a_ , return_offsets_mapping=a_ , return_token_type_ids=a_ , return_length=a_ , verbose=a_ , return_tensors=a_ , **a_ , ) return text_encoding # add pixel_values SCREAMING_SNAKE_CASE__ : Optional[Any] = self.image_processor(a_ , return_tensors=a_ ) if text is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer( text=a_ , add_special_tokens=a_ , padding=a_ , truncation=a_ , max_length=a_ , stride=a_ , pad_to_multiple_of=a_ , return_attention_mask=a_ , return_overflowing_tokens=a_ , return_special_tokens_mask=a_ , return_offsets_mapping=a_ , return_token_type_ids=a_ , return_length=a_ , verbose=a_ , return_tensors=a_ , **a_ , ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = None if text_encoding is not None: encoding_image_processor.update(a_ ) return encoding_image_processor def __lowercase( self : Any , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : List[Any] , *a_ : Any , **a_ : Dict )-> int: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property # Copied from transformers.models.blip.processing_blip.BlipProcessor.model_input_names def __lowercase( self : Tuple )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.tokenizer.model_input_names SCREAMING_SNAKE_CASE__ : List[str] = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
85
def _a ( lowercase__ : int = 60_08_51_47_51_43 ): '''simple docstring''' try: SCREAMING_SNAKE_CASE__ : Dict = int(lowercase__ ) except (TypeError, ValueError): raise TypeError('Parameter n must be int or castable to int.' ) if n <= 0: raise ValueError('Parameter n must be greater than or equal to one.' ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : int = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 SCREAMING_SNAKE_CASE__ : str = i while n % i == 0: SCREAMING_SNAKE_CASE__ : List[Any] = n // i i += 1 return int(lowercase__ ) if __name__ == "__main__": print(F"""{solution() = }""")
85
1
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 SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json", # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case ( UpperCamelCase_ ): lowercase_ = 'levit' def __init__( self : str , a_ : Optional[Any]=224 , a_ : List[str]=3 , a_ : Any=3 , a_ : Any=2 , a_ : Tuple=1 , a_ : int=16 , a_ : Optional[int]=[128, 256, 384] , a_ : Dict=[4, 8, 12] , a_ : List[str]=[4, 4, 4] , a_ : Any=[16, 16, 16] , a_ : Dict=0 , a_ : Tuple=[2, 2, 2] , a_ : Union[str, Any]=[2, 2, 2] , a_ : Optional[Any]=0.02 , **a_ : str , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : Any = kernel_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = stride SCREAMING_SNAKE_CASE__ : Any = padding SCREAMING_SNAKE_CASE__ : Any = hidden_sizes SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = key_dim SCREAMING_SNAKE_CASE__ : int = drop_path_rate SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = attention_ratio SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.11' ) @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowercase( self : Any )-> float: """simple docstring""" return 1e-4
85
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = int(lowercase__ ) if n_element < 1: SCREAMING_SNAKE_CASE__ : Tuple = ValueError('a should be a positive number' ) raise my_error SCREAMING_SNAKE_CASE__ : Any = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = (0, 0, 0) SCREAMING_SNAKE_CASE__ : Any = 1 while index < n_element: while hamming_list[i] * 2 <= hamming_list[-1]: i += 1 while hamming_list[j] * 3 <= hamming_list[-1]: j += 1 while hamming_list[k] * 5 <= hamming_list[-1]: k += 1 hamming_list.append( min(hamming_list[i] * 2 , hamming_list[j] * 3 , hamming_list[k] * 5 ) ) index += 1 return hamming_list if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = input("Enter the last number (nth term) of the Hamming Number Series: ") print("Formula of Hamming Number Series => 2^i * 3^j * 5^k") SCREAMING_SNAKE_CASE__ : int = hamming(int(n)) print("-----------------------------------------------------") print(F"""The list with nth numbers is: {hamming_numbers}""") print("-----------------------------------------------------")
85
1
def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = [1] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = 0, 0, 0 SCREAMING_SNAKE_CASE__ : Any = ugly_nums[ia] * 2 SCREAMING_SNAKE_CASE__ : Any = ugly_nums[ia] * 3 SCREAMING_SNAKE_CASE__ : Optional[Any] = ugly_nums[ia] * 5 for _ in range(1 , lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = min(lowercase__ , lowercase__ , lowercase__ ) ugly_nums.append(lowercase__ ) if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ : Tuple = ugly_nums[ia] * 2 if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ : Dict = ugly_nums[ia] * 3 if next_num == next_a: ia += 1 SCREAMING_SNAKE_CASE__ : str = ugly_nums[ia] * 5 return ugly_nums[-1] if __name__ == "__main__": from doctest import testmod testmod(verbose=True) print(F"""{ugly_numbers(200) = }""")
85
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys SCREAMING_SNAKE_CASE__ : str = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class snake_case ( UpperCamelCase_ ): def __init__( self : Dict , a_ : str , a_ : Optional[int]=None , a_ : str=True , a_ : Optional[Any]=None , **a_ : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = parent SCREAMING_SNAKE_CASE__ : str = config_class SCREAMING_SNAKE_CASE__ : Union[str, Any] = has_text_modality SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs SCREAMING_SNAKE_CASE__ : str = common_properties def __lowercase( self : List[str] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.config_class(**self.inputs_dict ) SCREAMING_SNAKE_CASE__ : int = ( ['hidden_size', 'num_attention_heads', 'num_hidden_layers'] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(['vocab_size'] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(a_ , a_ ) , msg=F'''`{prop}` does not exist''' ) # Test that config has the common properties as setter for idx, name in enumerate(a_ ): try: setattr(a_ , a_ , a_ ) self.parent.assertEqual( getattr(a_ , a_ ) , a_ , msg=F'''`{name} value {idx} expected, but was {getattr(a_ , a_ )}''' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(a_ ): try: SCREAMING_SNAKE_CASE__ : Tuple = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(a_ , a_ ) , a_ , msg=F'''`{name} value {idx} expected, but was {getattr(a_ , a_ )}''' ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.config_class(**self.inputs_dict ) SCREAMING_SNAKE_CASE__ : Tuple = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , a_ ) def __lowercase( self : int )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Optional[Any] = os.path.join(a_ , 'config.json' ) config_first.to_json_file(a_ ) SCREAMING_SNAKE_CASE__ : int = self.config_class.from_json_file(a_ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.config_class.from_pretrained(a_ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def __lowercase( self : Any )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.config_class(**self.inputs_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'test' with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(a_ , a_ ) config_first.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.config_class.from_pretrained(a_ , subfolder=a_ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) SCREAMING_SNAKE_CASE__ : int = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def __lowercase( self : Any )-> Dict: """simple docstring""" if self.config_class.is_composition: return SCREAMING_SNAKE_CASE__ : Any = self.config_class() self.parent.assertIsNotNone(a_ ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = copy.deepcopy(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.config_class(**a_ ) SCREAMING_SNAKE_CASE__ : Any = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(('torch_dtype', config.torch_dtype, torch.floataa) ) elif getattr(a_ , a_ ) != value: wrong_values.append((key, getattr(a_ , a_ ), value) ) if len(a_ ) > 0: SCREAMING_SNAKE_CASE__ : str = '\n'.join([F'''- {v[0]}: got {v[1]} instead of {v[2]}''' for v in wrong_values] ) raise ValueError(F'''The following keys were not properly set in the config:\n{errors}''' ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Optional[int] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
85
1
import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def _a ( lowercase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [] embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight''', f'''stage{idx}.patch_embed.proj.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias''', f'''stage{idx}.patch_embed.proj.bias''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight''', f'''stage{idx}.patch_embed.norm.weight''', ) ) embed.append( ( f'''cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias''', f'''stage{idx}.patch_embed.norm.bias''', ) ) return embed def _a ( lowercase__ : Union[str, Any] , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = [] attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked''', f'''stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_q.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_k.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj_v.bias''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.attn.proj.weight''', ) ) attention_weights.append( ( f'''cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.attn.proj.bias''', ) ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias''', f'''stage{idx}.blocks.{cnt}.mlp.fc2.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight''', f'''stage{idx}.blocks.{cnt}.norm1.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias''', f'''stage{idx}.blocks.{cnt}.norm1.bias''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight''', f'''stage{idx}.blocks.{cnt}.norm2.weight''') ) attention_weights.append( (f'''cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias''', f'''stage{idx}.blocks.{cnt}.norm2.bias''') ) return attention_weights def _a ( lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] token.append((f'''cvt.encoder.stages.{idx}.cls_token''', 'stage2.cls_token') ) return token def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] head.append(('layernorm.weight', 'norm.weight') ) head.append(('layernorm.bias', 'norm.bias') ) head.append(('classifier.weight', 'head.weight') ) head.append(('classifier.bias', 'head.bias') ) return head def _a ( lowercase__ : Optional[Any] , lowercase__ : Any , lowercase__ : Optional[int] , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : int = 10_00 SCREAMING_SNAKE_CASE__ : Dict = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : str = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Dict = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Optional[Any] = idalabel SCREAMING_SNAKE_CASE__ : Union[str, Any] = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = CvtConfig(num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit('/' , 1 )[-1][4:6] == "13": SCREAMING_SNAKE_CASE__ : int = [1, 2, 10] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit('/' , 1 )[-1][4:6] == "21": SCREAMING_SNAKE_CASE__ : Dict = [1, 4, 16] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: SCREAMING_SNAKE_CASE__ : Dict = [2, 2, 20] SCREAMING_SNAKE_CASE__ : Any = [3, 12, 16] SCREAMING_SNAKE_CASE__ : List[str] = [1_92, 7_68, 10_24] SCREAMING_SNAKE_CASE__ : List[Any] = CvtForImageClassification(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' ) SCREAMING_SNAKE_CASE__ : Optional[int] = image_size SCREAMING_SNAKE_CASE__ : List[str] = torch.load(lowercase__ , map_location=torch.device('cpu' ) ) SCREAMING_SNAKE_CASE__ : Any = OrderedDict() SCREAMING_SNAKE_CASE__ : Dict = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: SCREAMING_SNAKE_CASE__ : Tuple = list_of_state_dict + cls_token(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = list_of_state_dict + embeddings(lowercase__ ) for cnt in range(config.depth[idx] ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = list_of_state_dict + attention(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = list_of_state_dict + final() for gg in list_of_state_dict: print(lowercase__ ) for i in range(len(lowercase__ ) ): SCREAMING_SNAKE_CASE__ : Optional[int] = original_weights[list_of_state_dict[i][1]] model.load_state_dict(lowercase__ ) model.save_pretrained(lowercase__ ) image_processor.save_pretrained(lowercase__ ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[str] = argparse.ArgumentParser() parser.add_argument( "--cvt_model", default="cvt-w24", type=str, help="Name of the cvt model you'd like to convert.", ) parser.add_argument( "--image_size", default=384, type=int, help="Input Image Size", ) parser.add_argument( "--cvt_file_name", default=r"cvtmodels\CvT-w24-384x384-IN-22k.pth", type=str, help="Input Image Size", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
85
import numpy as np from cva import COLOR_BGR2GRAY, cvtColor, imread from numpy import array, uinta from PIL import Image from digital_image_processing import change_contrast as cc from digital_image_processing import convert_to_negative as cn from digital_image_processing import sepia as sp from digital_image_processing.dithering import burkes as bs from digital_image_processing.edge_detection import canny from digital_image_processing.filters import convolve as conv from digital_image_processing.filters import gaussian_filter as gg from digital_image_processing.filters import local_binary_pattern as lbp from digital_image_processing.filters import median_filter as med from digital_image_processing.filters import sobel_filter as sob from digital_image_processing.resize import resize as rs SCREAMING_SNAKE_CASE__ : int = imread(r"digital_image_processing/image_data/lena_small.jpg") SCREAMING_SNAKE_CASE__ : List[Any] = cvtColor(img, COLOR_BGR2GRAY) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = cn.convert_to_negative(lowercase__ ) # assert negative_img array for at least one True assert negative_img.any() def _a ( ): '''simple docstring''' with Image.open('digital_image_processing/image_data/lena_small.jpg' ) as img: # Work around assertion for response assert str(cc.change_contrast(lowercase__ , 1_10 ) ).startswith( '<PIL.Image.Image image mode=RGB size=100x100 at' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = canny.gen_gaussian_kernel(9 , sigma=1.4 ) # Assert ambiguous array assert resp.all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = imread('digital_image_processing/image_data/lena_small.jpg' , 0 ) # assert ambiguous array for all == True assert canny_img.all() SCREAMING_SNAKE_CASE__ : List[str] = canny.canny(lowercase__ ) # assert canny array for at least one True assert canny_array.any() def _a ( ): '''simple docstring''' assert gg.gaussian_filter(lowercase__ , 5 , sigma=0.9 ).all() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]] ) SCREAMING_SNAKE_CASE__ : Tuple = conv.img_convolve(lowercase__ , lowercase__ ).astype(lowercase__ ) assert res.any() def _a ( ): '''simple docstring''' assert med.median_filter(lowercase__ , 3 ).any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = sob.sobel_filter(lowercase__ ) assert grad.any() and theta.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = sp.make_sepia(lowercase__ , 20 ) assert sepia.all() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = bs.Burkes(imread(lowercase__ , 1 ) , 1_20 ) burkes.process() assert burkes.output_img.any() def _a ( lowercase__ : str = "digital_image_processing/image_data/lena_small.jpg" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = rs.NearestNeighbour(imread(lowercase__ , 1 ) , 4_00 , 2_00 ) nn.process() assert nn.output.any() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 'digital_image_processing/image_data/lena.jpg' # Reading the image and converting it to grayscale. SCREAMING_SNAKE_CASE__ : Dict = imread(lowercase__ , 0 ) # Test for get_neighbors_pixel function() return not None SCREAMING_SNAKE_CASE__ : str = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = image[x_coordinate][y_coordinate] SCREAMING_SNAKE_CASE__ : List[Any] = lbp.get_neighbors_pixel( lowercase__ , lowercase__ , lowercase__ , lowercase__ ) assert neighbors_pixels is not None # Test for local_binary_pattern function() # Create a numpy array as the same height and width of read image SCREAMING_SNAKE_CASE__ : Optional[Any] = np.zeros((image.shape[0], image.shape[1]) ) # Iterating through the image and calculating the local binary pattern value # for each pixel. for i in range(0 , image.shape[0] ): for j in range(0 , image.shape[1] ): SCREAMING_SNAKE_CASE__ : str = lbp.local_binary_value(lowercase__ , lowercase__ , lowercase__ ) assert lbp_image.any()
85
1
from __future__ import annotations import requests def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = f'''https://hacker-news.firebaseio.com/v0/item/{story_id}.json?print=pretty''' return requests.get(lowercase__ ).json() def _a ( lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(lowercase__ ).json()[:max_stories] return [get_hackernews_story(lowercase__ ) for story_id in story_ids] def _a ( lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = hackernews_top_stories(lowercase__ ) return "\n".join('* [{title}]({url})'.format(**lowercase__ ) for story in stories ) if __name__ == "__main__": print(hackernews_top_stories_as_markdown())
85
import io import json import unittest from parameterized import parameterized from transformers import FSMTForConditionalGeneration, FSMTTokenizer from transformers.testing_utils import get_tests_dir, require_torch, slow, torch_device from utils import calculate_bleu SCREAMING_SNAKE_CASE__ : Any = get_tests_dir() + "/test_data/fsmt/fsmt_val_data.json" with io.open(filename, "r", encoding="utf-8") as f: SCREAMING_SNAKE_CASE__ : Tuple = json.load(f) @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : List[str] , a_ : Any )-> str: """simple docstring""" return FSMTTokenizer.from_pretrained(a_ ) def __lowercase( self : int , a_ : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FSMTForConditionalGeneration.from_pretrained(a_ ).to(a_ ) if torch_device == "cuda": model.half() return model @parameterized.expand( [ ['en-ru', 26.0], ['ru-en', 22.0], ['en-de', 22.0], ['de-en', 29.0], ] ) @slow def __lowercase( self : int , a_ : Optional[int] , a_ : str )-> List[str]: """simple docstring""" # note: this test is not testing the best performance since it only evals a small batch # but it should be enough to detect a regression in the output quality SCREAMING_SNAKE_CASE__ : Any = F'''facebook/wmt19-{pair}''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_model(a_ ) SCREAMING_SNAKE_CASE__ : int = bleu_data[pair]['src'] SCREAMING_SNAKE_CASE__ : Optional[int] = bleu_data[pair]['tgt'] SCREAMING_SNAKE_CASE__ : Any = tokenizer(a_ , return_tensors='pt' , truncation=a_ , padding='longest' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( input_ids=batch.input_ids , num_beams=8 , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.batch_decode( a_ , skip_special_tokens=a_ , clean_up_tokenization_spaces=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_bleu(a_ , a_ ) print(a_ ) self.assertGreaterEqual(scores['bleu'] , a_ )
85
1
from __future__ import annotations def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = get_failure_array(lowercase__ ) # 2) Step through text searching for pattern SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = 0, 0 # index into text, pattern while i < len(lowercase__ ): if pattern[j] == text[i]: if j == (len(lowercase__ ) - 1): return True j += 1 # if this is a prefix in our pattern # just go back far enough to continue elif j > 0: SCREAMING_SNAKE_CASE__ : Tuple = failure[j - 1] continue i += 1 return False def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = [0] SCREAMING_SNAKE_CASE__ : List[Any] = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 while j < len(lowercase__ ): if pattern[i] == pattern[j]: i += 1 elif i > 0: SCREAMING_SNAKE_CASE__ : Optional[int] = failure[i - 1] continue j += 1 failure.append(lowercase__ ) return failure if __name__ == "__main__": # Test 1) SCREAMING_SNAKE_CASE__ : Optional[Any] = "abc1abc12" SCREAMING_SNAKE_CASE__ : Any = "alskfjaldsabc1abc1abc12k23adsfabcabc" SCREAMING_SNAKE_CASE__ : Dict = "alskfjaldsk23adsfabcabc" assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) SCREAMING_SNAKE_CASE__ : Optional[int] = "ABABX" SCREAMING_SNAKE_CASE__ : Tuple = "ABABZABABYABABX" assert kmp(pattern, text) # Test 3) SCREAMING_SNAKE_CASE__ : Any = "AAAB" SCREAMING_SNAKE_CASE__ : Optional[int] = "ABAAAAAB" assert kmp(pattern, text) # Test 4) SCREAMING_SNAKE_CASE__ : Optional[Any] = "abcdabcy" SCREAMING_SNAKE_CASE__ : str = "abcxabcdabxabcdabcdabcy" assert kmp(pattern, text) # Test 5) SCREAMING_SNAKE_CASE__ : int = "aabaabaaa" assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
85
import os import pytest from attr import dataclass SCREAMING_SNAKE_CASE__ : int = "us-east-1" # defaults region @dataclass class snake_case : lowercase_ = 42 lowercase_ = 'arn:aws:iam::558105141721:role/sagemaker_execution_role' lowercase_ = { 'task_name': 'mnli', 'per_device_train_batch_size': 16, 'per_device_eval_batch_size': 16, 'do_train': True, 'do_eval': True, 'do_predict': True, 'output_dir': '/opt/ml/model', 'overwrite_output_dir': True, 'max_steps': 500, 'save_steps': 5_500, } lowercase_ = {**hyperparameters, 'max_steps': 1_000} @property def __lowercase( self : List[str] )-> str: """simple docstring""" if self.framework == "pytorch": return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, ] else: return [ {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, ] @property def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" return F'''{self.framework}-transfromers-test''' @property def __lowercase( self : int )-> str: """simple docstring""" return F'''./tests/sagemaker/scripts/{self.framework}''' @property def __lowercase( self : Tuple )-> str: """simple docstring""" if self.framework == "pytorch": return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" else: return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" @pytest.fixture(scope='class' ) def _a ( lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = SageMakerTestEnvironment(framework=request.cls.framework )
85
1
import torch import torch.nn as nn from transformers.modeling_utils import ModuleUtilsMixin from transformers.models.ta.modeling_ta import TaBlock, TaConfig, TaLayerNorm from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): @register_to_config def __init__( self : List[str] , a_ : int , a_ : int , a_ : int , a_ : float , a_ : int , a_ : int , a_ : int , a_ : int , a_ : str , a_ : bool = False , )-> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Dict = nn.Embedding(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = nn.Embedding(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Union[str, Any] = nn.Dropout(p=a_ ) SCREAMING_SNAKE_CASE__ : Dict = TaConfig( vocab_size=a_ , d_model=a_ , num_heads=a_ , d_kv=a_ , d_ff=a_ , dropout_rate=a_ , feed_forward_proj=a_ , is_decoder=a_ , is_encoder_decoder=a_ , ) SCREAMING_SNAKE_CASE__ : int = nn.ModuleList() for lyr_num in range(a_ ): SCREAMING_SNAKE_CASE__ : Tuple = TaBlock(a_ ) self.encoders.append(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = TaLayerNorm(a_ ) SCREAMING_SNAKE_CASE__ : int = nn.Dropout(p=a_ ) def __lowercase( self : List[str] , a_ : int , a_ : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.token_embedder(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = encoder_input_tokens.shape[1] SCREAMING_SNAKE_CASE__ : int = torch.arange(a_ , device=encoder_input_tokens.device ) x += self.position_encoding(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.dropout_pre(a_ ) # inverted the attention mask SCREAMING_SNAKE_CASE__ : List[str] = encoder_input_tokens.size() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_extended_attention_mask(a_ , a_ ) for lyr in self.encoders: SCREAMING_SNAKE_CASE__ : Optional[Any] = lyr(a_ , a_ )[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.layer_norm(a_ ) return self.dropout_post(a_ ), encoder_inputs_mask
85
import os import unittest from transformers import FunnelTokenizer, FunnelTokenizerFast from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = FunnelTokenizer lowercase_ = FunnelTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" super().setUp() SCREAMING_SNAKE_CASE__ : str = [ '<unk>', '<cls>', '<sep>', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] SCREAMING_SNAKE_CASE__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase( self : Any , **a_ : Any )-> List[str]: """simple docstring""" return FunnelTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Tuple , **a_ : List[Any] )-> List[Any]: """simple docstring""" return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'UNwant\u00E9d,running' SCREAMING_SNAKE_CASE__ : int = 'unwanted, running' return input_text, output_text def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.tokenizer_class(self.vocab_file ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(a_ , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(a_ ) , [7, 4, 5, 10, 8, 9] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizers(do_lower_case=a_ ) for tokenizer in tokenizers: SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer('UNwant\u00E9d,running' ) SCREAMING_SNAKE_CASE__ : List[Any] = len(inputs['input_ids'] ) - 1 self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('UNwant\u00E9d,running' , 'UNwant\u00E9d,running' ) self.assertListEqual(inputs['token_type_ids'] , [2] + [0] * sentence_len + [1] * sentence_len )
85
1
def _a ( lowercase__ : int = 10 , lowercase__ : int = 10_00 , lowercase__ : bool = True ): '''simple docstring''' assert ( isinstance(lowercase__ , lowercase__ ) and isinstance(lowercase__ , lowercase__ ) and isinstance(lowercase__ , lowercase__ ) ), "Invalid type of value(s) specified to function!" if min_val > max_val: raise ValueError('Invalid value for min_val or max_val (min_value < max_value)' ) return min_val if option else max_val def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((number_a + number_a) / 2 ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : int ): '''simple docstring''' assert ( isinstance(lowercase__ , lowercase__ ) and isinstance(lowercase__ , lowercase__ ) and isinstance(lowercase__ , lowercase__ ) ), 'argument values must be type of "int"' if lower > higher: raise ValueError('argument value for lower and higher must be(lower > higher)' ) if not lower < to_guess < higher: raise ValueError( 'guess value must be within the range of lower and higher value' ) def answer(lowercase__ : int ) -> str: if number > to_guess: return "high" elif number < to_guess: return "low" else: return "same" print('started...' ) SCREAMING_SNAKE_CASE__ : Optional[int] = lower SCREAMING_SNAKE_CASE__ : List[str] = higher SCREAMING_SNAKE_CASE__ : str = [] while True: SCREAMING_SNAKE_CASE__ : List[str] = get_avg(lowercase__ , lowercase__ ) last_numbers.append(lowercase__ ) if answer(lowercase__ ) == "low": SCREAMING_SNAKE_CASE__ : str = number elif answer(lowercase__ ) == "high": SCREAMING_SNAKE_CASE__ : Any = number else: break print(f'''guess the number : {last_numbers[-1]}''' ) print(f'''details : {last_numbers!s}''' ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = int(input('Enter lower value : ' ).strip() ) SCREAMING_SNAKE_CASE__ : Dict = int(input('Enter high value : ' ).strip() ) SCREAMING_SNAKE_CASE__ : Any = int(input('Enter value to guess : ' ).strip() ) guess_the_number(lowercase__ , lowercase__ , lowercase__ ) if __name__ == "__main__": main()
85
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 SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json", # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case ( UpperCamelCase_ ): lowercase_ = 'levit' def __init__( self : str , a_ : Optional[Any]=224 , a_ : List[str]=3 , a_ : Any=3 , a_ : Any=2 , a_ : Tuple=1 , a_ : int=16 , a_ : Optional[int]=[128, 256, 384] , a_ : Dict=[4, 8, 12] , a_ : List[str]=[4, 4, 4] , a_ : Any=[16, 16, 16] , a_ : Dict=0 , a_ : Tuple=[2, 2, 2] , a_ : Union[str, Any]=[2, 2, 2] , a_ : Optional[Any]=0.02 , **a_ : str , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : Any = kernel_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = stride SCREAMING_SNAKE_CASE__ : Any = padding SCREAMING_SNAKE_CASE__ : Any = hidden_sizes SCREAMING_SNAKE_CASE__ : List[Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = depths SCREAMING_SNAKE_CASE__ : List[str] = key_dim SCREAMING_SNAKE_CASE__ : int = drop_path_rate SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : List[str] = attention_ratio SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = [ ['Subsample', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['Subsample', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.11' ) @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def __lowercase( self : Any )-> float: """simple docstring""" return 1e-4
85
1
import os import tempfile import unittest from transformers import FlaubertConfig, is_torch_available from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FlaubertForMultipleChoice, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertModel, FlaubertWithLMHeadModel, ) from transformers.models.flaubert.modeling_flaubert import FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case ( UpperCamelCase_ ): def __init__( self : str , a_ : Optional[Any] , a_ : Optional[Any]=13 , a_ : List[Any]=7 , a_ : Optional[int]=True , a_ : Any=True , a_ : Dict=True , a_ : Tuple=True , a_ : str=True , a_ : Tuple=False , a_ : Optional[int]=False , a_ : Union[str, Any]=False , a_ : int=2 , a_ : Dict=99 , a_ : Union[str, Any]=0 , a_ : str=32 , a_ : Union[str, Any]=5 , a_ : Any=4 , a_ : int=0.1 , a_ : Any=0.1 , a_ : List[str]=512 , a_ : Optional[int]=12 , a_ : Union[str, Any]=2 , a_ : List[Any]=0.02 , a_ : Tuple=3 , a_ : int=4 , a_ : Optional[int]="last" , a_ : List[str]=None , a_ : List[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : Optional[int] = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : str = use_input_lengths SCREAMING_SNAKE_CASE__ : Optional[int] = use_token_type_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : List[str] = gelu_activation SCREAMING_SNAKE_CASE__ : str = sinusoidal_embeddings SCREAMING_SNAKE_CASE__ : Any = causal SCREAMING_SNAKE_CASE__ : Optional[Any] = asm SCREAMING_SNAKE_CASE__ : Union[str, Any] = n_langs SCREAMING_SNAKE_CASE__ : Dict = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = n_special SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : int = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : str = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Dict = initializer_range SCREAMING_SNAKE_CASE__ : Dict = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = num_choices SCREAMING_SNAKE_CASE__ : List[Any] = summary_type SCREAMING_SNAKE_CASE__ : Optional[Any] = use_proj SCREAMING_SNAKE_CASE__ : List[str] = scope def __lowercase( self : Optional[int] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_input_lengths: SCREAMING_SNAKE_CASE__ : Optional[Any] = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Optional[int] = None SCREAMING_SNAKE_CASE__ : List[Any] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size] , 2 ).float() SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : 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 __lowercase( self : int )-> Any: """simple docstring""" return FlaubertConfig( 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 , ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Any , a_ : Union[str, Any] , a_ : Any , a_ : Union[str, Any] , a_ : List[str] , a_ : List[Any] , a_ : int , a_ : Any , )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = FlaubertModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , lengths=a_ , langs=a_ ) SCREAMING_SNAKE_CASE__ : int = model(a_ , langs=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : str , a_ : str , a_ : int , a_ : Union[str, Any] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Any , a_ : int , a_ : Tuple , a_ : str , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaubertWithLMHeadModel(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Any , a_ : Optional[Any] , a_ : Union[str, Any] , a_ : str , a_ : int , a_ : Union[str, Any] , a_ : List[Any] , a_ : Any , a_ : Any , a_ : Union[str, Any] , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = FlaubertForQuestionAnsweringSimple(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , start_positions=a_ , end_positions=a_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowercase( self : Tuple , a_ : Tuple , a_ : int , a_ : Optional[Any] , a_ : Optional[int] , a_ : Tuple , a_ : List[Any] , a_ : int , a_ : Optional[int] , a_ : int , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaubertForQuestionAnswering(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = model( a_ , start_positions=a_ , end_positions=a_ , cls_index=a_ , is_impossible=a_ , p_mask=a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = model( a_ , start_positions=a_ , end_positions=a_ , cls_index=a_ , is_impossible=a_ , ) ((SCREAMING_SNAKE_CASE__) , ) : Optional[Any] = result_with_labels.to_tuple() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , start_positions=a_ , end_positions=a_ ) ((SCREAMING_SNAKE_CASE__) , ) : 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 __lowercase( self : Dict , a_ : int , a_ : Optional[int] , a_ : Tuple , a_ : Dict , a_ : Any , a_ : List[str] , a_ : str , a_ : List[Any] , a_ : int , )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = FlaubertForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : List[str] , a_ : Tuple , a_ : str , a_ : Optional[Any] , a_ : List[Any] , a_ : Tuple , a_ : List[Any] , a_ : List[Any] , a_ : Optional[int] , a_ : List[str] , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.num_labels SCREAMING_SNAKE_CASE__ : Any = FlaubertForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Optional[int] , a_ : Union[str, Any] , a_ : str , a_ : List[str] , a_ : Any , a_ : Any , a_ : Any , a_ : List[Any] , a_ : Optional[Any] , a_ : Any , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.num_choices SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaubertForMultipleChoice(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : int = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Optional[Any] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Optional[int] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Dict = model( a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowercase( self : Optional[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Dict = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[int] = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'lengths': input_lengths, 'attention_mask': input_mask, } return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': FlaubertModel, 'fill-mask': FlaubertWithLMHeadModel, 'question-answering': FlaubertForQuestionAnsweringSimple, 'text-classification': FlaubertForSequenceClassification, 'token-classification': FlaubertForTokenClassification, 'zero-shot': FlaubertForSequenceClassification, } if is_torch_available() else {} ) def __lowercase( self : Union[str, Any] , a_ : str , a_ : List[Any] , a_ : int , a_ : str , a_ : Union[str, Any] )-> 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 __lowercase( self : Optional[Any] , a_ : List[Any] , a_ : int , a_ : List[str]=False )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a_ ) return inputs_dict def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = FlaubertModelTester(self ) SCREAMING_SNAKE_CASE__ : Optional[int] = ConfigTester(self , config_class=a_ , emb_dim=37 ) def __lowercase( self : Dict )-> Any: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*a_ ) def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*a_ ) def __lowercase( self : Union[str, Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*a_ ) def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*a_ ) def __lowercase( self : List[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*a_ ) def __lowercase( self : Dict )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*a_ ) def __lowercase( self : Tuple )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*a_ ) @slow def __lowercase( self : int )-> List[Any]: """simple docstring""" for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Tuple = FlaubertModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) @slow @require_torch_gpu def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return SCREAMING_SNAKE_CASE__ : Tuple = True SCREAMING_SNAKE_CASE__ : Any = model_class(config=a_ ) SCREAMING_SNAKE_CASE__ : int = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = torch.jit.trace( a_ , (inputs_dict['input_ids'].to('cpu' ), inputs_dict['attention_mask'].to('cpu' )) ) with tempfile.TemporaryDirectory() as tmp: torch.jit.save(a_ , os.path.join(a_ , 'traced_model.pt' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.jit.load(os.path.join(a_ , 'traced_model.pt' ) , map_location=a_ ) loaded(inputs_dict['input_ids'].to(a_ ) , inputs_dict['attention_mask'].to(a_ ) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = FlaubertModel.from_pretrained('flaubert/flaubert_base_cased' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : str = torch.tensor( [[[-2.6251, -1.4298, -0.0227], [-2.8510, -1.6387, 0.2258], [-2.8114, -1.1832, -0.3066]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) )
85
import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = StableDiffusionInstructPixaPixPipeline lowercase_ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} lowercase_ = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS lowercase_ = IMAGE_TO_IMAGE_IMAGE_PARAMS def __lowercase( self : str )-> int: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : List[Any] = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=8 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) SCREAMING_SNAKE_CASE__ : List[str] = PNDMScheduler(skip_prk_steps=a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = 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 ) SCREAMING_SNAKE_CASE__ : Optional[int] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) SCREAMING_SNAKE_CASE__ : int = CLIPTextModel(a_ ) SCREAMING_SNAKE_CASE__ : Dict = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) SCREAMING_SNAKE_CASE__ : List[str] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def __lowercase( self : List[Any] , a_ : Tuple , a_ : Optional[Any]=0 )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor((1, 3, 32, 32) , rng=random.Random(a_ ) ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = image.cpu().permute(0 , 2 , 3 , 1 )[0] SCREAMING_SNAKE_CASE__ : List[Any] = Image.fromarray(np.uinta(a_ ) ).convert('RGB' ) if str(a_ ).startswith('mps' ): SCREAMING_SNAKE_CASE__ : str = torch.manual_seed(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Generator(device=a_ ).manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : Dict = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Dict = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'french fries' SCREAMING_SNAKE_CASE__ : Optional[Any] = sd_pipe(**a_ , negative_prompt=a_ ) SCREAMING_SNAKE_CASE__ : Dict = output.images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = [inputs['prompt']] * 2 SCREAMING_SNAKE_CASE__ : List[str] = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 SCREAMING_SNAKE_CASE__ : Tuple = torch.from_numpy(a_ ).unsqueeze(0 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = image / 2 + 0.5 SCREAMING_SNAKE_CASE__ : Tuple = image.permute(0 , 3 , 1 , 2 ) SCREAMING_SNAKE_CASE__ : int = image.repeat(2 , 1 , 1 , 1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) SCREAMING_SNAKE_CASE__ : int = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 'cpu' # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE__ : str = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : Optional[Any] = EulerAncestralDiscreteScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='scaled_linear' ) SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = sd_pipe.to(a_ ) sd_pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_dummy_inputs(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = sd_pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Any = [round(a_ , 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(a_ ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.get_dummy_components() SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline(**a_ ) SCREAMING_SNAKE_CASE__ : int = VaeImageProcessor(do_resize=a_ , do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) SCREAMING_SNAKE_CASE__ : Any = pipe(**self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) )[0] SCREAMING_SNAKE_CASE__ : Optional[int] = components['vae'] SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_dummy_inputs_by_type(a_ , input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae.encode(inputs[image_param] ).latent_dist.mode() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ )[0] SCREAMING_SNAKE_CASE__ : List[Any] = np.abs(out - out_latents_inputs ).max() self.assertLess(a_ , 1e-4 , 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class snake_case ( unittest.TestCase ): def __lowercase( self : Tuple )-> Dict: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase( self : List[Any] , a_ : Dict=0 )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.manual_seed(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) SCREAMING_SNAKE_CASE__ : Tuple = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def __lowercase( self : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Optional[Any] = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : Union[str, Any] = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Dict = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : Optional[int] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[Any] = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ ) SCREAMING_SNAKE_CASE__ : Dict = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : str = self.get_inputs() SCREAMING_SNAKE_CASE__ : Tuple = pipe(**a_ ).images SCREAMING_SNAKE_CASE__ : List[str] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) SCREAMING_SNAKE_CASE__ : List[str] = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = 0 def callback_fn(a_ : int , a_ : int , a_ : torch.FloatTensor ) -> None: SCREAMING_SNAKE_CASE__ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : List[Any] = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Optional[int] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: SCREAMING_SNAKE_CASE__ : Optional[int] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) SCREAMING_SNAKE_CASE__ : Tuple = latents[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__ : Dict = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : List[Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() pipe(**a_ , callback=a_ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def __lowercase( self : int )-> Any: """simple docstring""" torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() SCREAMING_SNAKE_CASE__ : Union[str, Any] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix' , safety_checker=a_ , torch_dtype=torch.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() SCREAMING_SNAKE_CASE__ : Tuple = self.get_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 SCREAMING_SNAKE_CASE__ : Dict = inputs['image'].resize((504, 504) ) SCREAMING_SNAKE_CASE__ : List[Any] = 'timbrooks/instruct-pix2pix' SCREAMING_SNAKE_CASE__ : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( a_ , safety_checker=a_ , ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) pipe.enable_attention_slicing() SCREAMING_SNAKE_CASE__ : Any = pipe(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = output.images[0] SCREAMING_SNAKE_CASE__ : Any = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) SCREAMING_SNAKE_CASE__ : str = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
85
1
from __future__ import annotations from math import pi def _a ( lowercase__ : float , lowercase__ : float , lowercase__ : float ): '''simple docstring''' if (inductance, frequency, reactance).count(0 ) != 1: raise ValueError('One and only one argument must be 0' ) if inductance < 0: raise ValueError('Inductance cannot be negative' ) if frequency < 0: raise ValueError('Frequency cannot be negative' ) if reactance < 0: raise ValueError('Inductive reactance cannot be negative' ) if inductance == 0: return {"inductance": reactance / (2 * pi * frequency)} elif frequency == 0: return {"frequency": reactance / (2 * pi * inductance)} elif reactance == 0: return {"reactance": 2 * pi * frequency * inductance} else: raise ValueError('Exactly one argument must be 0' ) if __name__ == "__main__": import doctest doctest.testmod()
85
import math from collections.abc import Callable def _a ( lowercase__ : Callable[[float], float] , lowercase__ : float , lowercase__ : float ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : float = xa SCREAMING_SNAKE_CASE__ : float = xa while True: if x_n == x_na or function(lowercase__ ) == function(lowercase__ ): raise ZeroDivisionError('float division by zero, could not find root' ) SCREAMING_SNAKE_CASE__ : float = x_na - ( function(lowercase__ ) / ((function(lowercase__ ) - function(lowercase__ )) / (x_na - x_n)) ) if abs(x_na - x_na ) < 10**-5: return x_na SCREAMING_SNAKE_CASE__ : Dict = x_na SCREAMING_SNAKE_CASE__ : List[str] = x_na def _a ( lowercase__ : float ): '''simple docstring''' return math.pow(lowercase__ , 3 ) - (2 * x) - 5 if __name__ == "__main__": print(intersection(f, 3, 3.5))
85
1