code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available a_ = { 'configuration_groupvit': [ 'GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GroupViTConfig', 'GroupViTOnnxConfig', 'GroupViTTextConfig', 'GroupViTVisionConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'GroupViTModel', 'GroupViTPreTrainedModel', 'GroupViTTextModel', 'GroupViTVisionModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFGroupViTModel', 'TFGroupViTPreTrainedModel', 'TFGroupViTTextModel', 'TFGroupViTVisionModel', ] if TYPE_CHECKING: from .configuration_groupvit import ( GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GroupViTConfig, GroupViTOnnxConfig, GroupViTTextConfig, GroupViTVisionConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_groupvit import ( GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, GroupViTModel, GroupViTPreTrainedModel, GroupViTTextModel, GroupViTVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_groupvit import ( TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST, TFGroupViTModel, TFGroupViTPreTrainedModel, TFGroupViTTextModel, TFGroupViTVisionModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
from datetime import datetime as dt import os from github import Github a_ = [ 'good first issue', 'good second issue', 'good difficult issue', 'feature request', 'new model', 'wip', ] def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : int = Github(os.environ["GITHUB_TOKEN"]) SCREAMING_SNAKE_CASE : List[str] = g.get_repo("huggingface/transformers") SCREAMING_SNAKE_CASE : Optional[int] = repo.get_issues(state="open") for issue in open_issues: SCREAMING_SNAKE_CASE : List[Any] = sorted([comment for comment in issue.get_comments()] , key=lambda _a: i.created_at , reverse=_a) SCREAMING_SNAKE_CASE : str = comments[0] if len(_a) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state="closed") elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( "This issue has been automatically marked as stale because it has not had " "recent activity. If you think this still needs to be addressed " "please comment on this thread.\n\nPlease note that issues that do not follow the " "[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) " "are likely to be ignored.") if __name__ == "__main__": main()
76
1
from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Union[str, Any] = 9, 14 # noqa: F841 SCREAMING_SNAKE_CASE : List[str] = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] SCREAMING_SNAKE_CASE : Any = defaultdict(_a) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost]) adjancency[nodea].append([nodea, cost]) SCREAMING_SNAKE_CASE : List[Any] = mst(_a) SCREAMING_SNAKE_CASE : List[str] = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: SCREAMING_SNAKE_CASE : Any = tuple(answer[:2]) SCREAMING_SNAKE_CASE : Optional[int] = tuple(edge[::-1]) assert edge in result or reverse in result
76
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): if isinstance(_a , (list, tuple)) and isinstance(videos[0] , (list, tuple)) and is_valid_image(videos[0][0]): return videos elif isinstance(_a , (list, tuple)) and is_valid_image(videos[0]): return [videos] elif is_valid_image(_a): return [[videos]] raise ValueError(f"Could not make batched video from {videos}") class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =['pixel_values'] def __init__( self : Optional[Any] , a : bool = True , a : Dict[str, int] = None , a : PILImageResampling = PILImageResampling.BILINEAR , a : bool = True , a : Dict[str, int] = None , a : bool = True , a : Union[int, float] = 1 / 255 , a : bool = True , a : bool = True , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , **a : Tuple , ) -> None: """simple docstring""" super().__init__(**a ) SCREAMING_SNAKE_CASE : Tuple = size if size is not None else {"shortest_edge": 256} SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE : str = get_size_dict(a , param_name="crop_size" ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : Optional[int] = do_center_crop SCREAMING_SNAKE_CASE : int = crop_size SCREAMING_SNAKE_CASE : int = resample SCREAMING_SNAKE_CASE : Any = do_rescale SCREAMING_SNAKE_CASE : int = rescale_factor SCREAMING_SNAKE_CASE : Tuple = offset SCREAMING_SNAKE_CASE : str = do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def __UpperCamelCase ( self : Optional[Any] , a : np.ndarray , a : Dict[str, int] , a : PILImageResampling = PILImageResampling.BILINEAR , a : Optional[Union[str, ChannelDimension]] = None , **a : Union[str, Any] , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) if "shortest_edge" in size: SCREAMING_SNAKE_CASE : str = get_resize_output_image_size(a , size["shortest_edge"] , default_to_square=a ) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE : Dict = (size["height"], size["width"]) else: raise ValueError(F"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a , size=a , resample=a , data_format=a , **a ) def __UpperCamelCase ( self : List[str] , a : np.ndarray , a : Dict[str, int] , a : Optional[Union[str, ChannelDimension]] = None , **a : str , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : str = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(F"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __UpperCamelCase ( self : List[Any] , a : np.ndarray , a : Union[int, float] , a : bool = True , a : Optional[Union[str, ChannelDimension]] = None , **a : Tuple , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = image.astype(np.floataa ) if offset: SCREAMING_SNAKE_CASE : Union[str, Any] = image - (scale / 2) return rescale(a , scale=a , data_format=a , **a ) def __UpperCamelCase ( self : int , a : np.ndarray , a : Union[float, List[float]] , a : Union[float, List[float]] , a : Optional[Union[str, ChannelDimension]] = None , **a : List[str] , ) -> np.ndarray: """simple docstring""" return normalize(a , mean=a , std=a , data_format=a , **a ) def __UpperCamelCase ( self : Tuple , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray: """simple docstring""" if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) if offset and not do_rescale: raise ValueError("For offset, do_rescale must also be set to True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : List[str] = to_numpy_array(a ) if do_resize: SCREAMING_SNAKE_CASE : Optional[Any] = self.resize(image=a , size=a , resample=a ) if do_center_crop: SCREAMING_SNAKE_CASE : Union[str, Any] = self.center_crop(a , size=a ) if do_rescale: SCREAMING_SNAKE_CASE : Any = self.rescale(image=a , scale=a , offset=a ) if do_normalize: SCREAMING_SNAKE_CASE : Tuple = self.normalize(image=a , mean=a , std=a ) SCREAMING_SNAKE_CASE : Optional[int] = to_channel_dimension_format(a , a ) return image def __UpperCamelCase ( self : Dict , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[str, TensorType]] = None , a : ChannelDimension = ChannelDimension.FIRST , **a : Tuple , ) -> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE : str = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Union[str, Any] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : int = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE : str = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[Any] = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Optional[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : int = size if size is not None else self.size SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : Tuple = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(a , param_name="crop_size" ) 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." ) SCREAMING_SNAKE_CASE : Optional[int] = make_batched(a ) SCREAMING_SNAKE_CASE : List[Any] = [ [ self._preprocess_image( image=a , do_resize=a , size=a , resample=a , do_center_crop=a , crop_size=a , do_rescale=a , rescale_factor=a , offset=a , do_normalize=a , image_mean=a , image_std=a , data_format=a , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE : Optional[int] = {"pixel_values": videos} return BatchFeature(data=a , tensor_type=a )
76
1
import re import tempfile from pathlib import Path import pytest import yaml from datasets.utils.readme import ReadMe # @pytest.fixture # def example_yaml_structure(): a_ = yaml.safe_load( '\\nname: ""\nallow_empty: false\nallow_empty_text: true\nsubsections:\n - name: "Dataset Card for X" # First-level markdown heading\n allow_empty: false\n allow_empty_text: true\n subsections:\n - name: "Table of Contents"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Dataset Description"\n allow_empty: false\n allow_empty_text: false\n subsections:\n - name: "Dataset Summary"\n allow_empty: false\n allow_empty_text: false\n subsections: null\n - name: "Supported Tasks and Leaderboards"\n allow_empty: true\n allow_empty_text: true\n subsections: null\n - name: Languages\n allow_empty: false\n allow_empty_text: true\n subsections: null\n' ) a_ = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n#### Extra Ignored Subsection\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = { 'name': 'root', 'text': '', 'is_empty_text': True, 'subsections': [ { 'name': 'Dataset Card for My Dataset', 'text': '', 'is_empty_text': True, 'subsections': [ {'name': 'Table of Contents', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': []}, { 'name': 'Dataset Description', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Dataset Summary', 'text': 'Some text here.', 'is_empty_text': False, 'subsections': [ { 'name': 'Extra Ignored Subsection', 'text': '', 'is_empty_text': True, 'subsections': [], } ], }, { 'name': 'Supported Tasks and Leaderboards', 'text': '', 'is_empty_text': True, 'subsections': [], }, {'name': 'Languages', 'text': 'Language Text', 'is_empty_text': False, 'subsections': []}, ], }, ], } ], } a_ = '\\n---\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = ( 'The following issues were found for the README at `{path}`:\n-\tEmpty YAML markers are present in the README.' ) a_ = '\\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = ( 'The following issues were found for the README at `{path}`:\n-\tNo YAML markers are present in the README.' ) a_ = '\\n---\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tOnly the start of YAML tags present in the README.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Summary` but it is empty.\n-\tExpected some text in section `Dataset Summary` but it is empty (text in subsections are ignored).' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Dataset Card for My Dataset` but it is empty.\n-\tSection `Dataset Card for My Dataset` expected the following subsections: `Table of Contents`, `Dataset Description`. Found \'None\'.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Languages\nLanguage Text\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tSection `Dataset Description` is missing subsection: `Supported Tasks and Leaderboards`.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tExpected some content in section `Languages` but it is empty.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n# Dataset Card My Dataset\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tThe README has several first-level headings: `Dataset Card for My Dataset`, `Dataset Card My Dataset`. Only one heading is expected. Skipping further validation for this README.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = 'The following issues were found for the README at `{path}`:\n-\tNo first-level heading starting with `Dataset Card for` found in README. Skipping further validation for this README.' a_ = '' a_ = 'The following issues were found for the README at `{path}`:\n-\tThe README has no first-level headings. One heading is expected. Skipping further validation for this README.\n-\tNo YAML markers are present in the README.' a_ = '\\n---\nlanguage:\n- zh\n- en\n---\n\n# Dataset Card for My Dataset\n# Dataset Card for My Dataset\n## Table of Contents\nSome text here.\n## Dataset Description\nSome text here.\n### Dataset Summary\nSome text here.\n### Supported Tasks and Leaderboards\n### Languages\nLanguage Text\n' a_ = 'The following issues were found while parsing the README at `{path}`:\n-\tMultiple sections with the same heading `Dataset Card for My Dataset` have been found. Please keep only one of these sections.' @pytest.mark.parametrize( "readme_md, expected_dict" , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def lowerCamelCase__ ( _a , _a): assert ReadMe.from_string(_a , _a).to_dict() == expected_dict @pytest.mark.parametrize( "readme_md, expected_error" , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def lowerCamelCase__ ( _a , _a): with pytest.raises(_a , match=re.escape(expected_error.format(path="root"))): SCREAMING_SNAKE_CASE : str = ReadMe.from_string(_a , _a) readme.validate() @pytest.mark.parametrize( "readme_md, expected_error" , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase__ ( _a , _a): with pytest.raises(_a , match=re.escape(expected_error.format(path="root"))): ReadMe.from_string(_a , _a) @pytest.mark.parametrize( "readme_md," , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase__ ( _a): ReadMe.from_string(_a , _a , suppress_parsing_errors=_a) @pytest.mark.parametrize( "readme_md, expected_dict" , [ (README_CORRECT, CORRECT_DICT), (README_CORRECT_FOUR_LEVEL, CORRECT_DICT_FOUR_LEVEL), ] , ) def lowerCamelCase__ ( _a , _a): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : Optional[int] = Path(_a) / "README.md" with open(_a , "w+") as readme_file: readme_file.write(_a) SCREAMING_SNAKE_CASE : Optional[Any] = ReadMe.from_readme(_a , _a).to_dict() assert out["name"] == path assert out["text"] == "" assert out["is_empty_text"] assert out["subsections"] == expected_dict["subsections"] @pytest.mark.parametrize( "readme_md, expected_error" , [ (README_NO_YAML, EXPECTED_ERROR_README_NO_YAML), (README_EMPTY_YAML, EXPECTED_ERROR_README_EMPTY_YAML), (README_INCORRECT_YAML, EXPECTED_ERROR_README_INCORRECT_YAML), (README_EMPTY, EXPECTED_ERROR_README_EMPTY), (README_NONE_SUBSECTION, EXPECTED_ERROR_README_NONE_SUBSECTION), (README_MISSING_FIRST_LEVEL, EXPECTED_ERROR_README_MISSING_FIRST_LEVEL), (README_MISSING_SUBSECTION, EXPECTED_ERROR_README_MISSING_SUBSECTION), (README_MISSING_TEXT, EXPECTED_ERROR_README_MISSING_TEXT), (README_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_WRONG_FIRST_LEVEL), (README_MULTIPLE_WRONG_FIRST_LEVEL, EXPECTED_ERROR_README_MULTIPLE_WRONG_FIRST_LEVEL), (README_MISSING_CONTENT, EXPECTED_ERROR_README_MISSING_CONTENT), ] , ) def lowerCamelCase__ ( _a , _a): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : List[str] = Path(_a) / "README.md" with open(_a , "w+") as readme_file: readme_file.write(_a) SCREAMING_SNAKE_CASE : Optional[Any] = expected_error.format(path=_a) with pytest.raises(_a , match=re.escape(_a)): SCREAMING_SNAKE_CASE : Optional[int] = ReadMe.from_readme(_a , _a) readme.validate() @pytest.mark.parametrize( "readme_md, expected_error" , [ (README_MULTIPLE_SAME_HEADING_1, EXPECTED_ERROR_README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase__ ( _a , _a): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : Any = Path(_a) / "README.md" with open(_a , "w+") as readme_file: readme_file.write(_a) SCREAMING_SNAKE_CASE : Dict = expected_error.format(path=_a) with pytest.raises(_a , match=re.escape(_a)): ReadMe.from_readme(_a , _a) @pytest.mark.parametrize( "readme_md," , [ (README_MULTIPLE_SAME_HEADING_1), ] , ) def lowerCamelCase__ ( _a): with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE : int = Path(_a) / "README.md" with open(_a , "w+") as readme_file: readme_file.write(_a) ReadMe.from_readme(_a , _a , suppress_parsing_errors=_a)
76
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt'} a_ = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } a_ = { 'YituTech/conv-bert-base': 512, 'YituTech/conv-bert-medium-small': 512, 'YituTech/conv-bert-small': 512, } a_ = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =VOCAB_FILES_NAMES lowerCamelCase__ =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ =PRETRAINED_INIT_CONFIGURATION lowerCamelCase__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ =ConvBertTokenizer def __init__( self : List[str] , a : Union[str, Any]=None , a : Optional[int]=None , a : int=True , a : Tuple="[UNK]" , a : Dict="[SEP]" , a : Dict="[PAD]" , a : List[Any]="[CLS]" , a : Tuple="[MASK]" , a : Dict=True , a : Optional[Any]=None , **a : str , ) -> Dict: """simple docstring""" super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) SCREAMING_SNAKE_CASE : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , a ) != do_lower_case or normalizer_state.get("strip_accents" , a ) != strip_accents or normalizer_state.get("handle_chinese_chars" , a ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : List[str] = getattr(a , normalizer_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE : Any = strip_accents SCREAMING_SNAKE_CASE : Optional[int] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : List[str] = normalizer_class(**a ) SCREAMING_SNAKE_CASE : str = do_lower_case def __UpperCamelCase ( self : Union[str, Any] , a : List[Any] , a : int=None ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __UpperCamelCase ( self : Dict , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCamelCase ( self : Tuple , a : str , a : Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self._tokenizer.model.save(a , name=a ) return tuple(a )
76
1
from typing import List from .keymap import KEYMAP, get_character def lowerCamelCase__ ( _a): def decorator(_a): SCREAMING_SNAKE_CASE : Dict = getattr(_a , "handle_key" , []) handle += [key] setattr(_a , "handle_key" , _a) return func return decorator def lowerCamelCase__ ( *_a): def decorator(_a): SCREAMING_SNAKE_CASE : Dict = getattr(_a , "handle_key" , []) handle += keys setattr(_a , "handle_key" , _a) return func return decorator class _UpperCamelCase ( __A ): '''simple docstring''' def __new__( cls : Tuple , a : Tuple , a : Dict , a : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = super().__new__(cls , a , a , a ) if not hasattr(a , "key_handler" ): setattr(a , "key_handler" , {} ) setattr(a , "handle_input" , KeyHandler.handle_input ) for value in attrs.values(): SCREAMING_SNAKE_CASE : List[Any] = getattr(a , "handle_key" , [] ) for key in handled_keys: SCREAMING_SNAKE_CASE : List[str] = value return new_cls @staticmethod def __UpperCamelCase ( cls : Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = get_character() if char != KEYMAP["undefined"]: SCREAMING_SNAKE_CASE : int = ord(a ) SCREAMING_SNAKE_CASE : str = cls.key_handler.get(a ) if handler: SCREAMING_SNAKE_CASE : Dict = char return handler(cls ) else: return None def lowerCamelCase__ ( cls): return KeyHandler(cls.__name__ , cls.__bases__ , cls.__dict__.copy())
76
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. a_ = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(_a) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE : Union[str, Any] = terminalreporter.config.getoption("--make-reports") if make_reports: pytest_terminal_summary_main(_a , id=_a)
76
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { 'configuration_longformer': [ 'LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'LongformerConfig', 'LongformerOnnxConfig', ], 'tokenization_longformer': ['LongformerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['LongformerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'LongformerForMaskedLM', 'LongformerForMultipleChoice', 'LongformerForQuestionAnswering', 'LongformerForSequenceClassification', 'LongformerForTokenClassification', 'LongformerModel', 'LongformerPreTrainedModel', 'LongformerSelfAttention', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFLongformerForMaskedLM', 'TFLongformerForMultipleChoice', 'TFLongformerForQuestionAnswering', 'TFLongformerForSequenceClassification', 'TFLongformerForTokenClassification', 'TFLongformerModel', 'TFLongformerPreTrainedModel', 'TFLongformerSelfAttention', ] if TYPE_CHECKING: from .configuration_longformer import ( LONGFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, LongformerConfig, LongformerOnnxConfig, ) from .tokenization_longformer import LongformerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_longformer_fast import LongformerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_longformer import ( LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, LongformerForMaskedLM, LongformerForMultipleChoice, LongformerForQuestionAnswering, LongformerForSequenceClassification, LongformerForTokenClassification, LongformerModel, LongformerPreTrainedModel, LongformerSelfAttention, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_longformer import ( TF_LONGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFLongformerForMaskedLM, TFLongformerForMultipleChoice, TFLongformerForQuestionAnswering, TFLongformerForSequenceClassification, TFLongformerForTokenClassification, TFLongformerModel, TFLongformerPreTrainedModel, TFLongformerSelfAttention, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , a : int , a : Optional[int]=13 , a : Optional[int]=3 , a : int=224 , a : Optional[int]=30 , a : int=400 , a : Union[str, Any]=True , a : int=None , a : Tuple=True , a : Tuple=[0.5, 0.5, 0.5] , a : Optional[int]=[0.5, 0.5, 0.5] , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = size if size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : int = num_channels SCREAMING_SNAKE_CASE : Any = image_size SCREAMING_SNAKE_CASE : Tuple = min_resolution SCREAMING_SNAKE_CASE : str = max_resolution SCREAMING_SNAKE_CASE : int = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : int = do_normalize SCREAMING_SNAKE_CASE : Tuple = image_mean SCREAMING_SNAKE_CASE : Tuple = image_std def __UpperCamelCase ( self : Any ) -> Optional[int]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =ViTImageProcessor if is_vision_available() else None def __UpperCamelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = EfficientFormerImageProcessorTester(self ) @property def __UpperCamelCase ( self : Any ) -> List[str]: """simple docstring""" return self.image_proc_tester.prepare_image_processor_dict() def __UpperCamelCase ( self : List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , "image_mean" ) ) self.assertTrue(hasattr(a , "image_std" ) ) self.assertTrue(hasattr(a , "do_normalize" ) ) self.assertTrue(hasattr(a , "do_resize" ) ) self.assertTrue(hasattr(a , "size" ) ) def __UpperCamelCase ( self : int ) -> str: """simple docstring""" pass def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : List[str] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : str = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , numpify=a ) for image in image_inputs: self.assertIsInstance(a , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Any = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , torchify=a ) for image in image_inputs: self.assertIsInstance(a , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , )
76
1
import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : List[Any] = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" SCREAMING_SNAKE_CASE : Optional[Any] = Image.open(requests.get(_a , stream=_a).raw).convert("RGB") SCREAMING_SNAKE_CASE : List[str] = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711)), ]) SCREAMING_SNAKE_CASE : Optional[int] = transform(_a).unsqueeze(0).to(_a) return image def lowerCamelCase__ ( _a): if "visual_encoder" in key: SCREAMING_SNAKE_CASE : Optional[Any] = re.sub("visual_encoder*" , "vision_model.encoder" , _a) if "blocks" in key: SCREAMING_SNAKE_CASE : Union[str, Any] = re.sub(r"blocks" , "layers" , _a) if "attn" in key: SCREAMING_SNAKE_CASE : Optional[int] = re.sub(r"attn" , "self_attn" , _a) if "norm1" in key: SCREAMING_SNAKE_CASE : Union[str, Any] = re.sub(r"norm1" , "layer_norm1" , _a) if "norm2" in key: SCREAMING_SNAKE_CASE : int = re.sub(r"norm2" , "layer_norm2" , _a) if "encoder.norm" in key: SCREAMING_SNAKE_CASE : Tuple = re.sub(r"encoder.norm" , "post_layernorm" , _a) if "encoder.patch_embed.proj" in key: SCREAMING_SNAKE_CASE : Dict = re.sub(r"encoder.patch_embed.proj" , "embeddings.patch_embedding" , _a) if "encoder.pos_embed" in key: SCREAMING_SNAKE_CASE : int = re.sub(r"encoder.pos_embed" , "embeddings.position_embedding" , _a) if "encoder.cls_token" in key: SCREAMING_SNAKE_CASE : Any = re.sub(r"encoder.cls_token" , "embeddings.class_embedding" , _a) if "self_attn" in key: SCREAMING_SNAKE_CASE : Union[str, Any] = re.sub(r"self_attn.proj" , "self_attn.projection" , _a) return key @torch.no_grad() def lowerCamelCase__ ( _a , _a=None): if config_path is not None: SCREAMING_SNAKE_CASE : Any = BlipConfig.from_pretrained(_a) else: SCREAMING_SNAKE_CASE : int = BlipConfig(projection_dim=512 , text_config={} , vision_config={}) SCREAMING_SNAKE_CASE : str = BlipForConditionalGeneration(_a).eval() SCREAMING_SNAKE_CASE : str = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" SCREAMING_SNAKE_CASE : List[Any] = blip_decoder(pretrained=_a , image_size=384 , vit="base") SCREAMING_SNAKE_CASE : Optional[Any] = pt_model.eval() SCREAMING_SNAKE_CASE : List[str] = pt_model.state_dict() for key in modified_state_dict.copy(): SCREAMING_SNAKE_CASE : Optional[int] = modified_state_dict.pop(_a) SCREAMING_SNAKE_CASE : int = rename_key(_a) SCREAMING_SNAKE_CASE : Dict = value hf_model.load_state_dict(_a) SCREAMING_SNAKE_CASE : Any = 384 SCREAMING_SNAKE_CASE : Dict = load_demo_image(image_size=_a , device="cpu") SCREAMING_SNAKE_CASE : List[str] = BertTokenizer.from_pretrained("bert-base-uncased") SCREAMING_SNAKE_CASE : Optional[int] = tokenizer(["a picture of"]).input_ids SCREAMING_SNAKE_CASE : Union[str, Any] = hf_model.generate(_a , _a) assert out[0].tolist() == [30522, 1037, 3861, 1997, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] SCREAMING_SNAKE_CASE : Tuple = hf_model.generate(_a) assert out[0].tolist() == [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(_a) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' SCREAMING_SNAKE_CASE : Dict = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) SCREAMING_SNAKE_CASE : Optional[Any] = blip_vqa(pretrained=_a , image_size=_a , vit="base") vqa_model.eval() SCREAMING_SNAKE_CASE : Optional[Any] = vqa_model.state_dict() for key in modified_state_dict.copy(): SCREAMING_SNAKE_CASE : Optional[Any] = modified_state_dict.pop(_a) SCREAMING_SNAKE_CASE : Optional[int] = rename_key(_a) SCREAMING_SNAKE_CASE : List[str] = value SCREAMING_SNAKE_CASE : Optional[int] = BlipForQuestionAnswering(_a) hf_vqa_model.load_state_dict(_a) SCREAMING_SNAKE_CASE : Union[str, Any] = ["How many dogs are in this image?"] SCREAMING_SNAKE_CASE : Any = tokenizer(_a , return_tensors="pt").input_ids SCREAMING_SNAKE_CASE : Union[str, Any] = hf_vqa_model.generate(_a , _a) print(tokenizer.decode(answer[0])) assert tokenizer.decode(answer[0]) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa") SCREAMING_SNAKE_CASE : Optional[Any] = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" SCREAMING_SNAKE_CASE : int = blip_itm(pretrained=_a , image_size=_a , vit="base") itm_model.eval() SCREAMING_SNAKE_CASE : Dict = itm_model.state_dict() for key in modified_state_dict.copy(): SCREAMING_SNAKE_CASE : Optional[int] = modified_state_dict.pop(_a) SCREAMING_SNAKE_CASE : Any = rename_key(_a) SCREAMING_SNAKE_CASE : List[Any] = value SCREAMING_SNAKE_CASE : str = BlipForImageTextRetrieval(_a) SCREAMING_SNAKE_CASE : Optional[Any] = ["A picture of a woman with a dog sitting in a beach"] SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer( _a , return_tensors="pt" , padding="max_length" , truncation=_a , max_length=35 , ).input_ids hf_itm_model.load_state_dict(_a) hf_itm_model.eval() SCREAMING_SNAKE_CASE : List[str] = hf_itm_model(_a , _a , use_itm_head=_a) SCREAMING_SNAKE_CASE : Dict = hf_itm_model(_a , _a , use_itm_head=_a) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1)[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm") if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') a_ = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
76
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = tokenizer(example["content"] , truncation=_a)["input_ids"] SCREAMING_SNAKE_CASE : Dict = len(example["content"]) / len(output["input_ids"]) return output a_ = HfArgumentParser(PretokenizationArguments) a_ = parser.parse_args() if args.num_workers is None: a_ = multiprocessing.cpu_count() a_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) a_ = time.time() a_ = load_dataset(args.dataset_name, split='train') print(F'''Dataset loaded in {time.time()-t_start:.2f}s''') a_ = time.time() a_ = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ 'repo_name', 'path', 'copies', 'size', 'content', 'license', 'hash', 'line_mean', 'line_max', 'alpha_frac', 'autogenerated', ], ) print(F'''Dataset tokenized in {time.time()-t_start:.2f}s''') a_ = time.time() ds.push_to_hub(args.tokenized_data_repo) print(F'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
76
1
import os import tempfile import unittest from transformers import NezhaConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, NezhaModel, ) from transformers.models.nezha.modeling_nezha import NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST class _UpperCamelCase : '''simple docstring''' def __init__( self : Dict , a : Union[str, Any] , a : List[str]=13 , a : Optional[Any]=7 , a : Tuple=True , a : Dict=True , a : List[Any]=True , a : Union[str, Any]=True , a : List[str]=99 , a : Any=32 , a : List[str]=5 , a : List[Any]=4 , a : Dict=37 , a : List[str]="gelu" , a : List[str]=0.1 , a : Dict=0.1 , a : Optional[int]=128 , a : Dict=32 , a : Any=16 , a : Optional[Any]=2 , a : Dict=0.02 , a : str=3 , a : Union[str, Any]=4 , a : str=None , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = parent SCREAMING_SNAKE_CASE : List[str] = batch_size SCREAMING_SNAKE_CASE : Any = seq_length SCREAMING_SNAKE_CASE : Tuple = is_training SCREAMING_SNAKE_CASE : Optional[int] = use_input_mask SCREAMING_SNAKE_CASE : List[Any] = use_token_type_ids SCREAMING_SNAKE_CASE : Any = use_labels SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : Tuple = hidden_size SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE : Any = intermediate_size SCREAMING_SNAKE_CASE : str = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[Any] = max_position_embeddings SCREAMING_SNAKE_CASE : Optional[int] = type_vocab_size SCREAMING_SNAKE_CASE : Union[str, Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : Dict = initializer_range SCREAMING_SNAKE_CASE : List[str] = num_labels SCREAMING_SNAKE_CASE : Union[str, Any] = num_choices SCREAMING_SNAKE_CASE : Optional[int] = scope def __UpperCamelCase ( self : Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : str = None if self.use_input_mask: SCREAMING_SNAKE_CASE : Dict = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Tuple = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase ( self : List[Any] ) -> str: """simple docstring""" return NezhaConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , ) def __UpperCamelCase ( self : str ) -> List[str]: """simple docstring""" ( ( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) , ) : List[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : Tuple = True SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def __UpperCamelCase ( self : Union[str, Any] , a : str , a : int , a : List[Any] , a : Tuple , a : Optional[Any] , a : Optional[int] , a : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : str = NezhaModel(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Any = model(a , attention_mask=a , token_type_ids=a ) SCREAMING_SNAKE_CASE : List[Any] = model(a , token_type_ids=a ) SCREAMING_SNAKE_CASE : Optional[int] = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCamelCase ( self : Dict , a : Any , a : Tuple , a : Dict , a : str , a : List[str] , a : Optional[Any] , a : List[str] , a : Tuple , a : str , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = True SCREAMING_SNAKE_CASE : Optional[int] = NezhaModel(a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : int = model( a , attention_mask=a , token_type_ids=a , encoder_hidden_states=a , encoder_attention_mask=a , ) SCREAMING_SNAKE_CASE : List[Any] = model( a , attention_mask=a , token_type_ids=a , encoder_hidden_states=a , ) SCREAMING_SNAKE_CASE : Optional[int] = model(a , attention_mask=a , token_type_ids=a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def __UpperCamelCase ( self : Any , a : Any , a : str , a : str , a : Union[str, Any] , a : Union[str, Any] , a : str , a : Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = NezhaForMaskedLM(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : List[Any] = model(a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase ( self : Dict , a : List[str] , a : Dict , a : Dict , a : Any , a : str , a : Optional[int] , a : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = NezhaForNextSentencePrediction(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model( a , attention_mask=a , token_type_ids=a , labels=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def __UpperCamelCase ( self : Tuple , a : Tuple , a : List[Any] , a : Tuple , a : Any , a : int , a : int , a : int ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = NezhaForPreTraining(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model( a , attention_mask=a , token_type_ids=a , labels=a , next_sentence_label=a , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def __UpperCamelCase ( self : str , a : List[Any] , a : Tuple , a : Union[str, Any] , a : Any , a : Optional[int] , a : List[Any] , a : Union[str, Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : str = NezhaForQuestionAnswering(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : List[str] = model( a , attention_mask=a , token_type_ids=a , start_positions=a , end_positions=a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase ( self : Optional[int] , a : int , a : str , a : Any , a : Union[str, Any] , a : str , a : Union[str, Any] , a : Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_labels SCREAMING_SNAKE_CASE : Any = NezhaForSequenceClassification(a ) model.to(a ) model.eval() 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_labels) ) def __UpperCamelCase ( self : Optional[Any] , a : Any , a : Tuple , a : List[Any] , a : Any , a : Dict , a : Union[str, Any] , a : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = self.num_labels SCREAMING_SNAKE_CASE : Dict = NezhaForTokenClassification(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Optional[Any] = model(a , attention_mask=a , token_type_ids=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase ( self : str , a : List[str] , a : Tuple , a : Optional[int] , a : Union[str, Any] , a : str , a : Tuple , a : Union[str, Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.num_choices SCREAMING_SNAKE_CASE : str = NezhaForMultipleChoice(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 : Any = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : Dict = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : Optional[Any] = model( a , attention_mask=a , token_type_ids=a , labels=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = 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 ) , ) : Dict = config_and_inputs SCREAMING_SNAKE_CASE : Dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _UpperCamelCase ( __A , __A , __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =( ( NezhaModel, NezhaForMaskedLM, NezhaForMultipleChoice, NezhaForNextSentencePrediction, NezhaForPreTraining, NezhaForQuestionAnswering, NezhaForSequenceClassification, NezhaForTokenClassification, ) if is_torch_available() else () ) lowerCamelCase__ =( { 'feature-extraction': NezhaModel, 'fill-mask': NezhaForMaskedLM, 'question-answering': NezhaForQuestionAnswering, 'text-classification': NezhaForSequenceClassification, 'token-classification': NezhaForTokenClassification, 'zero-shot': NezhaForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase__ =True def __UpperCamelCase ( self : Optional[int] , a : Any , a : Optional[int] , a : str=False ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = super()._prepare_for_class(a , a , return_labels=a ) if return_labels: if model_class in get_values(a ): SCREAMING_SNAKE_CASE : Any = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , 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 __UpperCamelCase ( self : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Any = NezhaModelTester(self ) SCREAMING_SNAKE_CASE : List[Any] = ConfigTester(self , config_class=a , hidden_size=37 ) def __UpperCamelCase ( self : Union[str, Any] ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def __UpperCamelCase ( self : List[str] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def __UpperCamelCase ( self : Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*a ) def __UpperCamelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" ( ( 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 = self.model_tester.prepare_config_and_inputs_for_decoder() SCREAMING_SNAKE_CASE : Union[str, Any] = None self.model_tester.create_and_check_model_as_decoder( a , a , a , a , a , a , a , a , a , ) def __UpperCamelCase ( self : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a ) def __UpperCamelCase ( self : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*a ) def __UpperCamelCase ( self : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_next_sequence_prediction(*a ) def __UpperCamelCase ( self : Dict ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*a ) def __UpperCamelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a ) def __UpperCamelCase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a ) def __UpperCamelCase ( self : Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a ) @slow def __UpperCamelCase ( self : Union[str, Any] ) -> Any: """simple docstring""" for model_name in NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Optional[Any] = NezhaModel.from_pretrained(a ) self.assertIsNotNone(a ) @slow @require_torch_gpu def __UpperCamelCase ( self : Any ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: # NezhaForMultipleChoice behaves incorrectly in JIT environments. if model_class == NezhaForMultipleChoice: return SCREAMING_SNAKE_CASE : List[Any] = True SCREAMING_SNAKE_CASE : int = model_class(config=a ) SCREAMING_SNAKE_CASE : Union[str, Any] = self._prepare_for_class(a , a ) SCREAMING_SNAKE_CASE : List[Any] = 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 , "bert.pt" ) ) SCREAMING_SNAKE_CASE : Tuple = torch.jit.load(os.path.join(a , "bert.pt" ) , map_location=a ) loaded(inputs_dict["input_ids"].to(a ) , inputs_dict["attention_mask"].to(a ) ) @require_torch class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : Dict ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = NezhaModel.from_pretrained("sijunhe/nezha-cn-base" ) SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[0, 1, 1, 1, 1, 1]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Any = model(a , attention_mask=a )[0] SCREAMING_SNAKE_CASE : str = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , a ) SCREAMING_SNAKE_CASE : Dict = torch.tensor([[[0.0685, 0.2441, 0.1102], [0.0600, 0.1906, 0.1349], [0.0221, 0.0819, 0.0586]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a , atol=1e-4 ) ) @slow def __UpperCamelCase ( self : List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = NezhaForMaskedLM.from_pretrained("sijunhe/nezha-cn-base" ) SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE : Any = torch.tensor([[1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(a , attention_mask=a )[0] SCREAMING_SNAKE_CASE : Optional[Any] = torch.Size((1, 6, 2_1128) ) self.assertEqual(output.shape , a ) SCREAMING_SNAKE_CASE : str = torch.tensor( [[-2.7939, -1.7902, -2.2189], [-2.8585, -1.8908, -2.3723], [-2.6499, -1.7750, -2.2558]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a , atol=1e-4 ) )
76
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): # initialize config if "resnet-50" in model_name: SCREAMING_SNAKE_CASE : int = ResNetConfig.from_pretrained("microsoft/resnet-50") elif "resnet-101" in model_name: SCREAMING_SNAKE_CASE : int = ResNetConfig.from_pretrained("microsoft/resnet-101") else: raise ValueError("Model name should include either resnet50 or resnet101") SCREAMING_SNAKE_CASE : str = DetrConfig(use_timm_backbone=_a , backbone_config=_a) # set label attributes SCREAMING_SNAKE_CASE : List[str] = "panoptic" in model_name if is_panoptic: SCREAMING_SNAKE_CASE : Union[str, Any] = 250 else: SCREAMING_SNAKE_CASE : Union[str, Any] = 91 SCREAMING_SNAKE_CASE : str = "huggingface/label-files" SCREAMING_SNAKE_CASE : Union[str, Any] = "coco-detection-id2label.json" SCREAMING_SNAKE_CASE : Optional[Any] = json.load(open(hf_hub_download(_a , _a , repo_type="dataset") , "r")) SCREAMING_SNAKE_CASE : int = {int(_a): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : List[Any] = idalabel SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in idalabel.items()} return config, is_panoptic def lowerCamelCase__ ( _a): # here we list all keys to be renamed (original name on the left, our name on the right) SCREAMING_SNAKE_CASE : Union[str, Any] = [] # stem # fmt: off rename_keys.append(("backbone.0.body.conv1.weight", "backbone.conv_encoder.model.embedder.embedder.convolution.weight")) rename_keys.append(("backbone.0.body.bn1.weight", "backbone.conv_encoder.model.embedder.embedder.normalization.weight")) rename_keys.append(("backbone.0.body.bn1.bias", "backbone.conv_encoder.model.embedder.embedder.normalization.bias")) rename_keys.append(("backbone.0.body.bn1.running_mean", "backbone.conv_encoder.model.embedder.embedder.normalization.running_mean")) rename_keys.append(("backbone.0.body.bn1.running_var", "backbone.conv_encoder.model.embedder.embedder.normalization.running_var")) # stages for stage_idx in range(len(config.backbone_config.depths)): for layer_idx in range(config.backbone_config.depths[stage_idx]): # shortcut if layer_idx == 0: rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var", )) # 3 convs for i in range(3): rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var", )) # fmt: on for i in range(config.encoder_layers): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( f"transformer.encoder.layers.{i}.self_attn.out_proj.weight", f"encoder.layers.{i}.self_attn.out_proj.weight", )) rename_keys.append( (f"transformer.encoder.layers.{i}.self_attn.out_proj.bias", f"encoder.layers.{i}.self_attn.out_proj.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"encoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"encoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"encoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"encoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm1.weight", f"encoder.layers.{i}.self_attn_layer_norm.weight")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm1.bias", f"encoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm2.weight", f"encoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"encoder.layers.{i}.final_layer_norm.bias")) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"decoder.layers.{i}.self_attn.out_proj.weight", )) rename_keys.append( (f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"decoder.layers.{i}.self_attn.out_proj.bias")) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight", f"decoder.layers.{i}.encoder_attn.out_proj.weight", )) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias", f"decoder.layers.{i}.encoder_attn.out_proj.bias", )) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"decoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"decoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"decoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"decoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm1.weight", f"decoder.layers.{i}.self_attn_layer_norm.weight")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm1.bias", f"decoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.weight", f"decoder.layers.{i}.encoder_attn_layer_norm.weight")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.bias", f"decoder.layers.{i}.encoder_attn_layer_norm.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm3.weight", f"decoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"decoder.layers.{i}.final_layer_norm.bias")) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ]) return rename_keys def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : str = state_dict.pop(_a) SCREAMING_SNAKE_CASE : int = val def lowerCamelCase__ ( _a , _a=False): SCREAMING_SNAKE_CASE : Optional[Any] = "" if is_panoptic: SCREAMING_SNAKE_CASE : Optional[int] = "detr." # first: transformer encoder for i in range(6): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight") SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias") # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : int = in_proj_bias[:256] SCREAMING_SNAKE_CASE : Tuple = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : List[Any] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : str = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight") SCREAMING_SNAKE_CASE : str = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias") # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : Dict = in_proj_bias[:256] SCREAMING_SNAKE_CASE : List[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : Any = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop( f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight") SCREAMING_SNAKE_CASE : int = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias") # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE : Tuple = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE : Dict = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias_cross_attn[-256:] def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Tuple = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(_a , stream=_a).raw) return im @torch.no_grad() def lowerCamelCase__ ( _a , _a=None , _a=False): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = get_detr_config(_a) # load original model from torch hub SCREAMING_SNAKE_CASE : Union[str, Any] = { "detr-resnet-50": "detr_resnet50", "detr-resnet-101": "detr_resnet101", } logger.info(f"Converting model {model_name}...") SCREAMING_SNAKE_CASE : Optional[int] = torch.hub.load("facebookresearch/detr" , model_name_to_original_name[model_name] , pretrained=_a).eval() SCREAMING_SNAKE_CASE : Tuple = detr.state_dict() # rename keys for src, dest in create_rename_keys(_a): if is_panoptic: SCREAMING_SNAKE_CASE : List[str] = "detr." + src rename_key(_a , _a , _a) # query, key and value matrices need special treatment read_in_q_k_v(_a , is_panoptic=_a) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE : List[Any] = "detr.model." if is_panoptic else "model." for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith("detr") and not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor") ): SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Union[str, Any] = val elif "class_labels_classifier" in key or "bbox_predictor" in key: SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Optional[int] = val elif key.startswith("bbox_attention") or key.startswith("mask_head"): continue else: SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : List[Any] = val else: if not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor"): SCREAMING_SNAKE_CASE : Any = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Any = val # finally, create HuggingFace model and load state dict SCREAMING_SNAKE_CASE : int = DetrForSegmentation(_a) if is_panoptic else DetrForObjectDetection(_a) model.load_state_dict(_a) model.eval() # verify our conversion on an image SCREAMING_SNAKE_CASE : int = "coco_panoptic" if is_panoptic else "coco_detection" SCREAMING_SNAKE_CASE : Optional[int] = DetrImageProcessor(format=_a) SCREAMING_SNAKE_CASE : List[str] = processor(images=prepare_img() , return_tensors="pt") SCREAMING_SNAKE_CASE : Any = encoding["pixel_values"] SCREAMING_SNAKE_CASE : Optional[Any] = detr(_a) SCREAMING_SNAKE_CASE : Any = model(_a) assert torch.allclose(outputs.logits , original_outputs["pred_logits"] , atol=1E-3) assert torch.allclose(outputs.pred_boxes , original_outputs["pred_boxes"] , atol=1E-3) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs["pred_masks"] , atol=1E-4) print("Looks ok!") if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f"Saving PyTorch model and image processor to {pytorch_dump_folder_path}...") Path(_a).mkdir(exist_ok=_a) model.save_pretrained(_a) processor.save_pretrained(_a) if push_to_hub: # Upload model and image processor to the hub logger.info("Uploading PyTorch model and image processor to the hub...") model.push_to_hub(f"nielsr/{model_name}") processor.push_to_hub(f"nielsr/{model_name}") if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') a_ = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
76
1
import baseaa def lowerCamelCase__ ( _a): return baseaa.aaaencode(string.encode("utf-8")) def lowerCamelCase__ ( _a): return baseaa.aaadecode(_a).decode("utf-8") if __name__ == "__main__": import doctest doctest.testmod()
76
import os def lowerCamelCase__ ( ): with open(os.path.dirname(_a) + "/p022_names.txt") as file: SCREAMING_SNAKE_CASE : List[str] = str(file.readlines()[0]) SCREAMING_SNAKE_CASE : List[Any] = names.replace("\"" , "").split(",") names.sort() SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : Dict = 0 for i, name in enumerate(_a): for letter in name: name_score += ord(_a) - 64 total_score += (i + 1) * name_score SCREAMING_SNAKE_CASE : str = 0 return total_score if __name__ == "__main__": print(solution())
76
1
from __future__ import annotations from collections import deque class _UpperCamelCase : '''simple docstring''' def __init__( self : int , a : list[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : list[dict] = [] self.adlist.append( {"value": "", "next_states": [], "fail_state": 0, "output": []} ) for keyword in keywords: self.add_keyword(a ) self.set_fail_transitions() def __UpperCamelCase ( self : Tuple , a : int , a : str ) -> int | None: """simple docstring""" for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def __UpperCamelCase ( self : List[str] , a : str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = 0 for character in keyword: SCREAMING_SNAKE_CASE : Optional[int] = self.find_next_state(a , a ) if next_state is None: self.adlist.append( { "value": character, "next_states": [], "fail_state": 0, "output": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) SCREAMING_SNAKE_CASE : int = len(self.adlist ) - 1 else: SCREAMING_SNAKE_CASE : Dict = next_state self.adlist[current_state]["output"].append(a ) def __UpperCamelCase ( self : List[Any] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : deque = deque() for node in self.adlist[0]["next_states"]: q.append(a ) SCREAMING_SNAKE_CASE : List[Any] = 0 while q: SCREAMING_SNAKE_CASE : Any = q.popleft() for child in self.adlist[r]["next_states"]: q.append(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.adlist[r]["fail_state"] while ( self.find_next_state(a , self.adlist[child]["value"] ) is None and state != 0 ): SCREAMING_SNAKE_CASE : str = self.adlist[state]["fail_state"] SCREAMING_SNAKE_CASE : Dict = self.find_next_state( a , self.adlist[child]["value"] ) if self.adlist[child]["fail_state"] is None: SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : Dict = ( self.adlist[child]["output"] + self.adlist[self.adlist[child]["fail_state"]]["output"] ) def __UpperCamelCase ( self : Optional[Any] , a : str ) -> dict[str, list[int]]: """simple docstring""" SCREAMING_SNAKE_CASE : dict = {} # returns a dict with keywords and list of its occurrences SCREAMING_SNAKE_CASE : Optional[Any] = 0 for i in range(len(a ) ): while ( self.find_next_state(a , string[i] ) is None and current_state != 0 ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.adlist[current_state]["fail_state"] SCREAMING_SNAKE_CASE : Optional[Any] = self.find_next_state(a , string[i] ) if next_state is None: SCREAMING_SNAKE_CASE : Optional[int] = 0 else: SCREAMING_SNAKE_CASE : Optional[int] = next_state for key in self.adlist[current_state]["output"]: if key not in result: SCREAMING_SNAKE_CASE : str = [] result[key].append(i - len(a ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
76
from collections.abc import Callable import numpy as np def lowerCamelCase__ ( _a , _a , _a , _a , _a): SCREAMING_SNAKE_CASE : Dict = int(np.ceil((x_end - xa) / step_size)) SCREAMING_SNAKE_CASE : Tuple = np.zeros((n + 1,)) SCREAMING_SNAKE_CASE : int = ya SCREAMING_SNAKE_CASE : int = xa for k in range(_a): SCREAMING_SNAKE_CASE : Any = y[k] + step_size * ode_func(_a , y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
76
1
import json import sys def lowerCamelCase__ ( _a , _a): with open(_a , encoding="utf-8") as f: SCREAMING_SNAKE_CASE : Any = json.load(_a) SCREAMING_SNAKE_CASE : Any = ["<details>", "<summary>Show updated benchmarks!</summary>", " "] for benchmark_name in sorted(_a): SCREAMING_SNAKE_CASE : str = results[benchmark_name] SCREAMING_SNAKE_CASE : Optional[int] = benchmark_name.split("/")[-1] output_md.append(f"### Benchmark: {benchmark_file_name}") SCREAMING_SNAKE_CASE : str = "| metric |" SCREAMING_SNAKE_CASE : str = "|--------|" SCREAMING_SNAKE_CASE : List[Any] = "| new / old (diff) |" for metric_name in sorted(_a): SCREAMING_SNAKE_CASE : Optional[int] = benchmark_res[metric_name] SCREAMING_SNAKE_CASE : Any = metric_vals["new"] SCREAMING_SNAKE_CASE : Optional[Any] = metric_vals.get("old" , _a) SCREAMING_SNAKE_CASE : Optional[Any] = metric_vals.get("diff" , _a) SCREAMING_SNAKE_CASE : int = f" {new_val:f}" if isinstance(_a , (int, float)) else "None" if old_val is not None: val_str += f" / {old_val:f}" if isinstance(_a , (int, float)) else "None" if dif_val is not None: val_str += f" ({dif_val:f})" if isinstance(_a , (int, float)) else "None" title += " " + metric_name + " |" lines += "---|" value += val_str + " |" output_md += [title, lines, value, " "] output_md.append("</details>") with open(_a , "w" , encoding="utf-8") as f: f.writelines("\n".join(_a)) if __name__ == "__main__": a_ = sys.argv[1] a_ = sys.argv[2] format_json_to_md(input_json_file, output_md_file)
76
def lowerCamelCase__ ( _a , _a): return int((input_a, input_a).count(1) != 0) def lowerCamelCase__ ( ): assert or_gate(0 , 0) == 0 assert or_gate(0 , 1) == 1 assert or_gate(1 , 0) == 1 assert or_gate(1 , 1) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
76
1
import os import tempfile import unittest from transformers import DistilBertConfig, 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 ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, ) class _UpperCamelCase ( __A ): '''simple docstring''' def __init__( self : List[str] , a : List[Any] , a : List[Any]=13 , a : Dict=7 , a : Optional[Any]=True , a : List[Any]=True , a : Tuple=False , a : Dict=True , a : Dict=99 , a : List[str]=32 , a : Dict=5 , a : Dict=4 , a : Tuple=37 , a : str="gelu" , a : Optional[Any]=0.1 , a : Optional[int]=0.1 , a : int=512 , a : Union[str, Any]=16 , a : Dict=2 , a : List[str]=0.02 , a : Any=3 , a : Tuple=4 , a : Union[str, Any]=None , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = parent SCREAMING_SNAKE_CASE : Optional[Any] = batch_size SCREAMING_SNAKE_CASE : List[str] = seq_length SCREAMING_SNAKE_CASE : Optional[Any] = is_training SCREAMING_SNAKE_CASE : str = use_input_mask SCREAMING_SNAKE_CASE : List[str] = use_token_type_ids SCREAMING_SNAKE_CASE : int = use_labels SCREAMING_SNAKE_CASE : Any = vocab_size SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Any = num_attention_heads SCREAMING_SNAKE_CASE : List[Any] = intermediate_size SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : Any = hidden_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Dict = max_position_embeddings SCREAMING_SNAKE_CASE : str = type_vocab_size SCREAMING_SNAKE_CASE : str = type_sequence_label_size SCREAMING_SNAKE_CASE : Any = initializer_range SCREAMING_SNAKE_CASE : Any = num_labels SCREAMING_SNAKE_CASE : List[Any] = num_choices SCREAMING_SNAKE_CASE : Dict = scope def __UpperCamelCase ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : List[str] = None if self.use_input_mask: SCREAMING_SNAKE_CASE : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Tuple = None SCREAMING_SNAKE_CASE : Optional[Any] = None SCREAMING_SNAKE_CASE : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE : Dict = 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[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : List[Any] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase ( self : Union[str, Any] ) -> int: """simple docstring""" return DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) def __UpperCamelCase ( self : str , a : Any , a : Optional[Any] , a : List[str] , a : List[str] , a : Union[str, Any] , a : List[str] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = DistilBertModel(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(a , a ) SCREAMING_SNAKE_CASE : str = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self : Optional[Any] , a : Dict , a : Tuple , a : Optional[int] , a : Optional[Any] , a : Any , a : int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = DistilBertForMaskedLM(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Optional[Any] = model(a , attention_mask=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase ( self : str , a : Optional[Any] , a : int , a : Tuple , a : Union[str, Any] , a : int , a : Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = DistilBertForQuestionAnswering(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Union[str, Any] = model( a , attention_mask=a , start_positions=a , end_positions=a ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __UpperCamelCase ( self : Tuple , a : str , a : Any , a : Optional[int] , a : Dict , a : Dict , a : Union[str, Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Any = self.num_labels SCREAMING_SNAKE_CASE : List[Any] = DistilBertForSequenceClassification(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.num_labels) ) def __UpperCamelCase ( self : Optional[int] , a : Dict , a : Any , a : List[Any] , a : List[Any] , a : Dict , a : List[str] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : str = self.num_labels SCREAMING_SNAKE_CASE : Optional[int] = DistilBertForTokenClassification(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Dict = model(a , attention_mask=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase ( self : str , a : Any , a : int , a : Dict , a : int , a : Optional[Any] , a : List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.num_choices SCREAMING_SNAKE_CASE : Optional[int] = DistilBertForMultipleChoice(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Tuple = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : str = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : Tuple = model( a , attention_mask=a , labels=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase ( self : Optional[Any] ) -> List[str]: """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)) : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE : List[Any] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class _UpperCamelCase ( __A , __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =( ( DistilBertModel, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, ) if is_torch_available() else None ) lowerCamelCase__ =( { 'feature-extraction': DistilBertModel, 'fill-mask': DistilBertForMaskedLM, 'question-answering': DistilBertForQuestionAnswering, 'text-classification': DistilBertForSequenceClassification, 'token-classification': DistilBertForTokenClassification, 'zero-shot': DistilBertForSequenceClassification, } if is_torch_available() else {} ) lowerCamelCase__ =True lowerCamelCase__ =True lowerCamelCase__ =True lowerCamelCase__ =True def __UpperCamelCase ( self : Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = DistilBertModelTester(self ) SCREAMING_SNAKE_CASE : Union[str, Any] = ConfigTester(self , config_class=a , dim=37 ) def __UpperCamelCase ( self : List[str] ) -> Dict: """simple docstring""" self.config_tester.run_common_tests() def __UpperCamelCase ( self : str ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*a ) def __UpperCamelCase ( self : Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*a ) def __UpperCamelCase ( self : Any ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*a ) def __UpperCamelCase ( self : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*a ) def __UpperCamelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*a ) def __UpperCamelCase ( self : List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*a ) @slow def __UpperCamelCase ( self : Any ) -> Tuple: """simple docstring""" for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Dict = DistilBertModel.from_pretrained(a ) self.assertIsNotNone(a ) @slow @require_torch_gpu def __UpperCamelCase ( self : Union[str, Any] ) -> Optional[int]: """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: # BertForMultipleChoice behaves incorrectly in JIT environments. if model_class == DistilBertForMultipleChoice: return SCREAMING_SNAKE_CASE : int = True SCREAMING_SNAKE_CASE : Any = model_class(config=a ) SCREAMING_SNAKE_CASE : int = self._prepare_for_class(a , a ) SCREAMING_SNAKE_CASE : Dict = 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[int] = 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 _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = DistilBertModel.from_pretrained("distilbert-base-uncased" ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) SCREAMING_SNAKE_CASE : int = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE : Optional[Any] = model(a , attention_mask=a )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , a ) SCREAMING_SNAKE_CASE : Any = torch.tensor( [[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , a , atol=1e-4 ) )
76
a_ = 8.314_4598 def lowerCamelCase__ ( _a , _a): if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example a_ = 300 a_ = 28 a_ = rms_speed_of_molecule(temperature, molar_mass) print(F'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
76
1
import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, ) a_ = logging.getLogger(__name__) def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=_a) SCREAMING_SNAKE_CASE : Optional[int] = { "repo_id": str(_a), "repo_sha": str(repo.head.object.hexsha), "repo_branch": str(repo.active_branch), } with open(os.path.join(_a , "git_log.json") , "w") as f: json.dump(_a , _a , indent=4) def lowerCamelCase__ ( _a): if params.n_gpu <= 0: SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : int = -1 SCREAMING_SNAKE_CASE : List[Any] = True SCREAMING_SNAKE_CASE : str = False return assert torch.cuda.is_available() logger.info("Initializing GPUs") if params.n_gpu > 1: assert params.local_rank != -1 SCREAMING_SNAKE_CASE : Union[str, Any] = int(os.environ["WORLD_SIZE"]) SCREAMING_SNAKE_CASE : Optional[Any] = int(os.environ["N_GPU_NODE"]) SCREAMING_SNAKE_CASE : int = int(os.environ["RANK"]) # number of nodes / node ID SCREAMING_SNAKE_CASE : Any = params.world_size // params.n_gpu_per_node SCREAMING_SNAKE_CASE : Any = params.global_rank // params.n_gpu_per_node SCREAMING_SNAKE_CASE : List[Any] = True assert params.n_nodes == int(os.environ["N_NODES"]) assert params.node_id == int(os.environ["NODE_RANK"]) # local job (single GPU) else: assert params.local_rank == -1 SCREAMING_SNAKE_CASE : str = 1 SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : Tuple = 0 SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : Tuple = 1 SCREAMING_SNAKE_CASE : List[Any] = 1 SCREAMING_SNAKE_CASE : Tuple = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode SCREAMING_SNAKE_CASE : Tuple = params.node_id == 0 and params.local_rank == 0 SCREAMING_SNAKE_CASE : int = params.n_nodes > 1 # summary SCREAMING_SNAKE_CASE : str = f"--- Global rank: {params.global_rank} - " logger.info(PREFIX + "Number of nodes: %i" % params.n_nodes) logger.info(PREFIX + "Node ID : %i" % params.node_id) logger.info(PREFIX + "Local rank : %i" % params.local_rank) logger.info(PREFIX + "World size : %i" % params.world_size) logger.info(PREFIX + "GPUs per node : %i" % params.n_gpu_per_node) logger.info(PREFIX + "Master : %s" % str(params.is_master)) logger.info(PREFIX + "Multi-node : %s" % str(params.multi_node)) logger.info(PREFIX + "Multi-GPU : %s" % str(params.multi_gpu)) logger.info(PREFIX + "Hostname : %s" % socket.gethostname()) # set GPU device torch.cuda.set_device(params.local_rank) # initialize multi-GPU if params.multi_gpu: logger.info("Initializing PyTorch distributed") torch.distributed.init_process_group( init_method="env://" , backend="nccl" , ) def lowerCamelCase__ ( _a): np.random.seed(args.seed) torch.manual_seed(args.seed) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed)
76
a_ = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : int = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE : int = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE : Optional[int] = queue.pop(0) # get the last node from the path SCREAMING_SNAKE_CASE : Union[str, Any] = path[-1] if node not in explored: SCREAMING_SNAKE_CASE : List[str] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE : List[Any] = list(_a) new_path.append(_a) queue.append(_a) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_a) # in case there's no path between the 2 nodes return [] def lowerCamelCase__ ( _a , _a , _a): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE : str = [start] SCREAMING_SNAKE_CASE : Optional[Any] = set(_a) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE : Union[str, Any] = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE : Optional[int] = queue.pop(0) if node == target: SCREAMING_SNAKE_CASE : Union[str, Any] = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node]) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_a) queue.append(_a) SCREAMING_SNAKE_CASE : Optional[Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, 'G', 'D')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, 'G', 'D')) # returns 4
76
1
def lowerCamelCase__ ( _a , _a): return int((input_a, input_a).count(1) != 0) def lowerCamelCase__ ( ): assert or_gate(0 , 0) == 0 assert or_gate(0 , 1) == 1 assert or_gate(1 , 0) == 1 assert or_gate(1 , 1) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
76
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE : Tuple = tokenizer("Hello there" , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer("Hi I am" , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE : str = model(a , labels=a ).loss SCREAMING_SNAKE_CASE : Any = -tf.math.reduce_mean(a ).numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = -21.22_8168 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2e-4 )
76
1
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_barthez import BarthezTokenizer else: a_ = None a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'} a_ = { 'vocab_file': { 'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model', 'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model', 'moussaKam/barthez-orangesum-title': ( 'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model' ), }, 'tokenizer_file': { 'moussaKam/mbarthez': 'https://huggingface.co/moussaKam/mbarthez/resolve/main/tokenizer.json', 'moussaKam/barthez': 'https://huggingface.co/moussaKam/barthez/resolve/main/tokenizer.json', 'moussaKam/barthez-orangesum-title': ( 'https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/tokenizer.json' ), }, } a_ = { 'moussaKam/mbarthez': 1024, 'moussaKam/barthez': 1024, 'moussaKam/barthez-orangesum-title': 1024, } a_ = '▁' class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =VOCAB_FILES_NAMES lowerCamelCase__ =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ =['input_ids', 'attention_mask'] lowerCamelCase__ =BarthezTokenizer def __init__( self : List[Any] , a : Union[str, Any]=None , a : Any=None , a : Optional[int]="<s>" , a : Optional[Any]="</s>" , a : Any="</s>" , a : List[Any]="<s>" , a : str="<unk>" , a : Tuple="<pad>" , a : int="<mask>" , **a : Union[str, Any] , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = AddedToken(a , lstrip=a , rstrip=a ) if isinstance(a , a ) else mask_token super().__init__( a , tokenizer_file=a , bos_token=a , eos_token=a , unk_token=a , sep_token=a , cls_token=a , pad_token=a , mask_token=a , **a , ) SCREAMING_SNAKE_CASE : List[Any] = vocab_file SCREAMING_SNAKE_CASE : Dict = False if not self.vocab_file else True def __UpperCamelCase ( self : Any , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] SCREAMING_SNAKE_CASE : int = [self.cls_token_id] SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def __UpperCamelCase ( self : str , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE : int = [self.sep_token_id] SCREAMING_SNAKE_CASE : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def __UpperCamelCase ( self : Union[str, Any] , a : str , a : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow " "tokenizer." ) if not os.path.isdir(a ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join( a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a ): copyfile(self.vocab_file , a ) return (out_vocab_file,)
76
from math import factorial def lowerCamelCase__ ( _a , _a , _a): if successes > trials: raise ValueError("successes must be lower or equal to trials") if trials < 0 or successes < 0: raise ValueError("the function is defined for non-negative integers") if not isinstance(_a , _a) or not isinstance(_a , _a): raise ValueError("the function is defined for non-negative integers") if not 0 < prob < 1: raise ValueError("prob has to be in range of 1 - 0") SCREAMING_SNAKE_CASE : int = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! SCREAMING_SNAKE_CASE : List[Any] = float(factorial(_a)) coefficient /= factorial(_a) * factorial(trials - successes) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
76
1
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. a_ = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(_a) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE : Union[str, Any] = terminalreporter.config.getoption("--make-reports") if make_reports: pytest_terminal_summary_main(_a , id=_a)
76
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =CustomTokenizer pass
76
1
from __future__ import annotations import math def lowerCamelCase__ ( _a): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(_a) + 1) , 6): if number % i == 0 or number % (i + 2) == 0: return False return True a_ = [num for num in range(3, 10_0001, 2) if not is_prime(num)] def lowerCamelCase__ ( _a): if not isinstance(_a , _a): raise ValueError("n must be an integer") if n <= 0: raise ValueError("n must be >= 0") SCREAMING_SNAKE_CASE : Dict = [] for num in range(len(_a)): SCREAMING_SNAKE_CASE : Optional[Any] = 0 while 2 * i * i <= odd_composites[num]: SCREAMING_SNAKE_CASE : Optional[Any] = odd_composites[num] - 2 * i * i if is_prime(_a): break i += 1 else: list_nums.append(odd_composites[num]) if len(_a) == n: return list_nums return [] def lowerCamelCase__ ( ): return compute_nums(1)[0] if __name__ == "__main__": print(F'''{solution() = }''')
76
import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex a_ = logging.getLogger(__name__) class _UpperCamelCase : '''simple docstring''' def __init__( self : Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = False def __UpperCamelCase ( self : str , a : str , a : Optional[int] , a : Any , a : str ) -> List[Any]: """simple docstring""" if not self.initialized: SCREAMING_SNAKE_CASE : List[str] = RagRetriever( a , question_encoder_tokenizer=a , generator_tokenizer=a , index=a , init_retrieval=a , ) SCREAMING_SNAKE_CASE : Optional[int] = True def __UpperCamelCase ( self : List[str] ) -> Optional[int]: """simple docstring""" self.retriever.index.init_index() def __UpperCamelCase ( self : Optional[Any] , a : List[Any] , a : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = self.retriever._main_retrieve(a , a ) return doc_ids, retrieved_doc_embeds class _UpperCamelCase ( __A ): '''simple docstring''' def __init__( self : Tuple , a : Any , a : Tuple , a : Tuple , a : Tuple , a : List[Any]=None ) -> Optional[int]: """simple docstring""" if index is not None and index.is_initialized() and len(a ) > 0: raise ValueError( "When using Ray for distributed fine-tuning, " "you'll need to provide the paths instead, " "as the dataset and the index are loaded " "separately. More info in examples/rag/use_own_knowledge_dataset.py " ) super().__init__( a , question_encoder_tokenizer=a , generator_tokenizer=a , index=a , init_retrieval=a , ) SCREAMING_SNAKE_CASE : Optional[Any] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(a , a , a , a ) for worker in self.retrieval_workers ] ) def __UpperCamelCase ( self : Any ) -> Dict: """simple docstring""" logger.info("initializing retrieval" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __UpperCamelCase ( self : Tuple , a : Optional[int] , a : Any ) -> int: """simple docstring""" if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. SCREAMING_SNAKE_CASE : Optional[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = ray.get(random_worker.retrieve.remote(a , a ) ) else: SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Any = self._main_retrieve(a , a ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(a ) @classmethod def __UpperCamelCase ( cls : str , a : Optional[Any] , a : Any=None , **a : List[Any] ) -> str: """simple docstring""" return super(a , cls ).get_tokenizers(a , a , **a ) @classmethod def __UpperCamelCase ( cls : Union[str, Any] , a : int , a : Any , a : List[Any]=None , **a : Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : str = kwargs.pop("config" , a ) or RagConfig.from_pretrained(a , **a ) SCREAMING_SNAKE_CASE : List[Any] = RagTokenizer.from_pretrained(a , config=a ) SCREAMING_SNAKE_CASE : List[Any] = rag_tokenizer.question_encoder SCREAMING_SNAKE_CASE : List[Any] = rag_tokenizer.generator if indexed_dataset is not None: SCREAMING_SNAKE_CASE : str = "custom" SCREAMING_SNAKE_CASE : List[Any] = CustomHFIndex(config.retrieval_vector_size , a ) else: SCREAMING_SNAKE_CASE : List[str] = cls._build_index(a ) return cls( a , question_encoder_tokenizer=a , generator_tokenizer=a , retrieval_workers=a , index=a , )
76
1
from __future__ import annotations import unittest from transformers import DistilBertConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.distilbert.modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertModel, ) class _UpperCamelCase : '''simple docstring''' def __init__( self : Tuple , a : str , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : Union[str, Any] = 13 SCREAMING_SNAKE_CASE : Union[str, Any] = 7 SCREAMING_SNAKE_CASE : Union[str, Any] = True SCREAMING_SNAKE_CASE : Optional[Any] = True SCREAMING_SNAKE_CASE : int = False SCREAMING_SNAKE_CASE : Dict = True SCREAMING_SNAKE_CASE : Tuple = 99 SCREAMING_SNAKE_CASE : Dict = 32 SCREAMING_SNAKE_CASE : List[Any] = 2 SCREAMING_SNAKE_CASE : Dict = 4 SCREAMING_SNAKE_CASE : Union[str, Any] = 37 SCREAMING_SNAKE_CASE : Optional[Any] = "gelu" SCREAMING_SNAKE_CASE : Union[str, Any] = 0.1 SCREAMING_SNAKE_CASE : Any = 0.1 SCREAMING_SNAKE_CASE : Any = 512 SCREAMING_SNAKE_CASE : Any = 16 SCREAMING_SNAKE_CASE : List[str] = 2 SCREAMING_SNAKE_CASE : Dict = 0.02 SCREAMING_SNAKE_CASE : List[Any] = 3 SCREAMING_SNAKE_CASE : Dict = 4 SCREAMING_SNAKE_CASE : List[Any] = None def __UpperCamelCase ( self : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE : Tuple = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : List[Any] = None SCREAMING_SNAKE_CASE : int = None if self.use_labels: SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE : Optional[int] = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , ) return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def __UpperCamelCase ( self : Optional[Any] , a : List[Any] , a : Optional[int] , a : Optional[int] , a : Dict , a : Any , a : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = TFDistilBertModel(config=a ) SCREAMING_SNAKE_CASE : List[str] = {"input_ids": input_ids, "attention_mask": input_mask} SCREAMING_SNAKE_CASE : Dict = model(a ) SCREAMING_SNAKE_CASE : int = [input_ids, input_mask] SCREAMING_SNAKE_CASE : int = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self : Optional[Any] , a : Dict , a : Tuple , a : str , a : int , a : List[str] , a : Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = TFDistilBertForMaskedLM(config=a ) SCREAMING_SNAKE_CASE : Optional[Any] = {"input_ids": input_ids, "attention_mask": input_mask} SCREAMING_SNAKE_CASE : List[Any] = model(a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __UpperCamelCase ( self : Any , a : List[Any] , a : str , a : Union[str, Any] , a : Dict , a : Optional[int] , a : List[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = TFDistilBertForQuestionAnswering(config=a ) SCREAMING_SNAKE_CASE : Union[str, Any] = { "input_ids": input_ids, "attention_mask": input_mask, } SCREAMING_SNAKE_CASE : List[str] = model(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 __UpperCamelCase ( self : int , a : List[Any] , a : Dict , a : Tuple , a : Tuple , a : Tuple , a : Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.num_labels SCREAMING_SNAKE_CASE : List[Any] = TFDistilBertForSequenceClassification(a ) SCREAMING_SNAKE_CASE : Optional[int] = {"input_ids": input_ids, "attention_mask": input_mask} SCREAMING_SNAKE_CASE : Optional[int] = model(a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __UpperCamelCase ( self : Any , a : Any , a : Optional[int] , a : Any , a : int , a : int , a : Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = self.num_choices SCREAMING_SNAKE_CASE : Dict = TFDistilBertForMultipleChoice(a ) SCREAMING_SNAKE_CASE : Dict = tf.tile(tf.expand_dims(a , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE : Dict = tf.tile(tf.expand_dims(a , 1 ) , (1, self.num_choices, 1) ) SCREAMING_SNAKE_CASE : int = { "input_ids": multiple_choice_inputs_ids, "attention_mask": multiple_choice_input_mask, } SCREAMING_SNAKE_CASE : Dict = model(a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase ( self : Optional[Any] , a : List[str] , a : Dict , a : List[Any] , a : List[Any] , a : Union[str, Any] , a : Dict ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE : Any = TFDistilBertForTokenClassification(a ) SCREAMING_SNAKE_CASE : int = {"input_ids": input_ids, "attention_mask": input_mask} SCREAMING_SNAKE_CASE : str = model(a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() ((SCREAMING_SNAKE_CASE) ,(SCREAMING_SNAKE_CASE) ,(SCREAMING_SNAKE_CASE) ,(SCREAMING_SNAKE_CASE) ,(SCREAMING_SNAKE_CASE) ,(SCREAMING_SNAKE_CASE)) : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE : Optional[int] = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class _UpperCamelCase ( __A , __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =( ( TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertForMultipleChoice, ) if is_tf_available() else None ) lowerCamelCase__ =( { 'feature-extraction': TFDistilBertModel, 'fill-mask': TFDistilBertForMaskedLM, 'question-answering': TFDistilBertForQuestionAnswering, 'text-classification': TFDistilBertForSequenceClassification, 'token-classification': TFDistilBertForTokenClassification, 'zero-shot': TFDistilBertForSequenceClassification, } if is_tf_available() else {} ) lowerCamelCase__ =False lowerCamelCase__ =False def __UpperCamelCase ( self : int ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = TFDistilBertModelTester(self ) SCREAMING_SNAKE_CASE : int = ConfigTester(self , config_class=a , dim=37 ) def __UpperCamelCase ( self : str ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def __UpperCamelCase ( self : List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_model(*a ) def __UpperCamelCase ( self : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_masked_lm(*a ) def __UpperCamelCase ( self : List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_question_answering(*a ) def __UpperCamelCase ( self : Optional[int] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_sequence_classification(*a ) def __UpperCamelCase ( self : Tuple ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_multiple_choice(*a ) def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_distilbert_for_token_classification(*a ) @slow def __UpperCamelCase ( self : Dict ) -> Any: """simple docstring""" for model_name in list(TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1] ): SCREAMING_SNAKE_CASE : List[str] = TFDistilBertModel.from_pretrained(a ) self.assertIsNotNone(a ) @require_tf class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : Optional[int] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = TFDistilBertModel.from_pretrained("distilbert-base-uncased" ) SCREAMING_SNAKE_CASE : Union[str, Any] = tf.constant([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE : Union[str, Any] = model(a )[0] SCREAMING_SNAKE_CASE : int = [1, 6, 768] self.assertEqual(output.shape , a ) SCREAMING_SNAKE_CASE : str = tf.constant( [ [ [0.1926_1885, -0.1373_2955, 0.411_9799], [0.2215_0156, -0.0742_2661, 0.3903_7204], [0.2275_6018, -0.089_6414, 0.370_1467], ] ] ) tf.debugging.assert_near(output[:, :3, :3] , a , atol=1e-4 )
76
from typing import Any class _UpperCamelCase : '''simple docstring''' def __init__( self : Dict , a : Any ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : int = data SCREAMING_SNAKE_CASE : int = None def __repr__( self : str ) -> str: """simple docstring""" return F"Node({self.data})" class _UpperCamelCase : '''simple docstring''' def __init__( self : List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = None def __iter__( self : Any ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.head while node: yield node.data SCREAMING_SNAKE_CASE : List[str] = node.next def __len__( self : str ) -> int: """simple docstring""" return sum(1 for _ in self ) def __repr__( self : Optional[Any] ) -> str: """simple docstring""" return "->".join([str(a ) for item in self] ) def __getitem__( self : List[Any] , a : int ) -> Any: """simple docstring""" if not 0 <= index < len(self ): raise ValueError("list index out of range." ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Tuple , a : int , a : Any ) -> None: """simple docstring""" if not 0 <= index < len(self ): raise ValueError("list index out of range." ) SCREAMING_SNAKE_CASE : str = self.head for _ in range(a ): SCREAMING_SNAKE_CASE : str = current.next SCREAMING_SNAKE_CASE : Any = data def __UpperCamelCase ( self : List[str] , a : Any ) -> None: """simple docstring""" self.insert_nth(len(self ) , a ) def __UpperCamelCase ( self : Union[str, Any] , a : Any ) -> None: """simple docstring""" self.insert_nth(0 , a ) def __UpperCamelCase ( self : Optional[Any] , a : int , a : Any ) -> None: """simple docstring""" if not 0 <= index <= len(self ): raise IndexError("list index out of range" ) SCREAMING_SNAKE_CASE : Any = Node(a ) if self.head is None: SCREAMING_SNAKE_CASE : Optional[int] = new_node elif index == 0: SCREAMING_SNAKE_CASE : Optional[int] = self.head # link new_node to head SCREAMING_SNAKE_CASE : List[Any] = new_node else: SCREAMING_SNAKE_CASE : Optional[Any] = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : Optional[int] = temp.next SCREAMING_SNAKE_CASE : Optional[int] = temp.next SCREAMING_SNAKE_CASE : int = new_node def __UpperCamelCase ( self : Optional[int] ) -> None: # print every node data """simple docstring""" print(self ) def __UpperCamelCase ( self : int ) -> Any: """simple docstring""" return self.delete_nth(0 ) def __UpperCamelCase ( self : Any ) -> Any: # delete from tail """simple docstring""" return self.delete_nth(len(self ) - 1 ) def __UpperCamelCase ( self : List[str] , a : int = 0 ) -> Any: """simple docstring""" if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("List index out of range." ) SCREAMING_SNAKE_CASE : Tuple = self.head # default first node if index == 0: SCREAMING_SNAKE_CASE : List[str] = self.head.next else: SCREAMING_SNAKE_CASE : Optional[Any] = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : Any = temp.next SCREAMING_SNAKE_CASE : List[Any] = temp.next SCREAMING_SNAKE_CASE : List[str] = temp.next.next return delete_node.data def __UpperCamelCase ( self : List[Any] ) -> bool: """simple docstring""" return self.head is None def __UpperCamelCase ( self : Optional[int] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = None SCREAMING_SNAKE_CASE : str = self.head while current: # Store the current node's next node. SCREAMING_SNAKE_CASE : Any = current.next # Make the current node's next point backwards SCREAMING_SNAKE_CASE : List[Any] = prev # Make the previous node be the current node SCREAMING_SNAKE_CASE : Any = current # Make the current node the next node (to progress iteration) SCREAMING_SNAKE_CASE : str = next_node # Return prev in order to put the head at the end SCREAMING_SNAKE_CASE : Optional[Any] = prev def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Union[str, Any] = LinkedList() assert linked_list.is_empty() is True assert str(_a) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(_a) == i linked_list.insert_nth(_a , i + 1) assert str(_a) == "->".join(str(_a) for i in range(1 , 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(_a) == "->".join(str(_a) for i in range(0 , 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(_a) == 9 assert str(_a) == "->".join(str(_a) for i in range(1 , 10)) assert all(linked_list[i] == i + 1 for i in range(0 , 9)) is True for i in range(0 , 9): SCREAMING_SNAKE_CASE : str = -i assert all(linked_list[i] == -i for i in range(0 , 9)) is True linked_list.reverse() assert str(_a) == "->".join(str(_a) for i in range(-8 , 1)) def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Optional[Any] = [ -9, 100, Node(77345112), "dlrow olleH", 7, 5555, 0, -192.5_5555, "Hello, world!", 77.9, Node(10), None, None, 12.20, ] SCREAMING_SNAKE_CASE : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(_a) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(_a) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head SCREAMING_SNAKE_CASE : List[Any] = linked_list.delete_head() assert result == -9 assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail SCREAMING_SNAKE_CASE : Any = linked_list.delete_tail() assert result == 12.2 assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list SCREAMING_SNAKE_CASE : Any = linked_list.delete_nth(10) assert result is None assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!")) assert ( str(_a) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(_a) assert ( str(_a) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(_a) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def lowerCamelCase__ ( ): from doctest import testmod testmod() SCREAMING_SNAKE_CASE : Optional[int] = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(_a) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") SCREAMING_SNAKE_CASE : Dict = input("Enter New Value: ").strip() print("New list:") print(_a) print(f"length of linked_list is : {len(_a)}") if __name__ == "__main__": main()
76
1
import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # 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 six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets a_ = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' a_ = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' a_ = '\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\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.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _UpperCamelCase ( datasets.Metric ): '''simple docstring''' def __UpperCamelCase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Value("string" , id="sequence" ), } ) , codebase_urls=["https://github.com/google-research/google-research/tree/master/rouge"] , reference_urls=[ "https://en.wikipedia.org/wiki/ROUGE_(metric)", "https://github.com/google-research/google-research/tree/master/rouge", ] , ) def __UpperCamelCase ( self : int , a : Any , a : Tuple , a : str=None , a : int=True , a : Optional[Any]=False ) -> List[str]: """simple docstring""" if rouge_types is None: SCREAMING_SNAKE_CASE : Any = ["rouge1", "rouge2", "rougeL", "rougeLsum"] SCREAMING_SNAKE_CASE : List[str] = rouge_scorer.RougeScorer(rouge_types=a , use_stemmer=a ) if use_aggregator: SCREAMING_SNAKE_CASE : Union[str, Any] = scoring.BootstrapAggregator() else: SCREAMING_SNAKE_CASE : Union[str, Any] = [] for ref, pred in zip(a , a ): SCREAMING_SNAKE_CASE : int = scorer.score(a , a ) if use_aggregator: aggregator.add_scores(a ) else: scores.append(a ) if use_aggregator: SCREAMING_SNAKE_CASE : Optional[int] = aggregator.aggregate() else: SCREAMING_SNAKE_CASE : Tuple = {} for key in scores[0]: SCREAMING_SNAKE_CASE : List[Any] = [score[key] for score in scores] return result
76
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger a_ = get_logger(__name__) class _UpperCamelCase ( enum.Enum ): '''simple docstring''' lowerCamelCase__ ='all_checks' lowerCamelCase__ ='basic_checks' lowerCamelCase__ ='no_checks' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' def lowerCamelCase__ ( _a , _a , _a=None): if expected_checksums is None: logger.info("Unable to verify checksums.") return if len(set(_a) - set(_a)) > 0: raise ExpectedMoreDownloadedFiles(str(set(_a) - set(_a))) if len(set(_a) - set(_a)) > 0: raise UnexpectedDownloadedFile(str(set(_a) - set(_a))) SCREAMING_SNAKE_CASE : str = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] SCREAMING_SNAKE_CASE : Tuple = " for " + verification_name if verification_name is not None else "" if len(_a) > 0: raise NonMatchingChecksumError( f"Checksums didn't match{for_verification_name}:\n" f"{bad_urls}\n" "Set `verification_mode='no_checks'` to skip checksums verification and ignore this error") logger.info("All the checksums matched successfully" + for_verification_name) class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' def lowerCamelCase__ ( _a , _a): if expected_splits is None: logger.info("Unable to verify splits sizes.") return if len(set(_a) - set(_a)) > 0: raise ExpectedMoreSplits(str(set(_a) - set(_a))) if len(set(_a) - set(_a)) > 0: raise UnexpectedSplits(str(set(_a) - set(_a))) SCREAMING_SNAKE_CASE : List[str] = [ {"expected": expected_splits[name], "recorded": recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(_a) > 0: raise NonMatchingSplitsSizesError(str(_a)) logger.info("All the splits matched successfully.") def lowerCamelCase__ ( _a , _a = True): if record_checksum: SCREAMING_SNAKE_CASE : List[str] = shaaaa() with open(_a , "rb") as f: for chunk in iter(lambda: f.read(1 << 20) , b""): m.update(_a) SCREAMING_SNAKE_CASE : Optional[int] = m.hexdigest() else: SCREAMING_SNAKE_CASE : List[str] = None return {"num_bytes": os.path.getsize(_a), "checksum": checksum} def lowerCamelCase__ ( _a): if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
76
1
import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel a_ = '0.12' # assumed parallelism: 8 @require_flax @is_staging_test class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @classmethod def __UpperCamelCase ( cls : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = TOKEN HfFolder.save_token(a ) @classmethod def __UpperCamelCase ( cls : List[str] ) -> Optional[Any]: """simple docstring""" try: delete_repo(token=cls._token , repo_id="test-model-flax" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-model-flax-org" ) except HTTPError: pass def __UpperCamelCase ( self : Union[str, Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) SCREAMING_SNAKE_CASE : List[str] = FlaxBertModel(a ) model.push_to_hub("test-model-flax" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : List[Any] = FlaxBertModel.from_pretrained(F"{USER}/test-model-flax" ) SCREAMING_SNAKE_CASE : Tuple = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE : Dict = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE : Dict = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(a , 1e-3 , msg=F"{key} not identical" ) # Reset repo delete_repo(token=self._token , repo_id="test-model-flax" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(a , repo_id="test-model-flax" , push_to_hub=a , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : int = FlaxBertModel.from_pretrained(F"{USER}/test-model-flax" ) SCREAMING_SNAKE_CASE : str = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE : Any = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE : str = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(a , 1e-3 , msg=F"{key} not identical" ) def __UpperCamelCase ( self : Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxBertModel(a ) model.push_to_hub("valid_org/test-model-flax-org" , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org" ) SCREAMING_SNAKE_CASE : str = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE : List[Any] = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE : Any = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(a , 1e-3 , msg=F"{key} not identical" ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-model-flax-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( a , repo_id="valid_org/test-model-flax-org" , push_to_hub=a , use_auth_token=self._token ) SCREAMING_SNAKE_CASE : Tuple = FlaxBertModel.from_pretrained("valid_org/test-model-flax-org" ) SCREAMING_SNAKE_CASE : Optional[int] = flatten_dict(unfreeze(model.params ) ) SCREAMING_SNAKE_CASE : str = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): SCREAMING_SNAKE_CASE : Optional[int] = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(a , 1e-3 , msg=F"{key} not identical" ) def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Optional[Any] = True SCREAMING_SNAKE_CASE : Union[str, Any] = flatten_dict(modela.params) SCREAMING_SNAKE_CASE : Optional[int] = flatten_dict(modela.params) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key])) > 1E-4: SCREAMING_SNAKE_CASE : Any = False return models_are_equal @require_flax class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : str = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) SCREAMING_SNAKE_CASE : List[Any] = FlaxBertModel(a ) SCREAMING_SNAKE_CASE : Optional[int] = "bert" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(a , a ) ) with self.assertRaises(a ): SCREAMING_SNAKE_CASE : Tuple = FlaxBertModel.from_pretrained(a ) SCREAMING_SNAKE_CASE : int = FlaxBertModel.from_pretrained(a , subfolder=a ) self.assertTrue(check_models_equal(a , a ) ) def __UpperCamelCase ( self : int ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Any = BertConfig.from_pretrained("hf-internal-testing/tiny-bert-flax-only" ) SCREAMING_SNAKE_CASE : Dict = FlaxBertModel(a ) SCREAMING_SNAKE_CASE : Tuple = "bert" with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(a , a ) , max_shard_size="10KB" ) with self.assertRaises(a ): SCREAMING_SNAKE_CASE : List[Any] = FlaxBertModel.from_pretrained(a ) SCREAMING_SNAKE_CASE : List[Any] = FlaxBertModel.from_pretrained(a , subfolder=a ) self.assertTrue(check_models_equal(a , a ) ) def __UpperCamelCase ( self : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : str = "bert" SCREAMING_SNAKE_CASE : Optional[Any] = "hf-internal-testing/tiny-random-bert-subfolder" with self.assertRaises(a ): SCREAMING_SNAKE_CASE : str = FlaxBertModel.from_pretrained(a ) SCREAMING_SNAKE_CASE : int = FlaxBertModel.from_pretrained(a , subfolder=a ) self.assertIsNotNone(a ) def __UpperCamelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = "bert" SCREAMING_SNAKE_CASE : Optional[int] = "hf-internal-testing/tiny-random-bert-sharded-subfolder" with self.assertRaises(a ): SCREAMING_SNAKE_CASE : Union[str, Any] = FlaxBertModel.from_pretrained(a ) SCREAMING_SNAKE_CASE : Optional[int] = FlaxBertModel.from_pretrained(a , subfolder=a ) self.assertIsNotNone(a )
76
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCamelCase__ ( _a , _a): # Load checkpoint SCREAMING_SNAKE_CASE : int = torch.load(_a , map_location="cpu") SCREAMING_SNAKE_CASE : Dict = chkpt["model"] # We have the base model one level deeper than the original XLM repository SCREAMING_SNAKE_CASE : Optional[int] = {} for k, v in state_dict.items(): if "pred_layer" in k: SCREAMING_SNAKE_CASE : List[str] = v else: SCREAMING_SNAKE_CASE : int = v SCREAMING_SNAKE_CASE : int = chkpt["params"] SCREAMING_SNAKE_CASE : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(_a , (torch.FloatTensor, numpy.ndarray))} SCREAMING_SNAKE_CASE : List[Any] = chkpt["dico_word2id"] SCREAMING_SNAKE_CASE : List[Any] = {s + "</w>" if s.find("@@") == -1 and i > 13 else s.replace("@@" , ""): i for s, i in vocab.items()} # Save pytorch-model SCREAMING_SNAKE_CASE : Tuple = pytorch_dump_folder_path + "/" + WEIGHTS_NAME SCREAMING_SNAKE_CASE : Any = pytorch_dump_folder_path + "/" + CONFIG_NAME SCREAMING_SNAKE_CASE : Optional[int] = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["vocab_file"] print(f"Save PyTorch model to {pytorch_weights_dump_path}") torch.save(_a , _a) print(f"Save configuration file to {pytorch_config_dump_path}") with open(_a , "w" , encoding="utf-8") as f: f.write(json.dumps(_a , indent=2) + "\n") print(f"Save vocab file to {pytorch_config_dump_path}") with open(_a , "w" , encoding="utf-8") as f: f.write(json.dumps(_a , indent=2) + "\n") if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xlm_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) a_ = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
76
1
import numpy as np from PIL import Image def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : str = np.array(_a) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : Optional[Any] = 0 SCREAMING_SNAKE_CASE : Any = 0 # compute the shape of the output matrix SCREAMING_SNAKE_CASE : str = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape maxpool_shape SCREAMING_SNAKE_CASE : Any = np.zeros((maxpool_shape, maxpool_shape)) while i < arr.shape[0]: if i + size > arr.shape[0]: # if the end of the matrix is reached, break break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the maximum of the pooling matrix SCREAMING_SNAKE_CASE : Any = np.max(arr[i : i + size, j : j + size]) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 SCREAMING_SNAKE_CASE : List[Any] = 0 SCREAMING_SNAKE_CASE : List[str] = 0 return updated_arr def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : Any = np.array(_a) if arr.shape[0] != arr.shape[1]: raise ValueError("The input array is not a square matrix") SCREAMING_SNAKE_CASE : Optional[int] = 0 SCREAMING_SNAKE_CASE : int = 0 SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : int = 0 # compute the shape of the output matrix SCREAMING_SNAKE_CASE : Any = (arr.shape[0] - size) // stride + 1 # initialize the output matrix with zeros of shape avgpool_shape SCREAMING_SNAKE_CASE : List[Any] = np.zeros((avgpool_shape, avgpool_shape)) while i < arr.shape[0]: # if the end of the matrix is reached, break if i + size > arr.shape[0]: break while j < arr.shape[1]: # if the end of the matrix is reached, break if j + size > arr.shape[1]: break # compute the average of the pooling matrix SCREAMING_SNAKE_CASE : Tuple = int(np.average(arr[i : i + size, j : j + size])) # shift the pooling matrix by stride of column pixels j += stride mat_j += 1 # shift the pooling matrix by stride of row pixels i += stride mat_i += 1 # reset the column index to 0 SCREAMING_SNAKE_CASE : Tuple = 0 SCREAMING_SNAKE_CASE : Optional[Any] = 0 return updated_arr # Main Function if __name__ == "__main__": from doctest import testmod testmod(name='avgpooling', verbose=True) # Loading the image a_ = Image.open('path_to_image') # Converting the image to numpy array and maxpooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show() # Converting the image to numpy array and averagepooling, displaying the result # Ensure that the image is a square matrix Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
76
def lowerCamelCase__ ( _a , _a): _validate_point(_a) _validate_point(_a) if len(_a) != len(_a): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(a - b) for a, b in zip(_a , _a))) def lowerCamelCase__ ( _a): if point: if isinstance(_a , _a): for item in point: if not isinstance(_a , (int, float)): SCREAMING_SNAKE_CASE : List[Any] = ( "Expected a list of numbers as input, found " f"{type(_a).__name__}" ) raise TypeError(_a) else: SCREAMING_SNAKE_CASE : List[Any] = f"Expected a list of numbers as input, found {type(_a).__name__}" raise TypeError(_a) else: raise ValueError("Missing an input") def lowerCamelCase__ ( _a , _a): _validate_point(_a) _validate_point(_a) if len(_a) != len(_a): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(x - y) for x, y in zip(_a , _a))) if __name__ == "__main__": import doctest doctest.testmod()
76
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) a_ = {'processing_layoutxlm': ['LayoutXLMProcessor']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['LayoutXLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['LayoutXLMTokenizerFast'] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ ='vit_msn' def __init__( self : str , a : Tuple=768 , a : Tuple=12 , a : Any=12 , a : int=3072 , a : List[Any]="gelu" , a : Dict=0.0 , a : int=0.0 , a : str=0.02 , a : List[str]=1e-06 , a : List[Any]=224 , a : Union[str, Any]=16 , a : Union[str, Any]=3 , a : Tuple=True , **a : Dict , ) -> List[Any]: """simple docstring""" super().__init__(**a ) SCREAMING_SNAKE_CASE : Dict = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = initializer_range SCREAMING_SNAKE_CASE : int = layer_norm_eps SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : Tuple = patch_size SCREAMING_SNAKE_CASE : Optional[int] = num_channels SCREAMING_SNAKE_CASE : List[str] = qkv_bias
76
1
from __future__ import annotations import os import tempfile import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import is_tensorflow_text_available, is_tf_available from transformers.testing_utils import require_tensorflow_text, require_tf, slow from ..test_modeling_tf_common import floats_tensor from .test_framework_agnostic import GenerationIntegrationTestsMixin if is_tf_available(): import tensorflow as tf from transformers import ( AutoTokenizer, TFAutoModelForCausalLM, TFAutoModelForSeqaSeqLM, TFAutoModelForSpeechSeqaSeq, TFAutoModelForVisionaSeq, TFBartForConditionalGeneration, TFLogitsProcessorList, TFMinLengthLogitsProcessor, tf_top_k_top_p_filtering, ) if is_tensorflow_text_available(): import tensorflow_text as text @require_tf class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = tf.convert_to_tensor( [ [ 8.222_0991, # 3rd highest value; idx. 0 -0.562_0044, 5.2322_9752, 4.038_6393, -6.879_8378, -0.5478_5802, -3.201_2153, 2.9277_7176, 1.8817_1953, 7.3534_1276, # 5th highest value; idx. 9 8.4320_7833, # 2nd highest value; idx. 10 -9.8571_1836, -5.9620_9236, -1.1303_9161, -7.111_5294, -0.836_9633, -5.318_6408, 7.0642_7407, 0.8136_9344, -0.8202_3817, -5.917_9796, 0.5881_3443, -6.9977_8438, 4.7155_1189, -0.1877_1637, 7.4402_0759, # 4th highest value; idx. 25 9.3845_0987, # 1st highest value; idx. 26 2.1266_2941, -9.3256_2038, 2.3565_2522, ], # cummulative prob of 5 highest values <= 0.6 [ 0.5842_5518, 4.5313_9238, -5.5751_0464, -6.2803_0699, -7.1952_9503, -4.0212_2551, 1.3933_7037, -6.0670_7057, 1.5948_0517, -9.64_3119, 0.0390_7799, 0.6723_1762, -8.8820_6726, 6.2711_5922, # 4th highest value; idx. 13 2.2852_0723, 4.8276_7506, 4.3042_1368, 8.827_5313, # 2nd highest value; idx. 17 5.4402_9958, # 5th highest value; idx. 18 -4.473_5794, 7.3857_9536, # 3rd highest value; idx. 20 -2.9105_1663, 2.6194_6077, -2.567_4762, -9.4895_9302, -4.0292_2645, -1.3541_6918, 9.6770_2323, # 1st highest value; idx. 27 -5.8947_8553, 1.8537_0467, ], # cummulative prob of 5 highest values <= 0.6 ] , dtype=tf.floataa , ) SCREAMING_SNAKE_CASE : Optional[Any] = tf.convert_to_tensor( [[0, 0], [0, 9], [0, 10], [0, 25], [0, 26], [1, 13], [1, 17], [1, 18], [1, 20], [1, 27]] , dtype=tf.intaa , ) # expected non filtered idx as noted above SCREAMING_SNAKE_CASE : Optional[Any] = tf.convert_to_tensor( [8.22_2099, 7.353_4126, 8.43_2078, 7.440_2075, 9.3_8451, 6.27_1159, 8.82_7531, 5.440_2995, 7.385_7956, 9.67_7023] , dtype=tf.floataa , ) # expected non filtered values as noted above SCREAMING_SNAKE_CASE : str = tf_top_k_top_p_filtering(a , top_k=10 , top_p=0.6 , min_tokens_to_keep=4 ) SCREAMING_SNAKE_CASE : Optional[Any] = output[output != -float("inf" )] SCREAMING_SNAKE_CASE : int = tf.cast( tf.where(tf.not_equal(a , tf.constant(-float("inf" ) , dtype=tf.floataa ) ) ) , dtype=tf.intaa , ) tf.debugging.assert_near(a , a , rtol=1e-12 ) tf.debugging.assert_equal(a , a ) @require_tf class _UpperCamelCase ( unittest.TestCase , __A ): '''simple docstring''' if is_tf_available(): lowerCamelCase__ ={ 'AutoModelForCausalLM': TFAutoModelForCausalLM, 'AutoModelForSpeechSeq2Seq': TFAutoModelForSpeechSeqaSeq, 'AutoModelForSeq2SeqLM': TFAutoModelForSeqaSeqLM, 'AutoModelForVision2Seq': TFAutoModelForVisionaSeq, 'LogitsProcessorList': TFLogitsProcessorList, 'MinLengthLogitsProcessor': TFMinLengthLogitsProcessor, 'create_tensor_fn': tf.convert_to_tensor, 'floats_tensor': floats_tensor, 'return_tensors': 'tf', } @slow def __UpperCamelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : Optional[Any] = 2 SCREAMING_SNAKE_CASE : Optional[Any] = 2 class _UpperCamelCase ( tf.Module ): '''simple docstring''' def __init__( self : Dict , a : int ) -> Tuple: """simple docstring""" super(a , self ).__init__() SCREAMING_SNAKE_CASE : List[str] = model @tf.function( input_signature=( tf.TensorSpec((None, input_length) , tf.intaa , name="input_ids" ), tf.TensorSpec((None, input_length) , tf.intaa , name="attention_mask" ), ) , jit_compile=a , ) def __UpperCamelCase ( self : int , a : Optional[Any] , a : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : int = self.model.generate( input_ids=a , attention_mask=a , max_new_tokens=a , return_dict_in_generate=a , ) return {"sequences": outputs["sequences"]} SCREAMING_SNAKE_CASE : Union[str, Any] = [[2, 0], [102, 103]] SCREAMING_SNAKE_CASE : str = [[1, 0], [1, 1]] SCREAMING_SNAKE_CASE : Dict = DummyModel(model=a ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(a , a , signatures={"serving_default": dummy_model.serving} ) SCREAMING_SNAKE_CASE : Any = tf.saved_model.load(a ).signatures["serving_default"] for batch_size in range(1 , len(a ) + 1 ): SCREAMING_SNAKE_CASE : str = { "input_ids": tf.constant(dummy_input_ids[:batch_size] ), "attention_mask": tf.constant(dummy_attention_masks[:batch_size] ), } SCREAMING_SNAKE_CASE : Any = serving_func(**a )["sequences"] SCREAMING_SNAKE_CASE : Optional[int] = test_model.generate(**a , max_new_tokens=a ) tf.debugging.assert_equal(a , a ) @slow def __UpperCamelCase ( self : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Any = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : List[Any] = 1 SCREAMING_SNAKE_CASE : List[Any] = 2 class _UpperCamelCase ( tf.Module ): '''simple docstring''' def __init__( self : List[str] , a : Any ) -> List[str]: """simple docstring""" super(a , self ).__init__() SCREAMING_SNAKE_CASE : Dict = model @tf.function( input_signature=( tf.TensorSpec((batch_size, None) , tf.intaa , name="input_ids" ), tf.TensorSpec((batch_size, None) , tf.intaa , name="attention_mask" ), ) , jit_compile=a , ) def __UpperCamelCase ( self : Optional[int] , a : int , a : List[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = self.model.generate( input_ids=a , attention_mask=a , max_new_tokens=a , return_dict_in_generate=a , ) return {"sequences": outputs["sequences"]} SCREAMING_SNAKE_CASE : Tuple = [[2], [102, 103]] SCREAMING_SNAKE_CASE : Optional[Any] = [[1], [1, 1]] SCREAMING_SNAKE_CASE : int = DummyModel(model=a ) with tempfile.TemporaryDirectory() as tmp_dir: tf.saved_model.save(a , a , signatures={"serving_default": dummy_model.serving} ) SCREAMING_SNAKE_CASE : int = tf.saved_model.load(a ).signatures["serving_default"] for input_row in range(len(a ) ): SCREAMING_SNAKE_CASE : Union[str, Any] = { "input_ids": tf.constant([dummy_input_ids[input_row]] ), "attention_mask": tf.constant([dummy_attention_masks[input_row]] ), } SCREAMING_SNAKE_CASE : Any = serving_func(**a )["sequences"] SCREAMING_SNAKE_CASE : int = test_model.generate(**a , max_new_tokens=a ) tf.debugging.assert_equal(a , a ) @slow @require_tensorflow_text def __UpperCamelCase ( self : List[str] ) -> List[str]: """simple docstring""" with tempfile.TemporaryDirectory() as tmp_dir: # file needed to load the TF tokenizer hf_hub_download(repo_id="google/flan-t5-small" , filename="spiece.model" , local_dir=a ) class _UpperCamelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Optional[int] ) -> List[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : str = text.SentencepieceTokenizer( model=tf.io.gfile.GFile(os.path.join(a , "spiece.model" ) , "rb" ).read() ) SCREAMING_SNAKE_CASE : Dict = TFAutoModelForSeqaSeqLM.from_pretrained("hf-internal-testing/tiny-random-t5" ) def __UpperCamelCase ( self : int , a : Dict , *a : str , **a : Optional[Any] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.tokenizer.tokenize(a ) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = text.pad_model_inputs( a , max_seq_length=64 , pad_value=self.model.config.pad_token_id ) SCREAMING_SNAKE_CASE : Optional[int] = self.model.generate(input_ids=a , attention_mask=a ) return self.tokenizer.detokenize(a ) SCREAMING_SNAKE_CASE : List[str] = CompleteSentenceTransformer() SCREAMING_SNAKE_CASE : Dict = tf.keras.layers.Input(shape=(1,) , dtype=tf.string , name="inputs" ) SCREAMING_SNAKE_CASE : Any = complete_model(a ) SCREAMING_SNAKE_CASE : List[str] = tf.keras.Model(a , a ) keras_model.save(a ) def __UpperCamelCase ( self : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : str = { "do_sample": True, "num_beams": 1, "top_p": 0.7, "top_k": 10, "temperature": 0.7, } SCREAMING_SNAKE_CASE : Tuple = 14 SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : Optional[int] = "Hello, my dog is cute and" SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer(a , return_tensors="tf" ) SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2" ) SCREAMING_SNAKE_CASE : int = 638 # forces the generation to happen on CPU, to avoid GPU-related quirks with tf.device(":/CPU:0" ): tf.random.set_seed(0 ) SCREAMING_SNAKE_CASE : str = model.generate(**a , eos_token_id=a , **a ) self.assertTrue(expectation == len(generated_tokens[0] ) ) SCREAMING_SNAKE_CASE : Dict = [638, 198] with tf.device(":/CPU:0" ): tf.random.set_seed(0 ) SCREAMING_SNAKE_CASE : List[str] = model.generate(**a , eos_token_id=a , **a ) self.assertTrue(expectation == len(generated_tokens[0] ) ) def __UpperCamelCase ( self : Tuple ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE : Any = "Hugging Face is a technology company based in New York and Paris." SCREAMING_SNAKE_CASE : List[str] = bart_tokenizer(a , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE : List[str] = TFBartForConditionalGeneration.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE : int = bart_model.generate(a ).numpy() class _UpperCamelCase ( __A ): '''simple docstring''' def __UpperCamelCase ( self : str , a : Dict , a : Dict=None , **a : Optional[Any] ) -> int: """simple docstring""" return super().call(a , **a ) SCREAMING_SNAKE_CASE : Tuple = FakeBart.from_pretrained("hf-internal-testing/tiny-random-bart" ) SCREAMING_SNAKE_CASE : List[str] = bart_model.generate(a , foo="bar" ).numpy() self.assertTrue(np.array_equal(a , a ) ) class _UpperCamelCase ( bart_model.model.encoder.__class__ ): '''simple docstring''' def __UpperCamelCase ( self : int , a : Optional[Any] , **a : Dict ) -> Tuple: """simple docstring""" return super().call(a , **a ) SCREAMING_SNAKE_CASE : int = FakeEncoder(bart_model.config , bart_model.model.shared ) SCREAMING_SNAKE_CASE : Tuple = fake_encoder # Normal generation still works (the output will be different because the encoder weights are different) SCREAMING_SNAKE_CASE : str = bart_model.generate(a ).numpy() with self.assertRaises(a ): # FakeEncoder.call() accepts **kwargs -> no filtering -> value error due to unexpected input "foo" bart_model.generate(a , foo="bar" )
76
import baseaa def lowerCamelCase__ ( _a): return baseaa.aaaencode(string.encode("utf-8")) def lowerCamelCase__ ( _a): return baseaa.aaadecode(_a).decode("utf-8") if __name__ == "__main__": import doctest doctest.testmod()
76
1
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'spiece.model'} a_ = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } a_ = { 'AI-Sweden/gpt-sw3-126m': 2048, 'AI-Sweden/gpt-sw3-350m': 2048, 'AI-Sweden/gpt-sw3-1.6b': 2048, 'AI-Sweden/gpt-sw3-6.7b': 2048, 'AI-Sweden/gpt-sw3-20b': 2048, } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =VOCAB_FILES_NAMES lowerCamelCase__ =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ =['input_ids', 'attention_mask'] def __init__( self : Optional[Any] , a : Optional[int] , a : List[Any]=False , a : Union[str, Any]=False , a : List[str]=False , a : List[Any]=None , a : Dict=None , a : Any=None , a : Union[str, Any]=None , a : Optional[Dict[str, Any]] = None , **a : Any , ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : Any = {} if sp_model_kwargs is None else sp_model_kwargs SCREAMING_SNAKE_CASE : Union[str, Any] = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) SCREAMING_SNAKE_CASE : Optional[int] = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing SCREAMING_SNAKE_CASE : Tuple = "<|endoftext|>" if eos_token is None else eos_token SCREAMING_SNAKE_CASE : Dict = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: SCREAMING_SNAKE_CASE : Optional[int] = unk_token if pad_token is None else pad_token SCREAMING_SNAKE_CASE : str = eos_token if bos_token is None else bos_token else: SCREAMING_SNAKE_CASE : Dict = "<pad>" if pad_token is None else pad_token SCREAMING_SNAKE_CASE : int = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=a , remove_space=a , keep_accents=a , bos_token=a , eos_token=a , unk_token=a , pad_token=a , sp_model_kwargs=self.sp_model_kwargs , **a , ) SCREAMING_SNAKE_CASE : Any = do_lower_case SCREAMING_SNAKE_CASE : Optional[Any] = remove_space SCREAMING_SNAKE_CASE : Optional[Any] = keep_accents SCREAMING_SNAKE_CASE : List[Any] = vocab_file SCREAMING_SNAKE_CASE : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(a ) # Used for whitespace normalization in input texts # fmt : off SCREAMING_SNAKE_CASE : str = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing SCREAMING_SNAKE_CASE : Optional[int] = re.compile( F"[{''.join(map(a , list(range(0 , 9 ) ) + list(range(11 , 32 ) ) + list(range(127 , 160 ) ) + [160, 173, 8203] ) )}]" ) def __getstate__( self : List[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.__dict__.copy() SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self : Optional[int] , a : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : str = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): SCREAMING_SNAKE_CASE : Any = {} SCREAMING_SNAKE_CASE : Optional[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def __UpperCamelCase ( self : Any ) -> int: """simple docstring""" return len(self.sp_model ) def __UpperCamelCase ( self : List[Any] , a : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : str = self.non_printing_characters_re.sub("" , a ) # Normalize whitespaces SCREAMING_SNAKE_CASE : Dict = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization SCREAMING_SNAKE_CASE : Tuple = unicodedata.normalize("NFC" , a ) return text def __UpperCamelCase ( self : Union[str, Any] , a : str , **a : List[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : str = self.preprocess_text(a ) return self.sp_model.encode(a , out_type=a ) def __UpperCamelCase ( self : Optional[int] , a : str ) -> int: """simple docstring""" return self.sp_model.PieceToId(a ) def __UpperCamelCase ( self : str , a : int ) -> str: """simple docstring""" return self.sp_model.IdToPiece(a ) @staticmethod def __UpperCamelCase ( a : str ) -> str: """simple docstring""" return out_string def __UpperCamelCase ( self : Tuple , a : List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : Any = "" SCREAMING_SNAKE_CASE : int = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(a ) + token SCREAMING_SNAKE_CASE : int = True SCREAMING_SNAKE_CASE : Dict = [] else: current_sub_tokens.append(a ) SCREAMING_SNAKE_CASE : List[Any] = False out_string += self.sp_model.decode(a ) return out_string def __UpperCamelCase ( self : int ) -> Dict[str, int]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = {self.convert_ids_to_tokens(a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __UpperCamelCase ( self : Union[str, Any] , a : str , a : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(a ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return SCREAMING_SNAKE_CASE : List[Any] = os.path.join( a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , a ) elif not os.path.isfile(self.vocab_file ): with open(a , "wb" ) as fi: SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.serialized_model_proto() fi.write(a ) return (out_vocab_file,) def __UpperCamelCase ( self : Union[str, Any] , a : Union[str, List[str]] , a : Union[str, bool] = False ) -> Union[List[int], List[List[int]], "torch.Tensor"]: """simple docstring""" if isinstance(a , a ): SCREAMING_SNAKE_CASE : List[str] = self.preprocess_text(a ) SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(a ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = [self.preprocess_text(a ) for t in text] SCREAMING_SNAKE_CASE : List[str] = self.sp_model.encode(a ) if return_tensors is True or return_tensors == "pt": SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(a ) return token_ids def __UpperCamelCase ( self : Tuple , a : Union[int, List[int]] ) -> str: """simple docstring""" return self.sp_model.decode(a ) def __UpperCamelCase ( self : List[str] , a : "Conversation" ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE : str = [F"User: {text}" if is_user else F"Bot: {text}" for is_user, text in conversation.iter_texts()] SCREAMING_SNAKE_CASE : List[str] = ( F"{self.eos_token}{self.bos_token}" + F"{self.bos_token}".join(a ) + F"{self.bos_token}Bot:" ) return self.encode(text=a )
76
from datetime import datetime as dt import os from github import Github a_ = [ 'good first issue', 'good second issue', 'good difficult issue', 'feature request', 'new model', 'wip', ] def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : int = Github(os.environ["GITHUB_TOKEN"]) SCREAMING_SNAKE_CASE : List[str] = g.get_repo("huggingface/transformers") SCREAMING_SNAKE_CASE : Optional[int] = repo.get_issues(state="open") for issue in open_issues: SCREAMING_SNAKE_CASE : List[Any] = sorted([comment for comment in issue.get_comments()] , key=lambda _a: i.created_at , reverse=_a) SCREAMING_SNAKE_CASE : str = comments[0] if len(_a) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state="closed") elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( "This issue has been automatically marked as stale because it has not had " "recent activity. If you think this still needs to be addressed " "please comment on this thread.\n\nPlease note that issues that do not follow the " "[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) " "are likely to be ignored.") if __name__ == "__main__": main()
76
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 _UpperCamelCase ( __A ): '''simple docstring''' def __init__( self : int , a : List[Any] , a : List[Any]=13 , a : int=7 , a : Optional[Any]=True , a : Optional[int]=True , a : str=True , a : List[Any]=True , a : List[Any]=True , a : List[str]=False , a : Any=False , a : Optional[int]=False , a : Tuple=2 , a : Any=99 , a : List[str]=0 , a : Any=32 , a : Tuple=5 , a : Any=4 , a : Union[str, Any]=0.1 , a : str=0.1 , a : Optional[int]=512 , a : Optional[int]=12 , a : List[Any]=2 , a : List[str]=0.02 , a : Any=3 , a : Optional[int]=4 , a : Optional[int]="last" , a : Optional[int]=None , a : int=None , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : Tuple = batch_size SCREAMING_SNAKE_CASE : Any = seq_length SCREAMING_SNAKE_CASE : int = is_training SCREAMING_SNAKE_CASE : Any = use_input_lengths SCREAMING_SNAKE_CASE : List[Any] = use_token_type_ids SCREAMING_SNAKE_CASE : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE : List[str] = gelu_activation SCREAMING_SNAKE_CASE : Dict = sinusoidal_embeddings SCREAMING_SNAKE_CASE : List[Any] = causal SCREAMING_SNAKE_CASE : Optional[int] = asm SCREAMING_SNAKE_CASE : Dict = n_langs SCREAMING_SNAKE_CASE : Tuple = vocab_size SCREAMING_SNAKE_CASE : List[Any] = n_special SCREAMING_SNAKE_CASE : Optional[int] = hidden_size SCREAMING_SNAKE_CASE : Dict = num_hidden_layers SCREAMING_SNAKE_CASE : Any = num_attention_heads SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE : List[str] = type_vocab_size SCREAMING_SNAKE_CASE : Optional[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : str = initializer_range SCREAMING_SNAKE_CASE : Tuple = num_labels SCREAMING_SNAKE_CASE : Tuple = num_choices SCREAMING_SNAKE_CASE : str = summary_type SCREAMING_SNAKE_CASE : Tuple = use_proj SCREAMING_SNAKE_CASE : Tuple = scope def __UpperCamelCase ( self : Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Dict = None if self.use_input_lengths: SCREAMING_SNAKE_CASE : List[Any] = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length SCREAMING_SNAKE_CASE : List[str] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) SCREAMING_SNAKE_CASE : Optional[Any] = None SCREAMING_SNAKE_CASE : int = None SCREAMING_SNAKE_CASE : Tuple = None if self.use_labels: SCREAMING_SNAKE_CASE : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : str = 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 : Dict = 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 __UpperCamelCase ( self : Optional[Any] ) -> Tuple: """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 __UpperCamelCase ( self : int , a : List[str] , a : List[str] , a : str , a : Any , a : Any , a : Optional[Any] , a : List[str] , a : Union[str, Any] , a : Union[str, Any] , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = FlaubertModel(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Optional[int] = model(a , lengths=a , langs=a ) SCREAMING_SNAKE_CASE : str = model(a , langs=a ) SCREAMING_SNAKE_CASE : Optional[Any] = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __UpperCamelCase ( self : Tuple , a : List[Any] , a : List[str] , a : Tuple , a : Dict , a : Any , a : List[Any] , a : List[Any] , a : List[str] , a : str , ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = FlaubertWithLMHeadModel(a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : List[Any] = 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 __UpperCamelCase ( self : Optional[int] , a : Tuple , a : Optional[Any] , a : str , a : int , a : Any , a : Dict , a : Any , a : Optional[Any] , a : Any , ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : int = FlaubertForQuestionAnsweringSimple(a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(a ) SCREAMING_SNAKE_CASE : int = 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 __UpperCamelCase ( self : Optional[Any] , a : Any , a : Dict , a : Tuple , a : Dict , a : str , a : List[Any] , a : Optional[int] , a : Union[str, Any] , a : Dict , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = FlaubertForQuestionAnswering(a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(a ) SCREAMING_SNAKE_CASE : List[str] = model( a , start_positions=a , end_positions=a , cls_index=a , is_impossible=a , p_mask=a , ) SCREAMING_SNAKE_CASE : Tuple = model( a , start_positions=a , end_positions=a , cls_index=a , is_impossible=a , ) ((SCREAMING_SNAKE_CASE) ,) : int = result_with_labels.to_tuple() SCREAMING_SNAKE_CASE : List[str] = model(a , start_positions=a , end_positions=a ) ((SCREAMING_SNAKE_CASE) ,) : Union[str, Any] = 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 __UpperCamelCase ( self : int , a : Optional[Any] , a : Any , a : Union[str, Any] , a : Optional[int] , a : str , a : Dict , a : Optional[Any] , a : List[str] , a : Union[str, Any] , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = FlaubertForSequenceClassification(a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Tuple = model(a ) SCREAMING_SNAKE_CASE : Optional[int] = 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 __UpperCamelCase ( self : Dict , a : Tuple , a : str , a : int , a : List[Any] , a : Dict , a : List[str] , a : Any , a : str , a : List[Any] , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.num_labels SCREAMING_SNAKE_CASE : List[Any] = FlaubertForTokenClassification(a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : Any = model(a , attention_mask=a , labels=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __UpperCamelCase ( self : Any , a : List[Any] , a : List[str] , a : Optional[Any] , a : Dict , a : str , a : Tuple , a : str , a : Tuple , a : Union[str, Any] , ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.num_choices SCREAMING_SNAKE_CASE : Any = FlaubertForMultipleChoice(config=a ) model.to(a ) model.eval() SCREAMING_SNAKE_CASE : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : str = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : Optional[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE : List[Any] = model( a , attention_mask=a , token_type_ids=a , labels=a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __UpperCamelCase ( self : str ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = 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 ) , ) : Any = config_and_inputs SCREAMING_SNAKE_CASE : Union[str, Any] = { "input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths, "attention_mask": input_mask, } return config, inputs_dict @require_torch class _UpperCamelCase ( __A , __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =( ( FlaubertModel, FlaubertWithLMHeadModel, FlaubertForQuestionAnswering, FlaubertForQuestionAnsweringSimple, FlaubertForSequenceClassification, FlaubertForTokenClassification, FlaubertForMultipleChoice, ) if is_torch_available() else () ) lowerCamelCase__ =( { 'feature-extraction': FlaubertModel, 'fill-mask': FlaubertWithLMHeadModel, 'question-answering': FlaubertForQuestionAnsweringSimple, 'text-classification': FlaubertForSequenceClassification, 'token-classification': FlaubertForTokenClassification, 'zero-shot': FlaubertForSequenceClassification, } if is_torch_available() else {} ) def __UpperCamelCase ( self : List[str] , a : Optional[Any] , a : Any , a : Optional[Any] , a : int , a : Optional[int] ) -> str: """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 __UpperCamelCase ( self : Any , a : Any , a : List[str] , a : int=False ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = super()._prepare_for_class(a , a , return_labels=a ) if return_labels: if model_class.__name__ == "FlaubertForQuestionAnswering": SCREAMING_SNAKE_CASE : Optional[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a ) SCREAMING_SNAKE_CASE : Dict = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a ) return inputs_dict def __UpperCamelCase ( self : Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = FlaubertModelTester(self ) SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=a , emb_dim=37 ) def __UpperCamelCase ( self : Tuple ) -> Dict: """simple docstring""" self.config_tester.run_common_tests() def __UpperCamelCase ( self : Tuple ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*a ) def __UpperCamelCase ( self : Union[str, Any] ) -> Union[str, Any]: """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 __UpperCamelCase ( self : Optional[int] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_simple_qa(*a ) def __UpperCamelCase ( self : int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*a ) def __UpperCamelCase ( self : List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*a ) def __UpperCamelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_token_classif(*a ) def __UpperCamelCase ( self : int ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_multiple_choice(*a ) @slow def __UpperCamelCase ( self : Dict ) -> str: """simple docstring""" for model_name in FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE : Dict = FlaubertModel.from_pretrained(a ) self.assertIsNotNone(a ) @slow @require_torch_gpu def __UpperCamelCase ( self : str ) -> Union[str, Any]: """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: # FlauBertForMultipleChoice behaves incorrectly in JIT environments. if model_class == FlaubertForMultipleChoice: return SCREAMING_SNAKE_CASE : Optional[int] = True SCREAMING_SNAKE_CASE : List[str] = model_class(config=a ) SCREAMING_SNAKE_CASE : Optional[int] = self._prepare_for_class(a , a ) SCREAMING_SNAKE_CASE : int = 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 : str = 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 _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = FlaubertModel.from_pretrained("flaubert/flaubert_base_cased" ) SCREAMING_SNAKE_CASE : Tuple = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE : List[str] = model(a )[0] SCREAMING_SNAKE_CASE : int = 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 ) )
76
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): if isinstance(_a , (list, tuple)) and isinstance(videos[0] , (list, tuple)) and is_valid_image(videos[0][0]): return videos elif isinstance(_a , (list, tuple)) and is_valid_image(videos[0]): return [videos] elif is_valid_image(_a): return [[videos]] raise ValueError(f"Could not make batched video from {videos}") class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =['pixel_values'] def __init__( self : Optional[Any] , a : bool = True , a : Dict[str, int] = None , a : PILImageResampling = PILImageResampling.BILINEAR , a : bool = True , a : Dict[str, int] = None , a : bool = True , a : Union[int, float] = 1 / 255 , a : bool = True , a : bool = True , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , **a : Tuple , ) -> None: """simple docstring""" super().__init__(**a ) SCREAMING_SNAKE_CASE : Tuple = size if size is not None else {"shortest_edge": 256} SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE : str = get_size_dict(a , param_name="crop_size" ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : Optional[int] = do_center_crop SCREAMING_SNAKE_CASE : int = crop_size SCREAMING_SNAKE_CASE : int = resample SCREAMING_SNAKE_CASE : Any = do_rescale SCREAMING_SNAKE_CASE : int = rescale_factor SCREAMING_SNAKE_CASE : Tuple = offset SCREAMING_SNAKE_CASE : str = do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def __UpperCamelCase ( self : Optional[Any] , a : np.ndarray , a : Dict[str, int] , a : PILImageResampling = PILImageResampling.BILINEAR , a : Optional[Union[str, ChannelDimension]] = None , **a : Union[str, Any] , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) if "shortest_edge" in size: SCREAMING_SNAKE_CASE : str = get_resize_output_image_size(a , size["shortest_edge"] , default_to_square=a ) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE : Dict = (size["height"], size["width"]) else: raise ValueError(F"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a , size=a , resample=a , data_format=a , **a ) def __UpperCamelCase ( self : List[str] , a : np.ndarray , a : Dict[str, int] , a : Optional[Union[str, ChannelDimension]] = None , **a : str , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : str = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(F"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __UpperCamelCase ( self : List[Any] , a : np.ndarray , a : Union[int, float] , a : bool = True , a : Optional[Union[str, ChannelDimension]] = None , **a : Tuple , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = image.astype(np.floataa ) if offset: SCREAMING_SNAKE_CASE : Union[str, Any] = image - (scale / 2) return rescale(a , scale=a , data_format=a , **a ) def __UpperCamelCase ( self : int , a : np.ndarray , a : Union[float, List[float]] , a : Union[float, List[float]] , a : Optional[Union[str, ChannelDimension]] = None , **a : List[str] , ) -> np.ndarray: """simple docstring""" return normalize(a , mean=a , std=a , data_format=a , **a ) def __UpperCamelCase ( self : Tuple , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray: """simple docstring""" if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) if offset and not do_rescale: raise ValueError("For offset, do_rescale must also be set to True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : List[str] = to_numpy_array(a ) if do_resize: SCREAMING_SNAKE_CASE : Optional[Any] = self.resize(image=a , size=a , resample=a ) if do_center_crop: SCREAMING_SNAKE_CASE : Union[str, Any] = self.center_crop(a , size=a ) if do_rescale: SCREAMING_SNAKE_CASE : Any = self.rescale(image=a , scale=a , offset=a ) if do_normalize: SCREAMING_SNAKE_CASE : Tuple = self.normalize(image=a , mean=a , std=a ) SCREAMING_SNAKE_CASE : Optional[int] = to_channel_dimension_format(a , a ) return image def __UpperCamelCase ( self : Dict , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[str, TensorType]] = None , a : ChannelDimension = ChannelDimension.FIRST , **a : Tuple , ) -> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE : str = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Union[str, Any] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : int = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE : str = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[Any] = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Optional[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : int = size if size is not None else self.size SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : Tuple = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(a , param_name="crop_size" ) 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." ) SCREAMING_SNAKE_CASE : Optional[int] = make_batched(a ) SCREAMING_SNAKE_CASE : List[Any] = [ [ self._preprocess_image( image=a , do_resize=a , size=a , resample=a , do_center_crop=a , crop_size=a , do_rescale=a , rescale_factor=a , offset=a , do_normalize=a , image_mean=a , image_std=a , data_format=a , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE : Optional[int] = {"pixel_values": videos} return BatchFeature(data=a , tensor_type=a )
76
1
import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def lowerCamelCase__ ( _a , _a=10): SCREAMING_SNAKE_CASE : int = [] for _ in range(_a): lrs.append(scheduler.get_lr()[0]) scheduler.step() return lrs def lowerCamelCase__ ( _a , _a=10): SCREAMING_SNAKE_CASE : Dict = [] for step in range(_a): lrs.append(scheduler.get_lr()[0]) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(_a , "schedule.bin") torch.save(scheduler.state_dict() , _a) SCREAMING_SNAKE_CASE : int = torch.load(_a) scheduler.load_state_dict(_a) return lrs @require_torch class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Any , a : Any , a : int , a : List[Any] ) -> Optional[int]: """simple docstring""" self.assertEqual(len(a ) , len(a ) ) for a, b in zip(a , a ): self.assertAlmostEqual(a , a , delta=a ) def __UpperCamelCase ( self : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = torch.tensor([0.1, -0.2, -0.1] , requires_grad=a ) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([0.4, 0.2, -0.5] ) SCREAMING_SNAKE_CASE : List[str] = nn.MSELoss() # No warmup, constant schedule, no gradient clipping SCREAMING_SNAKE_CASE : Optional[int] = AdamW(params=[w] , lr=2e-1 , weight_decay=0.0 ) for _ in range(100 ): SCREAMING_SNAKE_CASE : int = criterion(a , a ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) def __UpperCamelCase ( self : List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Any = torch.tensor([0.1, -0.2, -0.1] , requires_grad=a ) SCREAMING_SNAKE_CASE : Any = torch.tensor([0.4, 0.2, -0.5] ) SCREAMING_SNAKE_CASE : Any = nn.MSELoss() # No warmup, constant schedule, no gradient clipping SCREAMING_SNAKE_CASE : str = Adafactor( params=[w] , lr=1e-2 , eps=(1e-30, 1e-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=a , weight_decay=0.0 , relative_step=a , scale_parameter=a , warmup_init=a , ) for _ in range(1000 ): SCREAMING_SNAKE_CASE : str = criterion(a , a ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1e-2 ) @require_torch class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =nn.Linear(50 , 50 ) if is_torch_available() else None lowerCamelCase__ =AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None lowerCamelCase__ =10 def __UpperCamelCase ( self : str , a : int , a : Optional[Any] , a : Optional[Any] , a : Optional[Any]=None ) -> Dict: """simple docstring""" self.assertEqual(len(a ) , len(a ) ) for a, b in zip(a , a ): self.assertAlmostEqual(a , a , delta=a , msg=a ) def __UpperCamelCase ( self : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = {"num_warmup_steps": 2, "num_training_steps": 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) SCREAMING_SNAKE_CASE : str = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {"num_warmup_steps": 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, "num_cycles": 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, "power": 2.0, "lr_end": 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {"num_warmup_steps": 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = data SCREAMING_SNAKE_CASE : Dict = scheduler_func(self.optimizer , **a ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) SCREAMING_SNAKE_CASE : int = unwrap_schedule(a , self.num_steps ) self.assertListAlmostEqual( a , a , tol=1e-2 , msg=F"failed for {scheduler_func} in normal scheduler" , ) SCREAMING_SNAKE_CASE : Union[str, Any] = scheduler_func(self.optimizer , **a ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(a ) # wrap to test picklability of the schedule SCREAMING_SNAKE_CASE : Union[str, Any] = unwrap_and_save_reload_schedule(a , self.num_steps ) self.assertListEqual(a , a , msg=F"failed for {scheduler_func} in save and reload" ) class _UpperCamelCase : '''simple docstring''' def __init__( self : Any , a : Any ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = fn def __call__( self : Any , *a : List[Any] , **a : Union[str, Any] ) -> Dict: """simple docstring""" return self.fn(*a , **a ) @classmethod def __UpperCamelCase ( self : int , a : Optional[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = list(map(self , scheduler.lr_lambdas ) )
76
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt'} a_ = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } a_ = { 'YituTech/conv-bert-base': 512, 'YituTech/conv-bert-medium-small': 512, 'YituTech/conv-bert-small': 512, } a_ = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =VOCAB_FILES_NAMES lowerCamelCase__ =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ =PRETRAINED_INIT_CONFIGURATION lowerCamelCase__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ =ConvBertTokenizer def __init__( self : List[str] , a : Union[str, Any]=None , a : Optional[int]=None , a : int=True , a : Tuple="[UNK]" , a : Dict="[SEP]" , a : Dict="[PAD]" , a : List[Any]="[CLS]" , a : Tuple="[MASK]" , a : Dict=True , a : Optional[Any]=None , **a : str , ) -> Dict: """simple docstring""" super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) SCREAMING_SNAKE_CASE : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , a ) != do_lower_case or normalizer_state.get("strip_accents" , a ) != strip_accents or normalizer_state.get("handle_chinese_chars" , a ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : List[str] = getattr(a , normalizer_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE : Any = strip_accents SCREAMING_SNAKE_CASE : Optional[int] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : List[str] = normalizer_class(**a ) SCREAMING_SNAKE_CASE : str = do_lower_case def __UpperCamelCase ( self : Union[str, Any] , a : List[Any] , a : int=None ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __UpperCamelCase ( self : Dict , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCamelCase ( self : Tuple , a : str , a : Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self._tokenizer.model.save(a , name=a ) return tuple(a )
76
1
import unittest import torch from torch import nn from diffusers.models.activations import get_activation class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = get_activation("swish" ) self.assertIsInstance(a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCamelCase ( self : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : str = get_activation("silu" ) self.assertIsInstance(a , nn.SiLU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCamelCase ( self : List[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Any = get_activation("mish" ) self.assertIsInstance(a , nn.Mish ) self.assertEqual(act(torch.tensor(-200 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 ) def __UpperCamelCase ( self : Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = get_activation("gelu" ) self.assertIsInstance(a , nn.GELU ) self.assertEqual(act(torch.tensor(-100 , dtype=torch.floataa ) ).item() , 0 ) self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa ) ).item() , 0 ) self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa ) ).item() , 20 )
76
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. a_ = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(_a) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE : Union[str, Any] = terminalreporter.config.getoption("--make-reports") if make_reports: pytest_terminal_summary_main(_a , id=_a)
76
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 lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Union[str, Any] = [] for part_id in partition_order: SCREAMING_SNAKE_CASE : int = df.where(f"SPARK_PARTITION_ID() = {part_id}").collect() for row_idx, row in enumerate(_a): 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 lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : str = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() SCREAMING_SNAKE_CASE : Dict = spark.range(100).repartition(1) SCREAMING_SNAKE_CASE : List[str] = Spark(_a) # 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 lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Optional[Any] = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() SCREAMING_SNAKE_CASE : str = spark.range(10).repartition(2) SCREAMING_SNAKE_CASE : List[str] = [1, 0] SCREAMING_SNAKE_CASE : Union[str, Any] = _generate_iterable_examples(_a , _a) # Reverse the partitions. SCREAMING_SNAKE_CASE : Optional[int] = _get_expected_row_ids_and_row_dicts_for_partition_order(_a , _a) for i, (row_id, row_dict) in enumerate(generate_fn()): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = 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 lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Optional[int] = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() SCREAMING_SNAKE_CASE : Optional[Any] = spark.range(10).repartition(1) SCREAMING_SNAKE_CASE : str = SparkExamplesIterable(_a) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(_a): assert row_id == f"0_{i}" assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Optional[Any] = 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 _a: x.reverse() SCREAMING_SNAKE_CASE : Any = _get_expected_row_ids_and_row_dicts_for_partition_order(_a , [2, 1, 0]) SCREAMING_SNAKE_CASE : Any = SparkExamplesIterable(_a).shuffle_data_sources(_a) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(_a): 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 lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : List[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(_a).shard_data_sources(worker_id=0 , num_workers=2) assert shard_it_a.n_shards == 2 SCREAMING_SNAKE_CASE : List[Any] = _get_expected_row_ids_and_row_dicts_for_partition_order(_a , [0, 2]) for i, (row_id, row_dict) in enumerate(_a): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = 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[Any] = SparkExamplesIterable(_a).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(_a , [1, 3]) for i, (row_id, row_dict) in enumerate(_a): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[Any] = 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 lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : List[Any] = pyspark.sql.SparkSession.builder.master("local[*]").appName("pyspark").getOrCreate() SCREAMING_SNAKE_CASE : Optional[Any] = spark.range(100).repartition(1) SCREAMING_SNAKE_CASE : Optional[Any] = Spark(_a) # 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() == 100
76
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , a : int , a : Optional[int]=13 , a : Optional[int]=3 , a : int=224 , a : Optional[int]=30 , a : int=400 , a : Union[str, Any]=True , a : int=None , a : Tuple=True , a : Tuple=[0.5, 0.5, 0.5] , a : Optional[int]=[0.5, 0.5, 0.5] , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = size if size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : int = num_channels SCREAMING_SNAKE_CASE : Any = image_size SCREAMING_SNAKE_CASE : Tuple = min_resolution SCREAMING_SNAKE_CASE : str = max_resolution SCREAMING_SNAKE_CASE : int = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : int = do_normalize SCREAMING_SNAKE_CASE : Tuple = image_mean SCREAMING_SNAKE_CASE : Tuple = image_std def __UpperCamelCase ( self : Any ) -> Optional[int]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =ViTImageProcessor if is_vision_available() else None def __UpperCamelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = EfficientFormerImageProcessorTester(self ) @property def __UpperCamelCase ( self : Any ) -> List[str]: """simple docstring""" return self.image_proc_tester.prepare_image_processor_dict() def __UpperCamelCase ( self : List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , "image_mean" ) ) self.assertTrue(hasattr(a , "image_std" ) ) self.assertTrue(hasattr(a , "do_normalize" ) ) self.assertTrue(hasattr(a , "do_resize" ) ) self.assertTrue(hasattr(a , "size" ) ) def __UpperCamelCase ( self : int ) -> str: """simple docstring""" pass def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : List[str] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : str = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , numpify=a ) for image in image_inputs: self.assertIsInstance(a , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Any = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , torchify=a ) for image in image_inputs: self.assertIsInstance(a , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , )
76
1
import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : str , a : List[str] , a : str=7 , a : int=3 , a : Dict=18 , a : Optional[Any]=30 , a : int=400 , a : str=True , a : Dict=None , a : str=True , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Any = size if size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE : Optional[int] = parent SCREAMING_SNAKE_CASE : Optional[int] = batch_size SCREAMING_SNAKE_CASE : Tuple = num_channels SCREAMING_SNAKE_CASE : Any = image_size SCREAMING_SNAKE_CASE : List[Any] = min_resolution SCREAMING_SNAKE_CASE : str = max_resolution SCREAMING_SNAKE_CASE : List[Any] = do_resize SCREAMING_SNAKE_CASE : Optional[Any] = size SCREAMING_SNAKE_CASE : Dict = do_normalize def __UpperCamelCase ( self : Tuple ) -> Optional[Any]: """simple docstring""" return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8866_4436_3403_3203, 0.6618_8293_6954_4983, 0.3891_7464_0178_6804], [-0.6042_5591_4688_1104, -0.0_2295_0088_6052_8469, 0.5423_7973_6900_3296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =ImageGPTImageProcessor if is_vision_available() else None def __UpperCamelCase ( self : Dict ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = ImageGPTImageProcessingTester(self ) @property def __UpperCamelCase ( self : str ) -> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __UpperCamelCase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , "clusters" ) ) self.assertTrue(hasattr(a , "do_resize" ) ) self.assertTrue(hasattr(a , "size" ) ) self.assertTrue(hasattr(a , "do_normalize" ) ) def __UpperCamelCase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 18} ) SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) def __UpperCamelCase ( self : List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE : Any = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(a , obj[key] ) ) else: self.assertEqual(obj[key] , a ) def __UpperCamelCase ( self : Optional[int] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : int = os.path.join(a , "image_processor.json" ) image_processor_first.to_json_file(a ) SCREAMING_SNAKE_CASE : Any = self.image_processing_class.from_json_file(a ).to_dict() SCREAMING_SNAKE_CASE : Optional[Any] = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(a , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , a ) def __UpperCamelCase ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(a ) SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_pretrained(a ).to_dict() SCREAMING_SNAKE_CASE : Optional[Any] = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(a , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , a ) @unittest.skip("ImageGPT requires clusters at initialization" ) def __UpperCamelCase ( self : Dict ) -> Any: """simple docstring""" pass def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : List[Any] = load_dataset("hf-internal-testing/fixtures_image_utils" , split="test") SCREAMING_SNAKE_CASE : Dict = Image.open(dataset[4]["file"]) SCREAMING_SNAKE_CASE : List[Any] = Image.open(dataset[5]["file"]) SCREAMING_SNAKE_CASE : List[Any] = [imagea, imagea] return images @require_vision @require_torch class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : Tuple ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = ImageGPTImageProcessor.from_pretrained("openai/imagegpt-small" ) SCREAMING_SNAKE_CASE : Dict = prepare_images() # test non-batched SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images[0] , return_tensors="pt" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1024) ) SCREAMING_SNAKE_CASE : Optional[Any] = [306, 191, 191] self.assertEqual(encoding.input_ids[0, :3].tolist() , a ) # test batched SCREAMING_SNAKE_CASE : Dict = image_processing(a , return_tensors="pt" ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1024) ) SCREAMING_SNAKE_CASE : Any = [303, 13, 13] self.assertEqual(encoding.input_ids[1, -3:].tolist() , a )
76
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = tokenizer(example["content"] , truncation=_a)["input_ids"] SCREAMING_SNAKE_CASE : Dict = len(example["content"]) / len(output["input_ids"]) return output a_ = HfArgumentParser(PretokenizationArguments) a_ = parser.parse_args() if args.num_workers is None: a_ = multiprocessing.cpu_count() a_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) a_ = time.time() a_ = load_dataset(args.dataset_name, split='train') print(F'''Dataset loaded in {time.time()-t_start:.2f}s''') a_ = time.time() a_ = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ 'repo_name', 'path', 'copies', 'size', 'content', 'license', 'hash', 'line_mean', 'line_max', 'alpha_frac', 'autogenerated', ], ) print(F'''Dataset tokenized in {time.time()-t_start:.2f}s''') a_ = time.time() ds.push_to_hub(args.tokenized_data_repo) print(F'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
76
1
import argparse import logging from collections import namedtuple import torch from model_bertabs import BertAbsSummarizer from models.model_builder import AbsSummarizer # The authors' implementation from transformers import BertTokenizer logging.basicConfig(level=logging.INFO) a_ = logging.getLogger(__name__) a_ = 'Hello world! cécé herlolip' a_ = namedtuple( 'BertAbsConfig', [ 'temp_dir', 'large', 'use_bert_emb', 'finetune_bert', 'encoder', 'share_emb', 'max_pos', 'enc_layers', 'enc_hidden_size', 'enc_heads', 'enc_ff_size', 'enc_dropout', 'dec_layers', 'dec_hidden_size', 'dec_heads', 'dec_ff_size', 'dec_dropout', ], ) def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Any = BertAbsConfig( temp_dir="." , finetune_bert=_a , large=_a , share_emb=_a , use_bert_emb=_a , encoder="bert" , max_pos=512 , enc_layers=6 , enc_hidden_size=512 , enc_heads=8 , enc_ff_size=512 , enc_dropout=0.2 , dec_layers=6 , dec_hidden_size=768 , dec_heads=8 , dec_ff_size=2048 , dec_dropout=0.2 , ) SCREAMING_SNAKE_CASE : List[Any] = torch.load(_a , lambda _a , _a: storage) SCREAMING_SNAKE_CASE : str = AbsSummarizer(_a , torch.device("cpu") , _a) original.eval() SCREAMING_SNAKE_CASE : Tuple = BertAbsSummarizer(_a , torch.device("cpu")) new_model.eval() # ------------------- # Convert the weights # ------------------- logging.info("convert the model") new_model.bert.load_state_dict(original.bert.state_dict()) new_model.decoder.load_state_dict(original.decoder.state_dict()) new_model.generator.load_state_dict(original.generator.state_dict()) # ---------------------------------- # Make sure the outpus are identical # ---------------------------------- logging.info("Make sure that the models' outputs are identical") SCREAMING_SNAKE_CASE : Optional[int] = BertTokenizer.from_pretrained("bert-base-uncased") # prepare the model inputs SCREAMING_SNAKE_CASE : Any = tokenizer.encode("This is sample éàalj'-.") encoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(_a))) SCREAMING_SNAKE_CASE : str = torch.tensor(_a).unsqueeze(0) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.encode("This is sample 3 éàalj'-.") decoder_input_ids.extend([tokenizer.pad_token_id] * (512 - len(_a))) SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor(_a).unsqueeze(0) # failsafe to make sure the weights reset does not affect the # loaded weights. assert torch.max(torch.abs(original.generator[0].weight - new_model.generator[0].weight)) == 0 # forward pass SCREAMING_SNAKE_CASE : Optional[int] = encoder_input_ids SCREAMING_SNAKE_CASE : Optional[int] = decoder_input_ids SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : Optional[Any] = None SCREAMING_SNAKE_CASE : Any = None SCREAMING_SNAKE_CASE : Dict = None SCREAMING_SNAKE_CASE : Union[str, 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 : List[str] = original(_a , _a , _a , _a , _a , _a , _a)[0] SCREAMING_SNAKE_CASE : List[str] = original.generator(_a) SCREAMING_SNAKE_CASE : Optional[int] = new_model( _a , _a , _a , _a , _a)[0] SCREAMING_SNAKE_CASE : List[str] = new_model.generator(_a) SCREAMING_SNAKE_CASE : Optional[int] = torch.max(torch.abs(output_converted_model - output_original_model)).item() print("Maximum absolute difference beween weights: {:.2f}".format(_a)) SCREAMING_SNAKE_CASE : Tuple = torch.max(torch.abs(output_converted_generator - output_original_generator)).item() print("Maximum absolute difference beween weights: {:.2f}".format(_a)) SCREAMING_SNAKE_CASE : Optional[int] = torch.allclose(_a , _a , atol=1E-3) if are_identical: logging.info("all weights are equal up to 1e-3") else: raise ValueError("the weights are different. The new model is likely different from the original one.") # The model has been saved with torch.save(model) and this is bound to the exact # directory structure. We save the state_dict instead. logging.info("saving the model's state dictionary") torch.save( new_model.state_dict() , "./bertabs-finetuned-cnndm-extractive-abstractive-summarization/pytorch_model.bin") if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument( '--bertabs_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.', ) a_ = parser.parse_args() convert_bertabs_checkpoints( args.bertabs_checkpoint_path, args.pytorch_dump_folder_path, )
76
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): # initialize config if "resnet-50" in model_name: SCREAMING_SNAKE_CASE : int = ResNetConfig.from_pretrained("microsoft/resnet-50") elif "resnet-101" in model_name: SCREAMING_SNAKE_CASE : int = ResNetConfig.from_pretrained("microsoft/resnet-101") else: raise ValueError("Model name should include either resnet50 or resnet101") SCREAMING_SNAKE_CASE : str = DetrConfig(use_timm_backbone=_a , backbone_config=_a) # set label attributes SCREAMING_SNAKE_CASE : List[str] = "panoptic" in model_name if is_panoptic: SCREAMING_SNAKE_CASE : Union[str, Any] = 250 else: SCREAMING_SNAKE_CASE : Union[str, Any] = 91 SCREAMING_SNAKE_CASE : str = "huggingface/label-files" SCREAMING_SNAKE_CASE : Union[str, Any] = "coco-detection-id2label.json" SCREAMING_SNAKE_CASE : Optional[Any] = json.load(open(hf_hub_download(_a , _a , repo_type="dataset") , "r")) SCREAMING_SNAKE_CASE : int = {int(_a): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : List[Any] = idalabel SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in idalabel.items()} return config, is_panoptic def lowerCamelCase__ ( _a): # here we list all keys to be renamed (original name on the left, our name on the right) SCREAMING_SNAKE_CASE : Union[str, Any] = [] # stem # fmt: off rename_keys.append(("backbone.0.body.conv1.weight", "backbone.conv_encoder.model.embedder.embedder.convolution.weight")) rename_keys.append(("backbone.0.body.bn1.weight", "backbone.conv_encoder.model.embedder.embedder.normalization.weight")) rename_keys.append(("backbone.0.body.bn1.bias", "backbone.conv_encoder.model.embedder.embedder.normalization.bias")) rename_keys.append(("backbone.0.body.bn1.running_mean", "backbone.conv_encoder.model.embedder.embedder.normalization.running_mean")) rename_keys.append(("backbone.0.body.bn1.running_var", "backbone.conv_encoder.model.embedder.embedder.normalization.running_var")) # stages for stage_idx in range(len(config.backbone_config.depths)): for layer_idx in range(config.backbone_config.depths[stage_idx]): # shortcut if layer_idx == 0: rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var", )) # 3 convs for i in range(3): rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var", )) # fmt: on for i in range(config.encoder_layers): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( f"transformer.encoder.layers.{i}.self_attn.out_proj.weight", f"encoder.layers.{i}.self_attn.out_proj.weight", )) rename_keys.append( (f"transformer.encoder.layers.{i}.self_attn.out_proj.bias", f"encoder.layers.{i}.self_attn.out_proj.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"encoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"encoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"encoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"encoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm1.weight", f"encoder.layers.{i}.self_attn_layer_norm.weight")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm1.bias", f"encoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm2.weight", f"encoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"encoder.layers.{i}.final_layer_norm.bias")) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"decoder.layers.{i}.self_attn.out_proj.weight", )) rename_keys.append( (f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"decoder.layers.{i}.self_attn.out_proj.bias")) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight", f"decoder.layers.{i}.encoder_attn.out_proj.weight", )) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias", f"decoder.layers.{i}.encoder_attn.out_proj.bias", )) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"decoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"decoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"decoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"decoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm1.weight", f"decoder.layers.{i}.self_attn_layer_norm.weight")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm1.bias", f"decoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.weight", f"decoder.layers.{i}.encoder_attn_layer_norm.weight")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.bias", f"decoder.layers.{i}.encoder_attn_layer_norm.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm3.weight", f"decoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"decoder.layers.{i}.final_layer_norm.bias")) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ]) return rename_keys def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : str = state_dict.pop(_a) SCREAMING_SNAKE_CASE : int = val def lowerCamelCase__ ( _a , _a=False): SCREAMING_SNAKE_CASE : Optional[Any] = "" if is_panoptic: SCREAMING_SNAKE_CASE : Optional[int] = "detr." # first: transformer encoder for i in range(6): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight") SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias") # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : int = in_proj_bias[:256] SCREAMING_SNAKE_CASE : Tuple = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : List[Any] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : str = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight") SCREAMING_SNAKE_CASE : str = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias") # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : Dict = in_proj_bias[:256] SCREAMING_SNAKE_CASE : List[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : Any = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop( f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight") SCREAMING_SNAKE_CASE : int = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias") # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE : Tuple = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE : Dict = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias_cross_attn[-256:] def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Tuple = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(_a , stream=_a).raw) return im @torch.no_grad() def lowerCamelCase__ ( _a , _a=None , _a=False): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = get_detr_config(_a) # load original model from torch hub SCREAMING_SNAKE_CASE : Union[str, Any] = { "detr-resnet-50": "detr_resnet50", "detr-resnet-101": "detr_resnet101", } logger.info(f"Converting model {model_name}...") SCREAMING_SNAKE_CASE : Optional[int] = torch.hub.load("facebookresearch/detr" , model_name_to_original_name[model_name] , pretrained=_a).eval() SCREAMING_SNAKE_CASE : Tuple = detr.state_dict() # rename keys for src, dest in create_rename_keys(_a): if is_panoptic: SCREAMING_SNAKE_CASE : List[str] = "detr." + src rename_key(_a , _a , _a) # query, key and value matrices need special treatment read_in_q_k_v(_a , is_panoptic=_a) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE : List[Any] = "detr.model." if is_panoptic else "model." for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith("detr") and not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor") ): SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Union[str, Any] = val elif "class_labels_classifier" in key or "bbox_predictor" in key: SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Optional[int] = val elif key.startswith("bbox_attention") or key.startswith("mask_head"): continue else: SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : List[Any] = val else: if not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor"): SCREAMING_SNAKE_CASE : Any = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Any = val # finally, create HuggingFace model and load state dict SCREAMING_SNAKE_CASE : int = DetrForSegmentation(_a) if is_panoptic else DetrForObjectDetection(_a) model.load_state_dict(_a) model.eval() # verify our conversion on an image SCREAMING_SNAKE_CASE : int = "coco_panoptic" if is_panoptic else "coco_detection" SCREAMING_SNAKE_CASE : Optional[int] = DetrImageProcessor(format=_a) SCREAMING_SNAKE_CASE : List[str] = processor(images=prepare_img() , return_tensors="pt") SCREAMING_SNAKE_CASE : Any = encoding["pixel_values"] SCREAMING_SNAKE_CASE : Optional[Any] = detr(_a) SCREAMING_SNAKE_CASE : Any = model(_a) assert torch.allclose(outputs.logits , original_outputs["pred_logits"] , atol=1E-3) assert torch.allclose(outputs.pred_boxes , original_outputs["pred_boxes"] , atol=1E-3) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs["pred_masks"] , atol=1E-4) print("Looks ok!") if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f"Saving PyTorch model and image processor to {pytorch_dump_folder_path}...") Path(_a).mkdir(exist_ok=_a) model.save_pretrained(_a) processor.save_pretrained(_a) if push_to_hub: # Upload model and image processor to the hub logger.info("Uploading PyTorch model and image processor to the hub...") model.push_to_hub(f"nielsr/{model_name}") processor.push_to_hub(f"nielsr/{model_name}") if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') a_ = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
76
1
def lowerCamelCase__ ( _a = 3 , _a = 7 , _a = 1000000): SCREAMING_SNAKE_CASE : str = 0 SCREAMING_SNAKE_CASE : int = 1 for current_denominator in range(1 , limit + 1): SCREAMING_SNAKE_CASE : int = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: SCREAMING_SNAKE_CASE : List[str] = current_numerator SCREAMING_SNAKE_CASE : List[Any] = current_denominator return max_numerator if __name__ == "__main__": print(solution(numerator=3, denominator=7, limit=100_0000))
76
import os def lowerCamelCase__ ( ): with open(os.path.dirname(_a) + "/p022_names.txt") as file: SCREAMING_SNAKE_CASE : List[str] = str(file.readlines()[0]) SCREAMING_SNAKE_CASE : List[Any] = names.replace("\"" , "").split(",") names.sort() SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : Dict = 0 for i, name in enumerate(_a): for letter in name: name_score += ord(_a) - 64 total_score += (i + 1) * name_score SCREAMING_SNAKE_CASE : str = 0 return total_score if __name__ == "__main__": print(solution())
76
1
class _UpperCamelCase : '''simple docstring''' def __init__( self : List[Any] , a : list[int] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = len(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = [0] * len_array if len_array > 0: SCREAMING_SNAKE_CASE : Dict = array[0] for i in range(1 , a ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.prefix_sum[i - 1] + array[i] def __UpperCamelCase ( self : List[str] , a : int , a : int ) -> int: """simple docstring""" if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def __UpperCamelCase ( self : Dict , a : int ) -> bool: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(a ) return False if __name__ == "__main__": import doctest doctest.testmod()
76
from collections.abc import Callable import numpy as np def lowerCamelCase__ ( _a , _a , _a , _a , _a): SCREAMING_SNAKE_CASE : Dict = int(np.ceil((x_end - xa) / step_size)) SCREAMING_SNAKE_CASE : Tuple = np.zeros((n + 1,)) SCREAMING_SNAKE_CASE : int = ya SCREAMING_SNAKE_CASE : int = xa for k in range(_a): SCREAMING_SNAKE_CASE : Any = y[k] + step_size * ode_func(_a , y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
76
1
from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig a_ = logging.get_logger(__name__) # General docstring a_ = 'RegNetConfig' # Base docstring a_ = 'facebook/regnet-y-040' a_ = [1, 1088, 7, 7] # Image classification docstring a_ = 'facebook/regnet-y-040' a_ = 'tabby, tabby cat' a_ = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class _UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] , a : int , a : int , a : int = 3 , a : int = 1 , a : int = 1 , a : Optional[str] = "relu" , ) -> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : Optional[Any] = nn.Convad( a , a , kernel_size=a , stride=a , padding=kernel_size // 2 , groups=a , bias=a , ) SCREAMING_SNAKE_CASE : List[str] = nn.BatchNormad(a ) SCREAMING_SNAKE_CASE : int = ACTaFN[activation] if activation is not None else nn.Identity() def __UpperCamelCase ( self : Any , a : Dict ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = self.convolution(a ) SCREAMING_SNAKE_CASE : Optional[int] = self.normalization(a ) SCREAMING_SNAKE_CASE : List[Any] = self.activation(a ) return hidden_state class _UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self : Any , a : RegNetConfig ) -> Any: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : Optional[int] = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) SCREAMING_SNAKE_CASE : str = config.num_channels def __UpperCamelCase ( self : List[str] , a : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : int = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) SCREAMING_SNAKE_CASE : Optional[Any] = self.embedder(a ) return hidden_state class _UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self : Union[str, Any] , a : int , a : int , a : int = 2 ) -> str: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : Dict = nn.Convad(a , a , kernel_size=1 , stride=a , bias=a ) SCREAMING_SNAKE_CASE : Optional[Any] = nn.BatchNormad(a ) def __UpperCamelCase ( self : str , a : Tensor ) -> Tensor: """simple docstring""" SCREAMING_SNAKE_CASE : int = self.convolution(a ) SCREAMING_SNAKE_CASE : Optional[Any] = self.normalization(a ) return hidden_state class _UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self : str , a : int , a : int ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : str = nn.AdaptiveAvgPoolad((1, 1) ) SCREAMING_SNAKE_CASE : Any = nn.Sequential( nn.Convad(a , a , kernel_size=1 ) , nn.ReLU() , nn.Convad(a , a , kernel_size=1 ) , nn.Sigmoid() , ) def __UpperCamelCase ( self : int , a : Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.pooler(a ) SCREAMING_SNAKE_CASE : List[Any] = self.attention(a ) SCREAMING_SNAKE_CASE : Optional[Any] = hidden_state * attention return hidden_state class _UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self : Dict , a : RegNetConfig , a : int , a : int , a : int = 1 ) -> Tuple: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : Tuple = in_channels != out_channels or stride != 1 SCREAMING_SNAKE_CASE : Union[str, Any] = max(1 , out_channels // config.groups_width ) SCREAMING_SNAKE_CASE : Union[str, Any] = ( RegNetShortCut(a , a , stride=a ) if should_apply_shortcut else nn.Identity() ) SCREAMING_SNAKE_CASE : int = nn.Sequential( RegNetConvLayer(a , a , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(a , a , stride=a , groups=a , activation=config.hidden_act ) , RegNetConvLayer(a , a , kernel_size=1 , activation=a ) , ) SCREAMING_SNAKE_CASE : Any = ACTaFN[config.hidden_act] def __UpperCamelCase ( self : List[Any] , a : str ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_state SCREAMING_SNAKE_CASE : Optional[Any] = self.layer(a ) SCREAMING_SNAKE_CASE : List[Any] = self.shortcut(a ) hidden_state += residual SCREAMING_SNAKE_CASE : List[str] = self.activation(a ) return hidden_state class _UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self : Optional[Any] , a : RegNetConfig , a : int , a : int , a : int = 1 ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : List[str] = in_channels != out_channels or stride != 1 SCREAMING_SNAKE_CASE : Union[str, Any] = max(1 , out_channels // config.groups_width ) SCREAMING_SNAKE_CASE : Union[str, Any] = ( RegNetShortCut(a , a , stride=a ) if should_apply_shortcut else nn.Identity() ) SCREAMING_SNAKE_CASE : str = nn.Sequential( RegNetConvLayer(a , a , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(a , a , stride=a , groups=a , activation=config.hidden_act ) , RegNetSELayer(a , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(a , a , kernel_size=1 , activation=a ) , ) SCREAMING_SNAKE_CASE : Optional[int] = ACTaFN[config.hidden_act] def __UpperCamelCase ( self : List[str] , a : List[str] ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : str = hidden_state SCREAMING_SNAKE_CASE : Optional[Any] = self.layer(a ) SCREAMING_SNAKE_CASE : Dict = self.shortcut(a ) hidden_state += residual SCREAMING_SNAKE_CASE : Dict = self.activation(a ) return hidden_state class _UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self : Optional[Any] , a : RegNetConfig , a : int , a : int , a : int = 2 , a : int = 2 , ) -> str: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : Tuple = RegNetXLayer if config.layer_type == "x" else RegNetYLayer SCREAMING_SNAKE_CASE : Dict = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( a , a , a , stride=a , ) , *[layer(a , a , a ) for _ in range(depth - 1 )] , ) def __UpperCamelCase ( self : Dict , a : Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.layers(a ) return hidden_state class _UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self : Optional[int] , a : RegNetConfig ) -> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : Dict = nn.ModuleList([] ) # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( RegNetStage( a , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) SCREAMING_SNAKE_CASE : Optional[Any] = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(a , config.depths[1:] ): self.stages.append(RegNetStage(a , a , a , depth=a ) ) def __UpperCamelCase ( self : List[str] , a : Tensor , a : bool = False , a : bool = True ) -> BaseModelOutputWithNoAttention: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: SCREAMING_SNAKE_CASE : Any = hidden_states + (hidden_state,) SCREAMING_SNAKE_CASE : Optional[int] = stage_module(a ) if output_hidden_states: SCREAMING_SNAKE_CASE : Any = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=a , hidden_states=a ) class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =RegNetConfig lowerCamelCase__ ='regnet' lowerCamelCase__ ='pixel_values' lowerCamelCase__ =True def __UpperCamelCase ( self : Tuple , a : List[str] ) -> List[str]: """simple docstring""" if isinstance(a , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="fan_out" , nonlinearity="relu" ) elif isinstance(a , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def __UpperCamelCase ( self : List[Any] , a : List[Any] , a : Optional[Any]=False ) -> List[Any]: """simple docstring""" if isinstance(a , a ): SCREAMING_SNAKE_CASE : int = value a_ = r'\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' a_ = r'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , __A , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class _UpperCamelCase ( __A ): '''simple docstring''' def __init__( self : List[str] , a : Optional[Any] ) -> Optional[Any]: """simple docstring""" super().__init__(a ) SCREAMING_SNAKE_CASE : List[str] = config SCREAMING_SNAKE_CASE : str = RegNetEmbeddings(a ) SCREAMING_SNAKE_CASE : List[Any] = RegNetEncoder(a ) SCREAMING_SNAKE_CASE : Optional[Any] = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(a ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=a , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __UpperCamelCase ( self : List[Any] , a : Tensor , a : Optional[bool] = None , a : Optional[bool] = None ) -> BaseModelOutputWithPoolingAndNoAttention: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE : Dict = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Any = self.embedder(a ) SCREAMING_SNAKE_CASE : Any = self.encoder( a , output_hidden_states=a , return_dict=a ) SCREAMING_SNAKE_CASE : str = encoder_outputs[0] SCREAMING_SNAKE_CASE : str = self.pooler(a ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=a , pooler_output=a , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , __A , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class _UpperCamelCase ( __A ): '''simple docstring''' def __init__( self : str , a : Optional[int] ) -> Tuple: """simple docstring""" super().__init__(a ) SCREAMING_SNAKE_CASE : Optional[Any] = config.num_labels SCREAMING_SNAKE_CASE : List[Any] = RegNetModel(a ) # classification head SCREAMING_SNAKE_CASE : int = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(a ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=a , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __UpperCamelCase ( self : Union[str, Any] , a : Optional[torch.FloatTensor] = None , a : Optional[torch.LongTensor] = None , a : Optional[bool] = None , a : Optional[bool] = None , ) -> ImageClassifierOutputWithNoAttention: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Dict = self.regnet(a , output_hidden_states=a , return_dict=a ) SCREAMING_SNAKE_CASE : List[Any] = outputs.pooler_output if return_dict else outputs[1] SCREAMING_SNAKE_CASE : Optional[Any] = self.classifier(a ) SCREAMING_SNAKE_CASE : Optional[Any] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE : Union[str, Any] = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE : Optional[int] = "single_label_classification" else: SCREAMING_SNAKE_CASE : Any = "multi_label_classification" if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE : Tuple = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE : List[Any] = loss_fct(logits.squeeze() , labels.squeeze() ) else: SCREAMING_SNAKE_CASE : str = loss_fct(a , a ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE : List[str] = CrossEntropyLoss() SCREAMING_SNAKE_CASE : Any = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE : List[str] = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE : Dict = loss_fct(a , a ) if not return_dict: SCREAMING_SNAKE_CASE : List[Any] = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=a , logits=a , hidden_states=outputs.hidden_states )
76
def lowerCamelCase__ ( _a , _a): return int((input_a, input_a).count(1) != 0) def lowerCamelCase__ ( ): assert or_gate(0 , 0) == 0 assert or_gate(0 , 1) == 1 assert or_gate(1 , 0) == 1 assert or_gate(1 , 1) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
76
1
from math import factorial a_ = {str(digit): factorial(digit) for digit in range(10)} def lowerCamelCase__ ( _a): if not isinstance(_a , _a): raise TypeError("Parameter number must be int") if number < 0: raise ValueError("Parameter number must be greater than or equal to 0") # Converts number in string to iterate on its digits and adds its factorial. return sum(DIGIT_FACTORIAL[digit] for digit in str(_a)) def lowerCamelCase__ ( _a = 60 , _a = 1000000): if not isinstance(_a , _a) or not isinstance(_a , _a): raise TypeError("Parameters chain_length and number_limit must be int") if chain_length <= 0 or number_limit <= 0: raise ValueError( "Parameters chain_length and number_limit must be greater than 0") # the counter for the chains with the exact desired length SCREAMING_SNAKE_CASE : Union[str, Any] = 0 # the cached sizes of the previous chains SCREAMING_SNAKE_CASE : dict[int, int] = {} for start_chain_element in range(1 , _a): # The temporary set will contain the elements of the chain SCREAMING_SNAKE_CASE : Dict = set() SCREAMING_SNAKE_CASE : int = 0 # Stop computing the chain when you find a cached size, a repeating item or the # length is greater then the desired one. SCREAMING_SNAKE_CASE : str = start_chain_element while ( chain_element not in chain_sets_lengths and chain_element not in chain_set and chain_set_length <= chain_length ): chain_set.add(_a) chain_set_length += 1 SCREAMING_SNAKE_CASE : List[Any] = digit_factorial_sum(_a) if chain_element in chain_sets_lengths: chain_set_length += chain_sets_lengths[chain_element] SCREAMING_SNAKE_CASE : str = chain_set_length # If chain contains the exact amount of elements increase the counter if chain_set_length == chain_length: chains_counter += 1 return chains_counter if __name__ == "__main__": import doctest doctest.testmod() print(F'''{solution()}''')
76
a_ = 8.314_4598 def lowerCamelCase__ ( _a , _a): if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example a_ = 300 a_ = 28 a_ = rms_speed_of_molecule(temperature, molar_mass) print(F'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
76
1
from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch a_ = logging.get_logger(__name__) @add_end_docstrings( __A , R'\n top_k (`int`, defaults to 5):\n The number of predictions to return.\n targets (`str` or `List[str]`, *optional*):\n When passed, the model will limit the scores to the passed targets instead of looking up in the whole\n vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting\n token will be used (with a warning, and that might be slower).\n\n ' , ) class _UpperCamelCase ( __A ): '''simple docstring''' def __UpperCamelCase ( self : int , a : GenericTensor ) -> np.ndarray: """simple docstring""" if self.framework == "tf": SCREAMING_SNAKE_CASE : List[Any] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": SCREAMING_SNAKE_CASE : Optional[int] = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=a ) else: raise ValueError("Unsupported framework" ) return masked_index def __UpperCamelCase ( self : Union[str, Any] , a : GenericTensor ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_masked_index(a ) SCREAMING_SNAKE_CASE : Any = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( "fill-mask" , self.model.base_model_prefix , F"No mask_token ({self.tokenizer.mask_token}) found on the input" , ) def __UpperCamelCase ( self : Dict , a : GenericTensor ) -> int: """simple docstring""" if isinstance(a , a ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input["input_ids"][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(a ) def __UpperCamelCase ( self : int , a : List[str] , a : int=None , **a : Any ) -> Dict[str, GenericTensor]: """simple docstring""" if return_tensors is None: SCREAMING_SNAKE_CASE : List[Any] = self.framework SCREAMING_SNAKE_CASE : Dict = self.tokenizer(a , return_tensors=a ) self.ensure_exactly_one_mask_token(a ) return model_inputs def __UpperCamelCase ( self : str , a : int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.model(**a ) SCREAMING_SNAKE_CASE : List[str] = model_inputs["input_ids"] return model_outputs def __UpperCamelCase ( self : List[str] , a : Optional[int] , a : Dict=5 , a : Optional[int]=None ) -> Optional[Any]: """simple docstring""" if target_ids is not None and target_ids.shape[0] < top_k: SCREAMING_SNAKE_CASE : Optional[Any] = target_ids.shape[0] SCREAMING_SNAKE_CASE : Optional[int] = model_outputs["input_ids"][0] SCREAMING_SNAKE_CASE : Union[str, Any] = model_outputs["logits"] if self.framework == "tf": SCREAMING_SNAKE_CASE : Optional[Any] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.numpy() SCREAMING_SNAKE_CASE : Dict = outputs[0, masked_index, :] SCREAMING_SNAKE_CASE : Dict = stable_softmax(a , axis=-1 ) if target_ids is not None: SCREAMING_SNAKE_CASE : str = tf.gather_nd(tf.squeeze(a , 0 ) , target_ids.reshape(-1 , 1 ) ) SCREAMING_SNAKE_CASE : int = tf.expand_dims(a , 0 ) SCREAMING_SNAKE_CASE : List[Any] = tf.math.top_k(a , k=a ) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = topk.values.numpy(), topk.indices.numpy() else: SCREAMING_SNAKE_CASE : Tuple = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=a ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample SCREAMING_SNAKE_CASE : Any = outputs[0, masked_index, :] SCREAMING_SNAKE_CASE : str = logits.softmax(dim=-1 ) if target_ids is not None: SCREAMING_SNAKE_CASE : Optional[Any] = probs[..., target_ids] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = probs.topk(a ) SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : Optional[Any] = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): SCREAMING_SNAKE_CASE : Optional[int] = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place SCREAMING_SNAKE_CASE : Dict = input_ids.numpy().copy() if target_ids is not None: SCREAMING_SNAKE_CASE : Tuple = target_ids[p].tolist() SCREAMING_SNAKE_CASE : Any = p # Filter padding out: SCREAMING_SNAKE_CASE : Optional[int] = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back SCREAMING_SNAKE_CASE : List[Any] = self.tokenizer.decode(a , skip_special_tokens=a ) SCREAMING_SNAKE_CASE : Optional[int] = {"score": v, "token": p, "token_str": self.tokenizer.decode([p] ), "sequence": sequence} row.append(a ) result.append(a ) if single_mask: return result[0] return result def __UpperCamelCase ( self : Dict , a : Tuple , a : Tuple=None ) -> Dict: """simple docstring""" if isinstance(a , a ): SCREAMING_SNAKE_CASE : Union[str, Any] = [targets] try: SCREAMING_SNAKE_CASE : Tuple = self.tokenizer.get_vocab() except Exception: SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Union[str, Any] = [] for target in targets: SCREAMING_SNAKE_CASE : int = vocab.get(a , a ) if id_ is None: SCREAMING_SNAKE_CASE : Any = self.tokenizer( a , add_special_tokens=a , return_attention_mask=a , return_token_type_ids=a , max_length=1 , truncation=a , )["input_ids"] if len(a ) == 0: logger.warning( F"The specified target token `{target}` does not exist in the model vocabulary. " "We cannot replace it with anything meaningful, ignoring it" ) continue SCREAMING_SNAKE_CASE : Optional[Any] = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( F"The specified target token `{target}` does not exist in the model vocabulary. " F"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`." ) target_ids.append(id_ ) SCREAMING_SNAKE_CASE : Optional[int] = list(set(a ) ) if len(a ) == 0: raise ValueError("At least one target must be provided when passed." ) SCREAMING_SNAKE_CASE : Dict = np.array(a ) return target_ids def __UpperCamelCase ( self : int , a : List[Any]=None , a : List[Any]=None ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Any = {} if targets is not None: SCREAMING_SNAKE_CASE : str = self.get_target_ids(a , a ) SCREAMING_SNAKE_CASE : Optional[Any] = target_ids if top_k is not None: SCREAMING_SNAKE_CASE : Tuple = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( "fill-mask" , self.model.base_model_prefix , "The tokenizer does not define a `mask_token`." ) return {}, {}, postprocess_params def __call__( self : Any , a : Optional[int] , *a : Dict , **a : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = super().__call__(a , **a ) if isinstance(a , a ) and len(a ) == 1: return outputs[0] return outputs
76
a_ = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : int = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE : int = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE : Optional[int] = queue.pop(0) # get the last node from the path SCREAMING_SNAKE_CASE : Union[str, Any] = path[-1] if node not in explored: SCREAMING_SNAKE_CASE : List[str] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE : List[Any] = list(_a) new_path.append(_a) queue.append(_a) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_a) # in case there's no path between the 2 nodes return [] def lowerCamelCase__ ( _a , _a , _a): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE : str = [start] SCREAMING_SNAKE_CASE : Optional[Any] = set(_a) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE : Union[str, Any] = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE : Optional[int] = queue.pop(0) if node == target: SCREAMING_SNAKE_CASE : Union[str, Any] = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node]) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_a) queue.append(_a) SCREAMING_SNAKE_CASE : Optional[Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, 'G', 'D')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, 'G', 'D')) # returns 4
76
1
from __future__ import annotations from collections import Counter from random import random class _UpperCamelCase : '''simple docstring''' def __init__( self : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = {} def __UpperCamelCase ( self : List[Any] , a : str ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = {} def __UpperCamelCase ( self : Any , a : str , a : str , a : float ) -> None: """simple docstring""" if nodea not in self.connections: self.add_node(a ) if nodea not in self.connections: self.add_node(a ) SCREAMING_SNAKE_CASE : Any = probability def __UpperCamelCase ( self : Any ) -> list[str]: """simple docstring""" return list(self.connections ) def __UpperCamelCase ( self : List[str] , a : str ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : Optional[int] = random() for dest in self.connections[node]: current_probability += self.connections[node][dest] if current_probability > random_value: return dest return "" def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : str = MarkovChainGraphUndirectedUnweighted() for nodea, nodea, probability in transitions: graph.add_transition_probability(_a , _a , _a) SCREAMING_SNAKE_CASE : str = Counter(graph.get_nodes()) SCREAMING_SNAKE_CASE : Optional[Any] = start for _ in range(_a): SCREAMING_SNAKE_CASE : Union[str, Any] = graph.transition(_a) visited[node] += 1 return visited if __name__ == "__main__": import doctest doctest.testmod()
76
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE : Tuple = tokenizer("Hello there" , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer("Hi I am" , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE : str = model(a , labels=a ).loss SCREAMING_SNAKE_CASE : Any = -tf.math.reduce_mean(a ).numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = -21.22_8168 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2e-4 )
76
1
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = tokenizer(example["content"] , truncation=_a)["input_ids"] SCREAMING_SNAKE_CASE : Dict = len(example["content"]) / len(output["input_ids"]) return output a_ = HfArgumentParser(PretokenizationArguments) a_ = parser.parse_args() if args.num_workers is None: a_ = multiprocessing.cpu_count() a_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) a_ = time.time() a_ = load_dataset(args.dataset_name, split='train') print(F'''Dataset loaded in {time.time()-t_start:.2f}s''') a_ = time.time() a_ = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ 'repo_name', 'path', 'copies', 'size', 'content', 'license', 'hash', 'line_mean', 'line_max', 'alpha_frac', 'autogenerated', ], ) print(F'''Dataset tokenized in {time.time()-t_start:.2f}s''') a_ = time.time() ds.push_to_hub(args.tokenized_data_repo) print(F'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
76
from math import factorial def lowerCamelCase__ ( _a , _a , _a): if successes > trials: raise ValueError("successes must be lower or equal to trials") if trials < 0 or successes < 0: raise ValueError("the function is defined for non-negative integers") if not isinstance(_a , _a) or not isinstance(_a , _a): raise ValueError("the function is defined for non-negative integers") if not 0 < prob < 1: raise ValueError("prob has to be in range of 1 - 0") SCREAMING_SNAKE_CASE : int = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! SCREAMING_SNAKE_CASE : List[Any] = float(factorial(_a)) coefficient /= factorial(_a) * factorial(trials - successes) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
76
1
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): if isinstance(_a , (list, tuple)) and isinstance(videos[0] , (list, tuple)) and is_valid_image(videos[0][0]): return videos elif isinstance(_a , (list, tuple)) and is_valid_image(videos[0]): return [videos] elif is_valid_image(_a): return [[videos]] raise ValueError(f"Could not make batched video from {videos}") class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =['pixel_values'] def __init__( self : Optional[Any] , a : bool = True , a : Dict[str, int] = None , a : PILImageResampling = PILImageResampling.BILINEAR , a : bool = True , a : Dict[str, int] = None , a : bool = True , a : Union[int, float] = 1 / 255 , a : bool = True , a : bool = True , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , **a : Tuple , ) -> None: """simple docstring""" super().__init__(**a ) SCREAMING_SNAKE_CASE : Tuple = size if size is not None else {"shortest_edge": 256} SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE : str = get_size_dict(a , param_name="crop_size" ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : Optional[int] = do_center_crop SCREAMING_SNAKE_CASE : int = crop_size SCREAMING_SNAKE_CASE : int = resample SCREAMING_SNAKE_CASE : Any = do_rescale SCREAMING_SNAKE_CASE : int = rescale_factor SCREAMING_SNAKE_CASE : Tuple = offset SCREAMING_SNAKE_CASE : str = do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def __UpperCamelCase ( self : Optional[Any] , a : np.ndarray , a : Dict[str, int] , a : PILImageResampling = PILImageResampling.BILINEAR , a : Optional[Union[str, ChannelDimension]] = None , **a : Union[str, Any] , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) if "shortest_edge" in size: SCREAMING_SNAKE_CASE : str = get_resize_output_image_size(a , size["shortest_edge"] , default_to_square=a ) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE : Dict = (size["height"], size["width"]) else: raise ValueError(F"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a , size=a , resample=a , data_format=a , **a ) def __UpperCamelCase ( self : List[str] , a : np.ndarray , a : Dict[str, int] , a : Optional[Union[str, ChannelDimension]] = None , **a : str , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : str = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(F"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __UpperCamelCase ( self : List[Any] , a : np.ndarray , a : Union[int, float] , a : bool = True , a : Optional[Union[str, ChannelDimension]] = None , **a : Tuple , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = image.astype(np.floataa ) if offset: SCREAMING_SNAKE_CASE : Union[str, Any] = image - (scale / 2) return rescale(a , scale=a , data_format=a , **a ) def __UpperCamelCase ( self : int , a : np.ndarray , a : Union[float, List[float]] , a : Union[float, List[float]] , a : Optional[Union[str, ChannelDimension]] = None , **a : List[str] , ) -> np.ndarray: """simple docstring""" return normalize(a , mean=a , std=a , data_format=a , **a ) def __UpperCamelCase ( self : Tuple , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray: """simple docstring""" if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) if offset and not do_rescale: raise ValueError("For offset, do_rescale must also be set to True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : List[str] = to_numpy_array(a ) if do_resize: SCREAMING_SNAKE_CASE : Optional[Any] = self.resize(image=a , size=a , resample=a ) if do_center_crop: SCREAMING_SNAKE_CASE : Union[str, Any] = self.center_crop(a , size=a ) if do_rescale: SCREAMING_SNAKE_CASE : Any = self.rescale(image=a , scale=a , offset=a ) if do_normalize: SCREAMING_SNAKE_CASE : Tuple = self.normalize(image=a , mean=a , std=a ) SCREAMING_SNAKE_CASE : Optional[int] = to_channel_dimension_format(a , a ) return image def __UpperCamelCase ( self : Dict , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[str, TensorType]] = None , a : ChannelDimension = ChannelDimension.FIRST , **a : Tuple , ) -> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE : str = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Union[str, Any] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : int = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE : str = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[Any] = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Optional[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : int = size if size is not None else self.size SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : Tuple = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(a , param_name="crop_size" ) 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." ) SCREAMING_SNAKE_CASE : Optional[int] = make_batched(a ) SCREAMING_SNAKE_CASE : List[Any] = [ [ self._preprocess_image( image=a , do_resize=a , size=a , resample=a , do_center_crop=a , crop_size=a , do_rescale=a , rescale_factor=a , offset=a , do_normalize=a , image_mean=a , image_std=a , data_format=a , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE : Optional[int] = {"pixel_values": videos} return BatchFeature(data=a , tensor_type=a )
76
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =CustomTokenizer pass
76
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, ) a_ = {'configuration_xglm': ['XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'XGLMConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['XGLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['XGLMTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'XGLMForCausalLM', 'XGLMModel', 'XGLMPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'FlaxXGLMForCausalLM', 'FlaxXGLMModel', 'FlaxXGLMPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFXGLMForCausalLM', 'TFXGLMModel', 'TFXGLMPreTrainedModel', ] if TYPE_CHECKING: from .configuration_xglm import XGLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XGLMConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm import XGLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xglm_fast import XGLMTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xglm import XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, XGLMForCausalLM, XGLMModel, XGLMPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_xglm import FlaxXGLMForCausalLM, FlaxXGLMModel, FlaxXGLMPreTrainedModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, TFXGLMPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure)
76
import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex a_ = logging.getLogger(__name__) class _UpperCamelCase : '''simple docstring''' def __init__( self : Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = False def __UpperCamelCase ( self : str , a : str , a : Optional[int] , a : Any , a : str ) -> List[Any]: """simple docstring""" if not self.initialized: SCREAMING_SNAKE_CASE : List[str] = RagRetriever( a , question_encoder_tokenizer=a , generator_tokenizer=a , index=a , init_retrieval=a , ) SCREAMING_SNAKE_CASE : Optional[int] = True def __UpperCamelCase ( self : List[str] ) -> Optional[int]: """simple docstring""" self.retriever.index.init_index() def __UpperCamelCase ( self : Optional[Any] , a : List[Any] , a : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = self.retriever._main_retrieve(a , a ) return doc_ids, retrieved_doc_embeds class _UpperCamelCase ( __A ): '''simple docstring''' def __init__( self : Tuple , a : Any , a : Tuple , a : Tuple , a : Tuple , a : List[Any]=None ) -> Optional[int]: """simple docstring""" if index is not None and index.is_initialized() and len(a ) > 0: raise ValueError( "When using Ray for distributed fine-tuning, " "you'll need to provide the paths instead, " "as the dataset and the index are loaded " "separately. More info in examples/rag/use_own_knowledge_dataset.py " ) super().__init__( a , question_encoder_tokenizer=a , generator_tokenizer=a , index=a , init_retrieval=a , ) SCREAMING_SNAKE_CASE : Optional[Any] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(a , a , a , a ) for worker in self.retrieval_workers ] ) def __UpperCamelCase ( self : Any ) -> Dict: """simple docstring""" logger.info("initializing retrieval" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __UpperCamelCase ( self : Tuple , a : Optional[int] , a : Any ) -> int: """simple docstring""" if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. SCREAMING_SNAKE_CASE : Optional[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = ray.get(random_worker.retrieve.remote(a , a ) ) else: SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Any = self._main_retrieve(a , a ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(a ) @classmethod def __UpperCamelCase ( cls : str , a : Optional[Any] , a : Any=None , **a : List[Any] ) -> str: """simple docstring""" return super(a , cls ).get_tokenizers(a , a , **a ) @classmethod def __UpperCamelCase ( cls : Union[str, Any] , a : int , a : Any , a : List[Any]=None , **a : Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : str = kwargs.pop("config" , a ) or RagConfig.from_pretrained(a , **a ) SCREAMING_SNAKE_CASE : List[Any] = RagTokenizer.from_pretrained(a , config=a ) SCREAMING_SNAKE_CASE : List[Any] = rag_tokenizer.question_encoder SCREAMING_SNAKE_CASE : List[Any] = rag_tokenizer.generator if indexed_dataset is not None: SCREAMING_SNAKE_CASE : str = "custom" SCREAMING_SNAKE_CASE : List[Any] = CustomHFIndex(config.retrieval_vector_size , a ) else: SCREAMING_SNAKE_CASE : List[str] = cls._build_index(a ) return cls( a , question_encoder_tokenizer=a , generator_tokenizer=a , retrieval_workers=a , index=a , )
76
1
def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : set[int] = set() # To detect a back edge, keep track of vertices currently in the recursion stack SCREAMING_SNAKE_CASE : set[int] = set() return any( node not in visited and depth_first_search(_a , _a , _a , _a) for node in graph) def lowerCamelCase__ ( _a , _a , _a , _a): visited.add(_a) rec_stk.add(_a) for node in graph[vertex]: if node not in visited: if depth_first_search(_a , _a , _a , _a): return True elif node in rec_stk: return True # The node needs to be removed from recursion stack before function ends rec_stk.remove(_a) return False if __name__ == "__main__": from doctest import testmod testmod()
76
from typing import Any class _UpperCamelCase : '''simple docstring''' def __init__( self : Dict , a : Any ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : int = data SCREAMING_SNAKE_CASE : int = None def __repr__( self : str ) -> str: """simple docstring""" return F"Node({self.data})" class _UpperCamelCase : '''simple docstring''' def __init__( self : List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = None def __iter__( self : Any ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.head while node: yield node.data SCREAMING_SNAKE_CASE : List[str] = node.next def __len__( self : str ) -> int: """simple docstring""" return sum(1 for _ in self ) def __repr__( self : Optional[Any] ) -> str: """simple docstring""" return "->".join([str(a ) for item in self] ) def __getitem__( self : List[Any] , a : int ) -> Any: """simple docstring""" if not 0 <= index < len(self ): raise ValueError("list index out of range." ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Tuple , a : int , a : Any ) -> None: """simple docstring""" if not 0 <= index < len(self ): raise ValueError("list index out of range." ) SCREAMING_SNAKE_CASE : str = self.head for _ in range(a ): SCREAMING_SNAKE_CASE : str = current.next SCREAMING_SNAKE_CASE : Any = data def __UpperCamelCase ( self : List[str] , a : Any ) -> None: """simple docstring""" self.insert_nth(len(self ) , a ) def __UpperCamelCase ( self : Union[str, Any] , a : Any ) -> None: """simple docstring""" self.insert_nth(0 , a ) def __UpperCamelCase ( self : Optional[Any] , a : int , a : Any ) -> None: """simple docstring""" if not 0 <= index <= len(self ): raise IndexError("list index out of range" ) SCREAMING_SNAKE_CASE : Any = Node(a ) if self.head is None: SCREAMING_SNAKE_CASE : Optional[int] = new_node elif index == 0: SCREAMING_SNAKE_CASE : Optional[int] = self.head # link new_node to head SCREAMING_SNAKE_CASE : List[Any] = new_node else: SCREAMING_SNAKE_CASE : Optional[Any] = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : Optional[int] = temp.next SCREAMING_SNAKE_CASE : Optional[int] = temp.next SCREAMING_SNAKE_CASE : int = new_node def __UpperCamelCase ( self : Optional[int] ) -> None: # print every node data """simple docstring""" print(self ) def __UpperCamelCase ( self : int ) -> Any: """simple docstring""" return self.delete_nth(0 ) def __UpperCamelCase ( self : Any ) -> Any: # delete from tail """simple docstring""" return self.delete_nth(len(self ) - 1 ) def __UpperCamelCase ( self : List[str] , a : int = 0 ) -> Any: """simple docstring""" if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("List index out of range." ) SCREAMING_SNAKE_CASE : Tuple = self.head # default first node if index == 0: SCREAMING_SNAKE_CASE : List[str] = self.head.next else: SCREAMING_SNAKE_CASE : Optional[Any] = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : Any = temp.next SCREAMING_SNAKE_CASE : List[Any] = temp.next SCREAMING_SNAKE_CASE : List[str] = temp.next.next return delete_node.data def __UpperCamelCase ( self : List[Any] ) -> bool: """simple docstring""" return self.head is None def __UpperCamelCase ( self : Optional[int] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = None SCREAMING_SNAKE_CASE : str = self.head while current: # Store the current node's next node. SCREAMING_SNAKE_CASE : Any = current.next # Make the current node's next point backwards SCREAMING_SNAKE_CASE : List[Any] = prev # Make the previous node be the current node SCREAMING_SNAKE_CASE : Any = current # Make the current node the next node (to progress iteration) SCREAMING_SNAKE_CASE : str = next_node # Return prev in order to put the head at the end SCREAMING_SNAKE_CASE : Optional[Any] = prev def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Union[str, Any] = LinkedList() assert linked_list.is_empty() is True assert str(_a) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(_a) == i linked_list.insert_nth(_a , i + 1) assert str(_a) == "->".join(str(_a) for i in range(1 , 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(_a) == "->".join(str(_a) for i in range(0 , 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(_a) == 9 assert str(_a) == "->".join(str(_a) for i in range(1 , 10)) assert all(linked_list[i] == i + 1 for i in range(0 , 9)) is True for i in range(0 , 9): SCREAMING_SNAKE_CASE : str = -i assert all(linked_list[i] == -i for i in range(0 , 9)) is True linked_list.reverse() assert str(_a) == "->".join(str(_a) for i in range(-8 , 1)) def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Optional[Any] = [ -9, 100, Node(77345112), "dlrow olleH", 7, 5555, 0, -192.5_5555, "Hello, world!", 77.9, Node(10), None, None, 12.20, ] SCREAMING_SNAKE_CASE : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(_a) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(_a) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head SCREAMING_SNAKE_CASE : List[Any] = linked_list.delete_head() assert result == -9 assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail SCREAMING_SNAKE_CASE : Any = linked_list.delete_tail() assert result == 12.2 assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list SCREAMING_SNAKE_CASE : Any = linked_list.delete_nth(10) assert result is None assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!")) assert ( str(_a) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(_a) assert ( str(_a) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(_a) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def lowerCamelCase__ ( ): from doctest import testmod testmod() SCREAMING_SNAKE_CASE : Optional[int] = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(_a) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") SCREAMING_SNAKE_CASE : Dict = input("Enter New Value: ").strip() print("New list:") print(_a) print(f"length of linked_list is : {len(_a)}") if __name__ == "__main__": main()
76
1
def lowerCamelCase__ ( _a , _a , _a=False): if isinstance(_a , _a) and isinstance(_a , _a): SCREAMING_SNAKE_CASE : List[str] = len(set_a.intersection(_a)) if alternative_union: SCREAMING_SNAKE_CASE : Optional[int] = len(_a) + len(_a) else: SCREAMING_SNAKE_CASE : Union[str, Any] = len(set_a.union(_a)) return intersection / union if isinstance(_a , (list, tuple)) and isinstance(_a , (list, tuple)): SCREAMING_SNAKE_CASE : Optional[Any] = [element for element in set_a if element in set_b] if alternative_union: SCREAMING_SNAKE_CASE : Optional[int] = len(_a) + len(_a) return len(_a) / union else: SCREAMING_SNAKE_CASE : Optional[Any] = set_a + [element for element in set_b if element not in set_a] return len(_a) / len(_a) return len(_a) / len(_a) return None if __name__ == "__main__": a_ = {'a', 'b', 'c', 'd', 'e'} a_ = {'c', 'd', 'e', 'f', 'h', 'i'} print(jaccard_similarity(set_a, set_b))
76
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger a_ = get_logger(__name__) class _UpperCamelCase ( enum.Enum ): '''simple docstring''' lowerCamelCase__ ='all_checks' lowerCamelCase__ ='basic_checks' lowerCamelCase__ ='no_checks' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' def lowerCamelCase__ ( _a , _a , _a=None): if expected_checksums is None: logger.info("Unable to verify checksums.") return if len(set(_a) - set(_a)) > 0: raise ExpectedMoreDownloadedFiles(str(set(_a) - set(_a))) if len(set(_a) - set(_a)) > 0: raise UnexpectedDownloadedFile(str(set(_a) - set(_a))) SCREAMING_SNAKE_CASE : str = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] SCREAMING_SNAKE_CASE : Tuple = " for " + verification_name if verification_name is not None else "" if len(_a) > 0: raise NonMatchingChecksumError( f"Checksums didn't match{for_verification_name}:\n" f"{bad_urls}\n" "Set `verification_mode='no_checks'` to skip checksums verification and ignore this error") logger.info("All the checksums matched successfully" + for_verification_name) class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' def lowerCamelCase__ ( _a , _a): if expected_splits is None: logger.info("Unable to verify splits sizes.") return if len(set(_a) - set(_a)) > 0: raise ExpectedMoreSplits(str(set(_a) - set(_a))) if len(set(_a) - set(_a)) > 0: raise UnexpectedSplits(str(set(_a) - set(_a))) SCREAMING_SNAKE_CASE : List[str] = [ {"expected": expected_splits[name], "recorded": recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(_a) > 0: raise NonMatchingSplitsSizesError(str(_a)) logger.info("All the splits matched successfully.") def lowerCamelCase__ ( _a , _a = True): if record_checksum: SCREAMING_SNAKE_CASE : List[str] = shaaaa() with open(_a , "rb") as f: for chunk in iter(lambda: f.read(1 << 20) , b""): m.update(_a) SCREAMING_SNAKE_CASE : Optional[int] = m.hexdigest() else: SCREAMING_SNAKE_CASE : List[str] = None return {"num_bytes": os.path.getsize(_a), "checksum": checksum} def lowerCamelCase__ ( _a): if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
76
1
from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer a_ = logging.get_logger(__name__) a_ = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } a_ = { 'vocab_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json' }, 'merges_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt' }, 'tokenizer_config_file': { 'facebook/blenderbot_small-90M': ( 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json' ) }, } a_ = { 'facebook/blenderbot_small-90M': 512, } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =VOCAB_FILES_NAMES lowerCamelCase__ =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ =BlenderbotSmallTokenizer def __init__( self : Optional[int] , a : str=None , a : List[Any]=None , a : Union[str, Any]="<|endoftext|>" , a : int="<|endoftext|>" , a : Dict="<|endoftext|>" , a : Tuple=False , a : Optional[Any]=True , **a : Union[str, Any] , ) -> Any: """simple docstring""" super().__init__( ByteLevelBPETokenizer( vocab=a , merges=a , add_prefix_space=a , trim_offsets=a , ) , bos_token=a , eos_token=a , unk_token=a , **a , ) SCREAMING_SNAKE_CASE : List[str] = add_prefix_space def __UpperCamelCase ( self : Union[str, Any] , a : Tuple , a : Optional[Any]=None ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def __UpperCamelCase ( self : Tuple , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = [self.sep_token_id] SCREAMING_SNAKE_CASE : int = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
76
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCamelCase__ ( _a , _a): # Load checkpoint SCREAMING_SNAKE_CASE : int = torch.load(_a , map_location="cpu") SCREAMING_SNAKE_CASE : Dict = chkpt["model"] # We have the base model one level deeper than the original XLM repository SCREAMING_SNAKE_CASE : Optional[int] = {} for k, v in state_dict.items(): if "pred_layer" in k: SCREAMING_SNAKE_CASE : List[str] = v else: SCREAMING_SNAKE_CASE : int = v SCREAMING_SNAKE_CASE : int = chkpt["params"] SCREAMING_SNAKE_CASE : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(_a , (torch.FloatTensor, numpy.ndarray))} SCREAMING_SNAKE_CASE : List[Any] = chkpt["dico_word2id"] SCREAMING_SNAKE_CASE : List[Any] = {s + "</w>" if s.find("@@") == -1 and i > 13 else s.replace("@@" , ""): i for s, i in vocab.items()} # Save pytorch-model SCREAMING_SNAKE_CASE : Tuple = pytorch_dump_folder_path + "/" + WEIGHTS_NAME SCREAMING_SNAKE_CASE : Any = pytorch_dump_folder_path + "/" + CONFIG_NAME SCREAMING_SNAKE_CASE : Optional[int] = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["vocab_file"] print(f"Save PyTorch model to {pytorch_weights_dump_path}") torch.save(_a , _a) print(f"Save configuration file to {pytorch_config_dump_path}") with open(_a , "w" , encoding="utf-8") as f: f.write(json.dumps(_a , indent=2) + "\n") print(f"Save vocab file to {pytorch_config_dump_path}") with open(_a , "w" , encoding="utf-8") as f: f.write(json.dumps(_a , indent=2) + "\n") if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xlm_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) a_ = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
76
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { 'configuration_distilbert': [ 'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DistilBertConfig', 'DistilBertOnnxConfig', ], 'tokenization_distilbert': ['DistilBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['DistilBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'DistilBertForMaskedLM', 'DistilBertForMultipleChoice', 'DistilBertForQuestionAnswering', 'DistilBertForSequenceClassification', 'DistilBertForTokenClassification', 'DistilBertModel', 'DistilBertPreTrainedModel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFDistilBertForMaskedLM', 'TFDistilBertForMultipleChoice', 'TFDistilBertForQuestionAnswering', 'TFDistilBertForSequenceClassification', 'TFDistilBertForTokenClassification', 'TFDistilBertMainLayer', 'TFDistilBertModel', 'TFDistilBertPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'FlaxDistilBertForMaskedLM', 'FlaxDistilBertForMultipleChoice', 'FlaxDistilBertForQuestionAnswering', 'FlaxDistilBertForSequenceClassification', 'FlaxDistilBertForTokenClassification', 'FlaxDistilBertModel', 'FlaxDistilBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_distilbert import ( DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, DistilBertConfig, DistilBertOnnxConfig, ) from .tokenization_distilbert import DistilBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_distilbert_fast import DistilBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_distilbert import ( DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, DistilBertForMaskedLM, DistilBertForMultipleChoice, DistilBertForQuestionAnswering, DistilBertForSequenceClassification, DistilBertForTokenClassification, DistilBertModel, DistilBertPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_distilbert import ( TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFDistilBertForMaskedLM, TFDistilBertForMultipleChoice, TFDistilBertForQuestionAnswering, TFDistilBertForSequenceClassification, TFDistilBertForTokenClassification, TFDistilBertMainLayer, TFDistilBertModel, TFDistilBertPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, FlaxDistilBertPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
def lowerCamelCase__ ( _a , _a): _validate_point(_a) _validate_point(_a) if len(_a) != len(_a): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(a - b) for a, b in zip(_a , _a))) def lowerCamelCase__ ( _a): if point: if isinstance(_a , _a): for item in point: if not isinstance(_a , (int, float)): SCREAMING_SNAKE_CASE : List[Any] = ( "Expected a list of numbers as input, found " f"{type(_a).__name__}" ) raise TypeError(_a) else: SCREAMING_SNAKE_CASE : List[Any] = f"Expected a list of numbers as input, found {type(_a).__name__}" raise TypeError(_a) else: raise ValueError("Missing an input") def lowerCamelCase__ ( _a , _a): _validate_point(_a) _validate_point(_a) if len(_a) != len(_a): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(x - y) for x, y in zip(_a , _a))) if __name__ == "__main__": import doctest doctest.testmod()
76
1
from math import factorial def lowerCamelCase__ ( _a , _a , _a): if successes > trials: raise ValueError("successes must be lower or equal to trials") if trials < 0 or successes < 0: raise ValueError("the function is defined for non-negative integers") if not isinstance(_a , _a) or not isinstance(_a , _a): raise ValueError("the function is defined for non-negative integers") if not 0 < prob < 1: raise ValueError("prob has to be in range of 1 - 0") SCREAMING_SNAKE_CASE : int = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! SCREAMING_SNAKE_CASE : List[Any] = float(factorial(_a)) coefficient /= factorial(_a) * factorial(trials - successes) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
76
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ ='vit_msn' def __init__( self : str , a : Tuple=768 , a : Tuple=12 , a : Any=12 , a : int=3072 , a : List[Any]="gelu" , a : Dict=0.0 , a : int=0.0 , a : str=0.02 , a : List[str]=1e-06 , a : List[Any]=224 , a : Union[str, Any]=16 , a : Union[str, Any]=3 , a : Tuple=True , **a : Dict , ) -> List[Any]: """simple docstring""" super().__init__(**a ) SCREAMING_SNAKE_CASE : Dict = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = initializer_range SCREAMING_SNAKE_CASE : int = layer_norm_eps SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : Tuple = patch_size SCREAMING_SNAKE_CASE : Optional[int] = num_channels SCREAMING_SNAKE_CASE : List[str] = qkv_bias
76
1
# Usage: # ./gen-card-facebook-wmt19.py import os from pathlib import Path def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : Optional[Any] = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, oder?", } # BLUE scores as follows: # "pair": [fairseq, transformers] SCREAMING_SNAKE_CASE : Any = { "ru-en": ["[41.3](http://matrix.statmt.org/matrix/output/1907?run_id=6937)", "39.20"], "en-ru": ["[36.4](http://matrix.statmt.org/matrix/output/1914?run_id=6724)", "33.47"], "en-de": ["[43.1](http://matrix.statmt.org/matrix/output/1909?run_id=6862)", "42.83"], "de-en": ["[42.3](http://matrix.statmt.org/matrix/output/1902?run_id=6750)", "41.35"], } SCREAMING_SNAKE_CASE : Tuple = f"{src_lang}-{tgt_lang}" SCREAMING_SNAKE_CASE : Union[str, Any] = f"\n---\nlanguage: \n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt19\n- facebook\nlicense: apache-2.0\ndatasets:\n- wmt19\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of [fairseq wmt19 transformer](https://github.com/pytorch/fairseq/blob/master/examples/wmt19/README.md) for {src_lang}-{tgt_lang}.\n\nFor more details, please see, [Facebook FAIR's WMT19 News Translation Task Submission](https://arxiv.org/abs/1907.06616).\n\nThe abbreviation FSMT stands for FairSeqMachineTranslation\n\nAll four models are available:\n\n* [wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru)\n* [wmt19-ru-en](https://huggingface.co/facebook/wmt19-ru-en)\n* [wmt19-en-de](https://huggingface.co/facebook/wmt19-en-de)\n* [wmt19-de-en](https://huggingface.co/facebook/wmt19-de-en)\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"facebook/wmt19-{src_lang}-{tgt_lang}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n- The original (and this ported model) doesn't seem to handle well inputs with repeated sub-phrases, [content gets truncated](https://discuss.huggingface.co/t/issues-with-translating-inputs-containing-repeated-phrases/981)\n\n## Training data\n\nPretrained weights were left identical to the original model released by fairseq. For more details, please, see the [paper](https://arxiv.org/abs/1907.06616).\n\n## Eval results\n\npair | fairseq | transformers\n-------|---------|----------\n{pair} | {scores[pair][0]} | {scores[pair][1]}\n\nThe score is slightly below the score reported by `fairseq`, since `transformers`` currently doesn't support:\n- model ensemble, therefore the best performing checkpoint was ported (``model4.pt``).\n- re-ranking\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=15\nmkdir -p $DATA_DIR\nsacrebleu -t wmt19 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt19 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py facebook/wmt19-$PAIR $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\nnote: fairseq reports using a beam of 50, so you should get a slightly higher score if re-run with `--num_beams 50`.\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt19/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2019.tgz?1556572561)\n\n\n### BibTeX entry and citation info\n\n```bibtex\n@inproceedings{{...,\n year={{2020}},\n title={{Facebook FAIR's WMT19 News Translation Task Submission}},\n author={{Ng, Nathan and Yee, Kyra and Baevski, Alexei and Ott, Myle and Auli, Michael and Edunov, Sergey}},\n booktitle={{Proc. of WMT}},\n}}\n```\n\n\n## TODO\n\n- port model ensemble (fairseq uses 4 model checkpoints)\n\n" os.makedirs(_a , exist_ok=_a) SCREAMING_SNAKE_CASE : Optional[int] = os.path.join(_a , "README.md") print(f"Generating {path}") with open(_a , "w" , encoding="utf-8") as f: f.write(_a) # make sure we are under the root of the project a_ = Path(__file__).resolve().parent.parent.parent a_ = repo_dir / 'model_cards' for model_name in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]: a_ , a_ , a_ = model_name.split('-') a_ = model_cards_dir / 'facebook' / model_name write_model_card(model_card_dir, src_lang=src_lang, tgt_lang=tgt_lang)
76
import baseaa def lowerCamelCase__ ( _a): return baseaa.aaaencode(string.encode("utf-8")) def lowerCamelCase__ ( _a): return baseaa.aaadecode(_a).decode("utf-8") if __name__ == "__main__": import doctest doctest.testmod()
76
1
import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel from diffusers.pipelines.stable_diffusion_safe import StableDiffusionPipelineSafe as StableDiffusionPipeline from diffusers.utils import floats_tensor, nightly, torch_device from diffusers.utils.testing_utils import require_torch_gpu class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Any ) -> Optional[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def __UpperCamelCase ( self : List[str] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : Any = 3 SCREAMING_SNAKE_CASE : Union[str, Any] = (32, 32) SCREAMING_SNAKE_CASE : Any = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(a ) return image @property def __UpperCamelCase ( self : Optional[Any] ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) return model @property def __UpperCamelCase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = 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 , ) return model @property def __UpperCamelCase ( self : Dict ) -> Tuple: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModel(a ) @property def __UpperCamelCase ( self : Optional[Any] ) -> List[str]: """simple docstring""" def extract(*a : List[Any] , **a : List[str] ): class _UpperCamelCase : '''simple docstring''' def __init__( self : Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : str = torch.ones([0] ) def __UpperCamelCase ( self : Union[str, Any] , a : Optional[Any] ) -> Tuple: """simple docstring""" self.pixel_values.to(a ) return self return Out() return extract def __UpperCamelCase ( self : Dict ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : List[Any] = self.dummy_cond_unet SCREAMING_SNAKE_CASE : List[Any] = DDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="scaled_linear" , clip_sample=a , set_alpha_to_one=a , ) SCREAMING_SNAKE_CASE : Any = self.dummy_vae SCREAMING_SNAKE_CASE : Optional[int] = self.dummy_text_encoder SCREAMING_SNAKE_CASE : Dict = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE : Dict = StableDiffusionPipeline( unet=a , scheduler=a , vae=a , text_encoder=a , tokenizer=a , safety_checker=a , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe.to(a ) sd_pipe.set_progress_bar_config(disable=a ) SCREAMING_SNAKE_CASE : str = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE : Optional[Any] = torch.Generator(device=a ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Any = sd_pipe([prompt] , generator=a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) SCREAMING_SNAKE_CASE : Optional[Any] = output.images SCREAMING_SNAKE_CASE : List[Any] = torch.Generator(device=a ).manual_seed(0 ) SCREAMING_SNAKE_CASE : str = sd_pipe( [prompt] , generator=a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=a , )[0] SCREAMING_SNAKE_CASE : int = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : int = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : List[Any] = np.array([0.5756, 0.6118, 0.5005, 0.5041, 0.5471, 0.4726, 0.4976, 0.4865, 0.4864] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCamelCase ( self : int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = "cpu" # ensure determinism for the device-dependent torch.Generator SCREAMING_SNAKE_CASE : Optional[Any] = self.dummy_cond_unet SCREAMING_SNAKE_CASE : Tuple = PNDMScheduler(skip_prk_steps=a ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.dummy_vae SCREAMING_SNAKE_CASE : Optional[Any] = self.dummy_text_encoder SCREAMING_SNAKE_CASE : int = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE : Any = StableDiffusionPipeline( unet=a , scheduler=a , vae=a , text_encoder=a , tokenizer=a , safety_checker=a , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE : Tuple = sd_pipe.to(a ) sd_pipe.set_progress_bar_config(disable=a ) SCREAMING_SNAKE_CASE : Union[str, Any] = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE : str = torch.Generator(device=a ).manual_seed(0 ) SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe([prompt] , generator=a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" ) SCREAMING_SNAKE_CASE : Union[str, Any] = output.images SCREAMING_SNAKE_CASE : Any = torch.Generator(device=a ).manual_seed(0 ) SCREAMING_SNAKE_CASE : int = sd_pipe( [prompt] , generator=a , guidance_scale=6.0 , num_inference_steps=2 , output_type="np" , return_dict=a , )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : List[str] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) SCREAMING_SNAKE_CASE : Optional[Any] = np.array([0.5125, 0.5716, 0.4828, 0.5060, 0.5650, 0.4768, 0.5185, 0.4895, 0.4993] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCamelCase ( self : List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = StableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-lms-pipe" , safety_checker=a ) assert isinstance(a , a ) assert isinstance(pipe.scheduler , a ) assert pipe.safety_checker is None SCREAMING_SNAKE_CASE : List[Any] = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(a ) SCREAMING_SNAKE_CASE : Tuple = StableDiffusionPipeline.from_pretrained(a ) # sanity check that the pipeline still works assert pipe.safety_checker is None SCREAMING_SNAKE_CASE : Optional[Any] = pipe("example prompt" , num_inference_steps=2 ).images[0] assert image is not None @unittest.skipIf(torch_device != "cuda" , "This test requires a GPU" ) def __UpperCamelCase ( self : str ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.dummy_cond_unet SCREAMING_SNAKE_CASE : List[str] = PNDMScheduler(skip_prk_steps=a ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.dummy_vae SCREAMING_SNAKE_CASE : List[str] = self.dummy_text_encoder SCREAMING_SNAKE_CASE : List[str] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) # put models in fp16 SCREAMING_SNAKE_CASE : Union[str, Any] = unet.half() SCREAMING_SNAKE_CASE : str = vae.half() SCREAMING_SNAKE_CASE : Dict = bert.half() # make sure here that pndm scheduler skips prk SCREAMING_SNAKE_CASE : Optional[Any] = StableDiffusionPipeline( unet=a , scheduler=a , vae=a , text_encoder=a , tokenizer=a , safety_checker=a , feature_extractor=self.dummy_extractor , ) SCREAMING_SNAKE_CASE : Any = sd_pipe.to(a ) sd_pipe.set_progress_bar_config(disable=a ) SCREAMING_SNAKE_CASE : str = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE : Any = sd_pipe([prompt] , num_inference_steps=2 , output_type="np" ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Optional[int] ) -> List[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __UpperCamelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=a ) SCREAMING_SNAKE_CASE : Any = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) SCREAMING_SNAKE_CASE : int = sd_pipe.to(a ) sd_pipe.set_progress_bar_config(disable=a ) SCREAMING_SNAKE_CASE : Optional[Any] = ( "portrait of girl with smokey eyes makeup in abandoned hotel, grange clothes, redshift, wide high angle" " coloured polaroid photograph with flash, kodak film, hyper real, stunning moody cinematography, with" " anamorphic lenses, by maripol, fallen angels by wong kar - wai, style of suspiria and neon demon and" " children from bahnhof zoo, detailed " ) SCREAMING_SNAKE_CASE : Tuple = 40_0366_0346 SCREAMING_SNAKE_CASE : Dict = 7 # without safety guidance (sld_guidance_scale = 0) SCREAMING_SNAKE_CASE : Optional[Any] = torch.manual_seed(a ) SCREAMING_SNAKE_CASE : int = sd_pipe( [prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE : Any = output.images SCREAMING_SNAKE_CASE : str = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : List[str] = [0.2278, 0.2231, 0.2249, 0.2333, 0.2303, 0.1885, 0.2273, 0.2144, 0.2176] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 # without safety guidance (strong configuration) SCREAMING_SNAKE_CASE : int = torch.manual_seed(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe( [prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE : str = output.images SCREAMING_SNAKE_CASE : Dict = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Any = [0.2383, 0.2276, 0.236, 0.2192, 0.2186, 0.2053, 0.1971, 0.1901, 0.1719] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCamelCase ( self : List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" , safety_checker=a ) SCREAMING_SNAKE_CASE : Optional[Any] = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) SCREAMING_SNAKE_CASE : Tuple = sd_pipe.to(a ) sd_pipe.set_progress_bar_config(disable=a ) SCREAMING_SNAKE_CASE : str = "padme amidala taking a bath artwork, safe for work, no nudity" SCREAMING_SNAKE_CASE : List[Any] = 27_3497_1755 SCREAMING_SNAKE_CASE : List[Any] = 7 SCREAMING_SNAKE_CASE : List[Any] = torch.manual_seed(a ) SCREAMING_SNAKE_CASE : Dict = sd_pipe( [prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE : Dict = output.images SCREAMING_SNAKE_CASE : List[str] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : List[str] = [0.3502, 0.3622, 0.3396, 0.3642, 0.3478, 0.3318, 0.35, 0.3348, 0.3297] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 SCREAMING_SNAKE_CASE : int = torch.manual_seed(a ) SCREAMING_SNAKE_CASE : str = sd_pipe( [prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE : Tuple = output.images SCREAMING_SNAKE_CASE : Any = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Tuple = [0.5531, 0.5206, 0.4895, 0.5156, 0.5182, 0.4751, 0.4802, 0.4803, 0.4443] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def __UpperCamelCase ( self : Dict ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" ) SCREAMING_SNAKE_CASE : Tuple = sd_pipe.to(a ) sd_pipe.set_progress_bar_config(disable=a ) SCREAMING_SNAKE_CASE : int = ( "the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c." " leyendecker" ) SCREAMING_SNAKE_CASE : int = 10_4435_5234 SCREAMING_SNAKE_CASE : Tuple = 12 SCREAMING_SNAKE_CASE : Any = torch.manual_seed(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe( [prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=0 , ) SCREAMING_SNAKE_CASE : int = output.images SCREAMING_SNAKE_CASE : List[str] = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Dict = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-7 SCREAMING_SNAKE_CASE : int = torch.manual_seed(a ) SCREAMING_SNAKE_CASE : Optional[Any] = sd_pipe( [prompt] , generator=a , guidance_scale=a , num_inference_steps=50 , output_type="np" , width=512 , height=512 , sld_guidance_scale=2000 , sld_warmup_steps=7 , sld_threshold=0.025 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) SCREAMING_SNAKE_CASE : Tuple = output.images SCREAMING_SNAKE_CASE : Tuple = image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE : Union[str, Any] = np.array([0.5818, 0.6285, 0.6835, 0.6019, 0.625, 0.6754, 0.6096, 0.6334, 0.6561] ) assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
76
from datetime import datetime as dt import os from github import Github a_ = [ 'good first issue', 'good second issue', 'good difficult issue', 'feature request', 'new model', 'wip', ] def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : int = Github(os.environ["GITHUB_TOKEN"]) SCREAMING_SNAKE_CASE : List[str] = g.get_repo("huggingface/transformers") SCREAMING_SNAKE_CASE : Optional[int] = repo.get_issues(state="open") for issue in open_issues: SCREAMING_SNAKE_CASE : List[Any] = sorted([comment for comment in issue.get_comments()] , key=lambda _a: i.created_at , reverse=_a) SCREAMING_SNAKE_CASE : str = comments[0] if len(_a) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state="closed") elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( "This issue has been automatically marked as stale because it has not had " "recent activity. If you think this still needs to be addressed " "please comment on this thread.\n\nPlease note that issues that do not follow the " "[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) " "are likely to be ignored.") if __name__ == "__main__": main()
76
1
def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : int = int(_a) if n_element < 1: SCREAMING_SNAKE_CASE : Optional[int] = ValueError("a should be a positive number") raise my_error SCREAMING_SNAKE_CASE : Union[str, Any] = [1] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = (0, 0, 0) SCREAMING_SNAKE_CASE : Union[str, 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__": a_ = input('Enter the last number (nth term) of the Hamming Number Series: ') print('Formula of Hamming Number Series => 2^i * 3^j * 5^k') a_ = hamming(int(n)) print('-----------------------------------------------------') print(F'''The list with nth numbers is: {hamming_numbers}''') print('-----------------------------------------------------')
76
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): if isinstance(_a , (list, tuple)) and isinstance(videos[0] , (list, tuple)) and is_valid_image(videos[0][0]): return videos elif isinstance(_a , (list, tuple)) and is_valid_image(videos[0]): return [videos] elif is_valid_image(_a): return [[videos]] raise ValueError(f"Could not make batched video from {videos}") class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =['pixel_values'] def __init__( self : Optional[Any] , a : bool = True , a : Dict[str, int] = None , a : PILImageResampling = PILImageResampling.BILINEAR , a : bool = True , a : Dict[str, int] = None , a : bool = True , a : Union[int, float] = 1 / 255 , a : bool = True , a : bool = True , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , **a : Tuple , ) -> None: """simple docstring""" super().__init__(**a ) SCREAMING_SNAKE_CASE : Tuple = size if size is not None else {"shortest_edge": 256} SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE : str = get_size_dict(a , param_name="crop_size" ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : Optional[int] = do_center_crop SCREAMING_SNAKE_CASE : int = crop_size SCREAMING_SNAKE_CASE : int = resample SCREAMING_SNAKE_CASE : Any = do_rescale SCREAMING_SNAKE_CASE : int = rescale_factor SCREAMING_SNAKE_CASE : Tuple = offset SCREAMING_SNAKE_CASE : str = do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def __UpperCamelCase ( self : Optional[Any] , a : np.ndarray , a : Dict[str, int] , a : PILImageResampling = PILImageResampling.BILINEAR , a : Optional[Union[str, ChannelDimension]] = None , **a : Union[str, Any] , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) if "shortest_edge" in size: SCREAMING_SNAKE_CASE : str = get_resize_output_image_size(a , size["shortest_edge"] , default_to_square=a ) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE : Dict = (size["height"], size["width"]) else: raise ValueError(F"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a , size=a , resample=a , data_format=a , **a ) def __UpperCamelCase ( self : List[str] , a : np.ndarray , a : Dict[str, int] , a : Optional[Union[str, ChannelDimension]] = None , **a : str , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : str = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(F"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __UpperCamelCase ( self : List[Any] , a : np.ndarray , a : Union[int, float] , a : bool = True , a : Optional[Union[str, ChannelDimension]] = None , **a : Tuple , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = image.astype(np.floataa ) if offset: SCREAMING_SNAKE_CASE : Union[str, Any] = image - (scale / 2) return rescale(a , scale=a , data_format=a , **a ) def __UpperCamelCase ( self : int , a : np.ndarray , a : Union[float, List[float]] , a : Union[float, List[float]] , a : Optional[Union[str, ChannelDimension]] = None , **a : List[str] , ) -> np.ndarray: """simple docstring""" return normalize(a , mean=a , std=a , data_format=a , **a ) def __UpperCamelCase ( self : Tuple , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray: """simple docstring""" if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) if offset and not do_rescale: raise ValueError("For offset, do_rescale must also be set to True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : List[str] = to_numpy_array(a ) if do_resize: SCREAMING_SNAKE_CASE : Optional[Any] = self.resize(image=a , size=a , resample=a ) if do_center_crop: SCREAMING_SNAKE_CASE : Union[str, Any] = self.center_crop(a , size=a ) if do_rescale: SCREAMING_SNAKE_CASE : Any = self.rescale(image=a , scale=a , offset=a ) if do_normalize: SCREAMING_SNAKE_CASE : Tuple = self.normalize(image=a , mean=a , std=a ) SCREAMING_SNAKE_CASE : Optional[int] = to_channel_dimension_format(a , a ) return image def __UpperCamelCase ( self : Dict , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[str, TensorType]] = None , a : ChannelDimension = ChannelDimension.FIRST , **a : Tuple , ) -> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE : str = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Union[str, Any] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : int = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE : str = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[Any] = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Optional[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : int = size if size is not None else self.size SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : Tuple = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(a , param_name="crop_size" ) 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." ) SCREAMING_SNAKE_CASE : Optional[int] = make_batched(a ) SCREAMING_SNAKE_CASE : List[Any] = [ [ self._preprocess_image( image=a , do_resize=a , size=a , resample=a , do_center_crop=a , crop_size=a , do_rescale=a , rescale_factor=a , offset=a , do_normalize=a , image_mean=a , image_std=a , data_format=a , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE : Optional[int] = {"pixel_values": videos} return BatchFeature(data=a , tensor_type=a )
76
1
from __future__ import annotations def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = position SCREAMING_SNAKE_CASE : Optional[int] = [ (y + 1, x + 2), (y - 1, x + 2), (y + 1, x - 2), (y - 1, x - 2), (y + 2, x + 1), (y + 2, x - 1), (y - 2, x + 1), (y - 2, x - 1), ] SCREAMING_SNAKE_CASE : Optional[int] = [] for position in positions: SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = position if 0 <= y_test < n and 0 <= x_test < n: permissible_positions.append(_a) return permissible_positions def lowerCamelCase__ ( _a): return not any(elem == 0 for row in board for elem in row) def lowerCamelCase__ ( _a , _a , _a): if is_complete(_a): return True for position in get_valid_pos(_a , len(_a)): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[Any] = position if board[y][x] == 0: SCREAMING_SNAKE_CASE : Any = curr + 1 if open_knight_tour_helper(_a , _a , curr + 1): return True SCREAMING_SNAKE_CASE : int = 0 return False def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : List[str] = [[0 for i in range(_a)] for j in range(_a)] for i in range(_a): for j in range(_a): SCREAMING_SNAKE_CASE : List[Any] = 1 if open_knight_tour_helper(_a , (i, j) , 1): return board SCREAMING_SNAKE_CASE : Tuple = 0 SCREAMING_SNAKE_CASE : Dict = f"Open Kight Tour cannot be performed on a board of size {n}" raise ValueError(_a) if __name__ == "__main__": import doctest doctest.testmod()
76
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt'} a_ = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } a_ = { 'YituTech/conv-bert-base': 512, 'YituTech/conv-bert-medium-small': 512, 'YituTech/conv-bert-small': 512, } a_ = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =VOCAB_FILES_NAMES lowerCamelCase__ =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ =PRETRAINED_INIT_CONFIGURATION lowerCamelCase__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ =ConvBertTokenizer def __init__( self : List[str] , a : Union[str, Any]=None , a : Optional[int]=None , a : int=True , a : Tuple="[UNK]" , a : Dict="[SEP]" , a : Dict="[PAD]" , a : List[Any]="[CLS]" , a : Tuple="[MASK]" , a : Dict=True , a : Optional[Any]=None , **a : str , ) -> Dict: """simple docstring""" super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) SCREAMING_SNAKE_CASE : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , a ) != do_lower_case or normalizer_state.get("strip_accents" , a ) != strip_accents or normalizer_state.get("handle_chinese_chars" , a ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : List[str] = getattr(a , normalizer_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE : Any = strip_accents SCREAMING_SNAKE_CASE : Optional[int] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : List[str] = normalizer_class(**a ) SCREAMING_SNAKE_CASE : str = do_lower_case def __UpperCamelCase ( self : Union[str, Any] , a : List[Any] , a : int=None ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __UpperCamelCase ( self : Dict , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCamelCase ( self : Tuple , a : str , a : Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self._tokenizer.model.save(a , name=a ) return tuple(a )
76
1
import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING a_ = logging.get_logger(__name__) a_ = { 'microsoft/conditional-detr-resnet-50': ( 'https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json' ), } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ ='conditional_detr' lowerCamelCase__ =['past_key_values'] lowerCamelCase__ ={ 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : List[Any] , a : List[str]=True , a : int=None , a : Optional[int]=3 , a : List[str]=300 , a : Optional[Any]=6 , a : Tuple=2048 , a : Dict=8 , a : Optional[Any]=6 , a : Tuple=2048 , a : List[Any]=8 , a : Tuple=0.0 , a : Optional[Any]=0.0 , a : Tuple=True , a : List[str]="relu" , a : List[Any]=256 , a : str=0.1 , a : Optional[Any]=0.0 , a : Optional[int]=0.0 , a : Union[str, Any]=0.02 , a : Tuple=1.0 , a : Dict=False , a : Optional[Any]="sine" , a : Optional[int]="resnet50" , a : Dict=True , a : str=False , a : int=2 , a : List[str]=5 , a : str=2 , a : Optional[int]=1 , a : Tuple=1 , a : Optional[Any]=2 , a : Optional[int]=5 , a : List[str]=2 , a : Any=0.25 , **a : Tuple , ) -> Dict: """simple docstring""" if backbone_config is not None and use_timm_backbone: raise ValueError("You can't specify both `backbone_config` and `use_timm_backbone`." ) if not use_timm_backbone: if backbone_config is None: logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone." ) SCREAMING_SNAKE_CASE : List[str] = CONFIG_MAPPING["resnet"](out_features=["stage4"] ) elif isinstance(a , a ): SCREAMING_SNAKE_CASE : List[Any] = backbone_config.get("model_type" ) SCREAMING_SNAKE_CASE : List[str] = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE : List[Any] = config_class.from_dict(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = use_timm_backbone SCREAMING_SNAKE_CASE : Dict = backbone_config SCREAMING_SNAKE_CASE : Tuple = num_channels SCREAMING_SNAKE_CASE : str = num_queries SCREAMING_SNAKE_CASE : List[Any] = d_model SCREAMING_SNAKE_CASE : Tuple = encoder_ffn_dim SCREAMING_SNAKE_CASE : Union[str, Any] = encoder_layers SCREAMING_SNAKE_CASE : Tuple = encoder_attention_heads SCREAMING_SNAKE_CASE : int = decoder_ffn_dim SCREAMING_SNAKE_CASE : Dict = decoder_layers SCREAMING_SNAKE_CASE : Dict = decoder_attention_heads SCREAMING_SNAKE_CASE : str = dropout SCREAMING_SNAKE_CASE : Any = attention_dropout SCREAMING_SNAKE_CASE : List[Any] = activation_dropout SCREAMING_SNAKE_CASE : List[Any] = activation_function SCREAMING_SNAKE_CASE : Optional[int] = init_std SCREAMING_SNAKE_CASE : Optional[int] = init_xavier_std SCREAMING_SNAKE_CASE : Dict = encoder_layerdrop SCREAMING_SNAKE_CASE : str = decoder_layerdrop SCREAMING_SNAKE_CASE : Any = encoder_layers SCREAMING_SNAKE_CASE : Optional[Any] = auxiliary_loss SCREAMING_SNAKE_CASE : Dict = position_embedding_type SCREAMING_SNAKE_CASE : Dict = backbone SCREAMING_SNAKE_CASE : Any = use_pretrained_backbone SCREAMING_SNAKE_CASE : str = dilation # Hungarian matcher SCREAMING_SNAKE_CASE : int = class_cost SCREAMING_SNAKE_CASE : Optional[int] = bbox_cost SCREAMING_SNAKE_CASE : Optional[Any] = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE : List[Any] = mask_loss_coefficient SCREAMING_SNAKE_CASE : Optional[int] = dice_loss_coefficient SCREAMING_SNAKE_CASE : Union[str, Any] = cls_loss_coefficient SCREAMING_SNAKE_CASE : Dict = bbox_loss_coefficient SCREAMING_SNAKE_CASE : Tuple = giou_loss_coefficient SCREAMING_SNAKE_CASE : List[Any] = focal_alpha super().__init__(is_encoder_decoder=a , **a ) @property def __UpperCamelCase ( self : Dict ) -> int: """simple docstring""" return self.encoder_attention_heads @property def __UpperCamelCase ( self : str ) -> int: """simple docstring""" return self.d_model def __UpperCamelCase ( self : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: SCREAMING_SNAKE_CASE : Optional[int] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE : str = self.__class__.model_type return output class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =version.parse('1.11' ) @property def __UpperCamelCase ( self : Optional[int] ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ("pixel_mask", {0: "batch"}), ] ) @property def __UpperCamelCase ( self : List[Any] ) -> float: """simple docstring""" return 1e-5 @property def __UpperCamelCase ( self : Optional[int] ) -> int: """simple docstring""" return 12
76
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. a_ = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(_a) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE : Union[str, Any] = terminalreporter.config.getoption("--make-reports") if make_reports: pytest_terminal_summary_main(_a , id=_a)
76
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { 'configuration_blip_2': [ 'BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Blip2Config', 'Blip2QFormerConfig', 'Blip2VisionConfig', ], 'processing_blip_2': ['Blip2Processor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST', 'Blip2Model', 'Blip2QFormerModel', 'Blip2PreTrainedModel', 'Blip2ForConditionalGeneration', 'Blip2VisionModel', ] if TYPE_CHECKING: from .configuration_blip_a import ( BLIP_2_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipaConfig, BlipaQFormerConfig, BlipaVisionConfig, ) from .processing_blip_a import BlipaProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip_a import ( BLIP_2_PRETRAINED_MODEL_ARCHIVE_LIST, BlipaForConditionalGeneration, BlipaModel, BlipaPreTrainedModel, BlipaQFormerModel, BlipaVisionModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , a : int , a : Optional[int]=13 , a : Optional[int]=3 , a : int=224 , a : Optional[int]=30 , a : int=400 , a : Union[str, Any]=True , a : int=None , a : Tuple=True , a : Tuple=[0.5, 0.5, 0.5] , a : Optional[int]=[0.5, 0.5, 0.5] , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = size if size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : int = num_channels SCREAMING_SNAKE_CASE : Any = image_size SCREAMING_SNAKE_CASE : Tuple = min_resolution SCREAMING_SNAKE_CASE : str = max_resolution SCREAMING_SNAKE_CASE : int = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : int = do_normalize SCREAMING_SNAKE_CASE : Tuple = image_mean SCREAMING_SNAKE_CASE : Tuple = image_std def __UpperCamelCase ( self : Any ) -> Optional[int]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =ViTImageProcessor if is_vision_available() else None def __UpperCamelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = EfficientFormerImageProcessorTester(self ) @property def __UpperCamelCase ( self : Any ) -> List[str]: """simple docstring""" return self.image_proc_tester.prepare_image_processor_dict() def __UpperCamelCase ( self : List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , "image_mean" ) ) self.assertTrue(hasattr(a , "image_std" ) ) self.assertTrue(hasattr(a , "do_normalize" ) ) self.assertTrue(hasattr(a , "do_resize" ) ) self.assertTrue(hasattr(a , "size" ) ) def __UpperCamelCase ( self : int ) -> str: """simple docstring""" pass def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : List[str] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : str = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , numpify=a ) for image in image_inputs: self.assertIsInstance(a , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Any = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , torchify=a ) for image in image_inputs: self.assertIsInstance(a , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , )
76
1
import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed a_ = { 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def lowerCamelCase__ ( _a): assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def lowerCamelCase__ ( _a , _a): if args.student_type == "roberta": SCREAMING_SNAKE_CASE : Any = False elif args.student_type == "gpt2": SCREAMING_SNAKE_CASE : Dict = False def lowerCamelCase__ ( _a , _a): if args.student_type == "roberta": SCREAMING_SNAKE_CASE : int = False def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser(description="Training") parser.add_argument("--force" , action="store_true" , help="Overwrite dump_path if it already exists.") parser.add_argument( "--dump_path" , type=_a , required=_a , help="The output directory (log, checkpoints, parameters, etc.)") parser.add_argument( "--data_file" , type=_a , required=_a , help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence." , ) parser.add_argument( "--student_type" , type=_a , choices=["distilbert", "roberta", "gpt2"] , required=_a , help="The student type (DistilBERT, RoBERTa)." , ) parser.add_argument("--student_config" , type=_a , required=_a , help="Path to the student configuration.") parser.add_argument( "--student_pretrained_weights" , default=_a , type=_a , help="Load student initialization checkpoint.") parser.add_argument( "--teacher_type" , choices=["bert", "roberta", "gpt2"] , required=_a , help="Teacher type (BERT, RoBERTa).") parser.add_argument("--teacher_name" , type=_a , required=_a , help="The teacher model.") parser.add_argument("--temperature" , default=2.0 , type=_a , help="Temperature for the softmax temperature.") parser.add_argument( "--alpha_ce" , default=0.5 , type=_a , help="Linear weight for the distillation loss. Must be >=0.") parser.add_argument( "--alpha_mlm" , default=0.0 , type=_a , help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag." , ) parser.add_argument("--alpha_clm" , default=0.5 , type=_a , help="Linear weight for the CLM loss. Must be >=0.") parser.add_argument("--alpha_mse" , default=0.0 , type=_a , help="Linear weight of the MSE loss. Must be >=0.") parser.add_argument( "--alpha_cos" , default=0.0 , type=_a , help="Linear weight of the cosine embedding loss. Must be >=0.") parser.add_argument( "--mlm" , action="store_true" , help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM.") parser.add_argument( "--mlm_mask_prop" , default=0.15 , type=_a , help="Proportion of tokens for which we need to make a prediction." , ) parser.add_argument("--word_mask" , default=0.8 , type=_a , help="Proportion of tokens to mask out.") parser.add_argument("--word_keep" , default=0.1 , type=_a , help="Proportion of tokens to keep.") parser.add_argument("--word_rand" , default=0.1 , type=_a , help="Proportion of tokens to randomly replace.") parser.add_argument( "--mlm_smoothing" , default=0.7 , type=_a , help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec)." , ) parser.add_argument("--token_counts" , type=_a , help="The token counts in the data_file for MLM.") parser.add_argument( "--restrict_ce_to_mask" , action="store_true" , help="If true, compute the distillation loss only the [MLM] prediction distribution." , ) parser.add_argument( "--freeze_pos_embs" , action="store_true" , help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only." , ) parser.add_argument( "--freeze_token_type_embds" , action="store_true" , help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only." , ) parser.add_argument("--n_epoch" , type=_a , default=3 , help="Number of pass on the whole dataset.") parser.add_argument("--batch_size" , type=_a , default=5 , help="Batch size (for each process).") parser.add_argument( "--group_by_size" , action="store_false" , help="If true, group sequences that have similar length into the same batch. Default is true." , ) parser.add_argument( "--gradient_accumulation_steps" , type=_a , default=50 , help="Gradient accumulation for larger training batches." , ) parser.add_argument("--warmup_prop" , default=0.05 , type=_a , help="Linear warmup proportion.") parser.add_argument("--weight_decay" , default=0.0 , type=_a , help="Weight decay if we apply some.") parser.add_argument("--learning_rate" , default=5E-4 , type=_a , help="The initial learning rate for Adam.") parser.add_argument("--adam_epsilon" , default=1E-6 , type=_a , help="Epsilon for Adam optimizer.") parser.add_argument("--max_grad_norm" , default=5.0 , type=_a , help="Max gradient norm.") parser.add_argument("--initializer_range" , default=0.02 , type=_a , help="Random initialization range.") parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=_a , default="O1" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_gpu" , type=_a , default=1 , help="Number of GPUs in the node.") parser.add_argument("--local_rank" , type=_a , default=-1 , help="Distributed training - Local rank") parser.add_argument("--seed" , type=_a , default=56 , help="Random seed") parser.add_argument("--log_interval" , type=_a , default=500 , help="Tensorboard logging interval.") parser.add_argument("--checkpoint_interval" , type=_a , default=4000 , help="Checkpoint interval.") SCREAMING_SNAKE_CASE : Union[str, Any] = parser.parse_args() sanity_checks(_a) # ARGS # init_gpu_params(_a) set_seed(_a) if args.is_master: if os.path.exists(args.dump_path): if not args.force: raise ValueError( f"Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite" " itUse `--force` if you want to overwrite it") else: shutil.rmtree(args.dump_path) if not os.path.exists(args.dump_path): os.makedirs(args.dump_path) logger.info(f"Experiment will be dumped and logged in {args.dump_path}") # SAVE PARAMS # logger.info(f"Param: {args}") with open(os.path.join(args.dump_path , "parameters.json") , "w") as f: json.dump(vars(_a) , _a , indent=4) git_log(args.dump_path) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[Any] = MODEL_CLASSES[args.student_type] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Union[str, Any] = MODEL_CLASSES[args.teacher_type] # TOKENIZER # SCREAMING_SNAKE_CASE : str = teacher_tokenizer_class.from_pretrained(args.teacher_name) SCREAMING_SNAKE_CASE : Any = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): SCREAMING_SNAKE_CASE : Dict = tokenizer.all_special_tokens.index(_a) SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.all_special_ids[idx] logger.info(f"Special tokens {special_tok_ids}") SCREAMING_SNAKE_CASE : Optional[Any] = special_tok_ids SCREAMING_SNAKE_CASE : List[str] = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"Loading data from {args.data_file}") with open(args.data_file , "rb") as fp: SCREAMING_SNAKE_CASE : str = pickle.load(_a) if args.mlm: logger.info(f"Loading token counts from {args.token_counts} (already pre-computed)") with open(args.token_counts , "rb") as fp: SCREAMING_SNAKE_CASE : Any = pickle.load(_a) SCREAMING_SNAKE_CASE : List[Any] = np.maximum(_a , 1) ** -args.mlm_smoothing for idx in special_tok_ids.values(): SCREAMING_SNAKE_CASE : Union[str, Any] = 0.0 # do not predict special tokens SCREAMING_SNAKE_CASE : Tuple = torch.from_numpy(_a) else: SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : Optional[int] = LmSeqsDataset(params=_a , data=_a) logger.info("Data loader created.") # STUDENT # logger.info(f"Loading student config from {args.student_config}") SCREAMING_SNAKE_CASE : List[str] = student_config_class.from_pretrained(args.student_config) SCREAMING_SNAKE_CASE : List[str] = True if args.student_pretrained_weights is not None: logger.info(f"Loading pretrained weights from {args.student_pretrained_weights}") SCREAMING_SNAKE_CASE : str = student_model_class.from_pretrained(args.student_pretrained_weights , config=_a) else: SCREAMING_SNAKE_CASE : Optional[Any] = student_model_class(_a) if args.n_gpu > 0: student.to(f"cuda:{args.local_rank}") logger.info("Student loaded.") # TEACHER # SCREAMING_SNAKE_CASE : Optional[int] = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=_a) if args.n_gpu > 0: teacher.to(f"cuda:{args.local_rank}") logger.info(f"Teacher loaded from {args.teacher_name}.") # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(_a , _a) if args.freeze_token_type_embds: freeze_token_type_embeddings(_a , _a) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() SCREAMING_SNAKE_CASE : List[str] = Distiller( params=_a , dataset=_a , token_probs=_a , student=_a , teacher=_a) distiller.train() logger.info("Let's go get some drinks.") if __name__ == "__main__": main()
76
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = tokenizer(example["content"] , truncation=_a)["input_ids"] SCREAMING_SNAKE_CASE : Dict = len(example["content"]) / len(output["input_ids"]) return output a_ = HfArgumentParser(PretokenizationArguments) a_ = parser.parse_args() if args.num_workers is None: a_ = multiprocessing.cpu_count() a_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) a_ = time.time() a_ = load_dataset(args.dataset_name, split='train') print(F'''Dataset loaded in {time.time()-t_start:.2f}s''') a_ = time.time() a_ = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ 'repo_name', 'path', 'copies', 'size', 'content', 'license', 'hash', 'line_mean', 'line_max', 'alpha_frac', 'autogenerated', ], ) print(F'''Dataset tokenized in {time.time()-t_start:.2f}s''') a_ = time.time() ds.push_to_hub(args.tokenized_data_repo) print(F'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
76
1
from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES a_ = logging.get_logger(__name__) a_ = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) a_ = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) a_ = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) a_ = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) a_ = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) a_ = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) a_ = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) a_ = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) a_ = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) a_ = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) a_ = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) a_ = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) a_ = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) a_ = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) a_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) a_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) a_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) a_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) a_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) a_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) a_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) a_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) a_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) a_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) a_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) a_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) a_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) a_ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_MAPPING a_ = auto_class_update(FlaxAutoModel) class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_PRETRAINING_MAPPING a_ = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_CAUSAL_LM_MAPPING a_ = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_MASKED_LM_MAPPING a_ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a_ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING a_ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING a_ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING a_ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING a_ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING a_ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING a_ = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING a_ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class _UpperCamelCase ( _BaseAutoModelClass ): '''simple docstring''' lowerCamelCase__ =FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING a_ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
76
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): # initialize config if "resnet-50" in model_name: SCREAMING_SNAKE_CASE : int = ResNetConfig.from_pretrained("microsoft/resnet-50") elif "resnet-101" in model_name: SCREAMING_SNAKE_CASE : int = ResNetConfig.from_pretrained("microsoft/resnet-101") else: raise ValueError("Model name should include either resnet50 or resnet101") SCREAMING_SNAKE_CASE : str = DetrConfig(use_timm_backbone=_a , backbone_config=_a) # set label attributes SCREAMING_SNAKE_CASE : List[str] = "panoptic" in model_name if is_panoptic: SCREAMING_SNAKE_CASE : Union[str, Any] = 250 else: SCREAMING_SNAKE_CASE : Union[str, Any] = 91 SCREAMING_SNAKE_CASE : str = "huggingface/label-files" SCREAMING_SNAKE_CASE : Union[str, Any] = "coco-detection-id2label.json" SCREAMING_SNAKE_CASE : Optional[Any] = json.load(open(hf_hub_download(_a , _a , repo_type="dataset") , "r")) SCREAMING_SNAKE_CASE : int = {int(_a): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : List[Any] = idalabel SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in idalabel.items()} return config, is_panoptic def lowerCamelCase__ ( _a): # here we list all keys to be renamed (original name on the left, our name on the right) SCREAMING_SNAKE_CASE : Union[str, Any] = [] # stem # fmt: off rename_keys.append(("backbone.0.body.conv1.weight", "backbone.conv_encoder.model.embedder.embedder.convolution.weight")) rename_keys.append(("backbone.0.body.bn1.weight", "backbone.conv_encoder.model.embedder.embedder.normalization.weight")) rename_keys.append(("backbone.0.body.bn1.bias", "backbone.conv_encoder.model.embedder.embedder.normalization.bias")) rename_keys.append(("backbone.0.body.bn1.running_mean", "backbone.conv_encoder.model.embedder.embedder.normalization.running_mean")) rename_keys.append(("backbone.0.body.bn1.running_var", "backbone.conv_encoder.model.embedder.embedder.normalization.running_var")) # stages for stage_idx in range(len(config.backbone_config.depths)): for layer_idx in range(config.backbone_config.depths[stage_idx]): # shortcut if layer_idx == 0: rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var", )) # 3 convs for i in range(3): rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var", )) # fmt: on for i in range(config.encoder_layers): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( f"transformer.encoder.layers.{i}.self_attn.out_proj.weight", f"encoder.layers.{i}.self_attn.out_proj.weight", )) rename_keys.append( (f"transformer.encoder.layers.{i}.self_attn.out_proj.bias", f"encoder.layers.{i}.self_attn.out_proj.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"encoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"encoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"encoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"encoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm1.weight", f"encoder.layers.{i}.self_attn_layer_norm.weight")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm1.bias", f"encoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm2.weight", f"encoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"encoder.layers.{i}.final_layer_norm.bias")) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"decoder.layers.{i}.self_attn.out_proj.weight", )) rename_keys.append( (f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"decoder.layers.{i}.self_attn.out_proj.bias")) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight", f"decoder.layers.{i}.encoder_attn.out_proj.weight", )) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias", f"decoder.layers.{i}.encoder_attn.out_proj.bias", )) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"decoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"decoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"decoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"decoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm1.weight", f"decoder.layers.{i}.self_attn_layer_norm.weight")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm1.bias", f"decoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.weight", f"decoder.layers.{i}.encoder_attn_layer_norm.weight")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.bias", f"decoder.layers.{i}.encoder_attn_layer_norm.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm3.weight", f"decoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"decoder.layers.{i}.final_layer_norm.bias")) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ]) return rename_keys def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : str = state_dict.pop(_a) SCREAMING_SNAKE_CASE : int = val def lowerCamelCase__ ( _a , _a=False): SCREAMING_SNAKE_CASE : Optional[Any] = "" if is_panoptic: SCREAMING_SNAKE_CASE : Optional[int] = "detr." # first: transformer encoder for i in range(6): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight") SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias") # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : int = in_proj_bias[:256] SCREAMING_SNAKE_CASE : Tuple = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : List[Any] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : str = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight") SCREAMING_SNAKE_CASE : str = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias") # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : Dict = in_proj_bias[:256] SCREAMING_SNAKE_CASE : List[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : Any = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop( f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight") SCREAMING_SNAKE_CASE : int = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias") # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE : Tuple = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE : Dict = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias_cross_attn[-256:] def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Tuple = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(_a , stream=_a).raw) return im @torch.no_grad() def lowerCamelCase__ ( _a , _a=None , _a=False): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = get_detr_config(_a) # load original model from torch hub SCREAMING_SNAKE_CASE : Union[str, Any] = { "detr-resnet-50": "detr_resnet50", "detr-resnet-101": "detr_resnet101", } logger.info(f"Converting model {model_name}...") SCREAMING_SNAKE_CASE : Optional[int] = torch.hub.load("facebookresearch/detr" , model_name_to_original_name[model_name] , pretrained=_a).eval() SCREAMING_SNAKE_CASE : Tuple = detr.state_dict() # rename keys for src, dest in create_rename_keys(_a): if is_panoptic: SCREAMING_SNAKE_CASE : List[str] = "detr." + src rename_key(_a , _a , _a) # query, key and value matrices need special treatment read_in_q_k_v(_a , is_panoptic=_a) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE : List[Any] = "detr.model." if is_panoptic else "model." for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith("detr") and not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor") ): SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Union[str, Any] = val elif "class_labels_classifier" in key or "bbox_predictor" in key: SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Optional[int] = val elif key.startswith("bbox_attention") or key.startswith("mask_head"): continue else: SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : List[Any] = val else: if not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor"): SCREAMING_SNAKE_CASE : Any = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Any = val # finally, create HuggingFace model and load state dict SCREAMING_SNAKE_CASE : int = DetrForSegmentation(_a) if is_panoptic else DetrForObjectDetection(_a) model.load_state_dict(_a) model.eval() # verify our conversion on an image SCREAMING_SNAKE_CASE : int = "coco_panoptic" if is_panoptic else "coco_detection" SCREAMING_SNAKE_CASE : Optional[int] = DetrImageProcessor(format=_a) SCREAMING_SNAKE_CASE : List[str] = processor(images=prepare_img() , return_tensors="pt") SCREAMING_SNAKE_CASE : Any = encoding["pixel_values"] SCREAMING_SNAKE_CASE : Optional[Any] = detr(_a) SCREAMING_SNAKE_CASE : Any = model(_a) assert torch.allclose(outputs.logits , original_outputs["pred_logits"] , atol=1E-3) assert torch.allclose(outputs.pred_boxes , original_outputs["pred_boxes"] , atol=1E-3) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs["pred_masks"] , atol=1E-4) print("Looks ok!") if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f"Saving PyTorch model and image processor to {pytorch_dump_folder_path}...") Path(_a).mkdir(exist_ok=_a) model.save_pretrained(_a) processor.save_pretrained(_a) if push_to_hub: # Upload model and image processor to the hub logger.info("Uploading PyTorch model and image processor to the hub...") model.push_to_hub(f"nielsr/{model_name}") processor.push_to_hub(f"nielsr/{model_name}") if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') a_ = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
76
1
from timeit import timeit def lowerCamelCase__ ( _a): if number < 0: raise ValueError("the value of input must not be negative") SCREAMING_SNAKE_CASE : Any = 0 while number: number &= number - 1 result += 1 return result def lowerCamelCase__ ( _a): if number < 0: raise ValueError("the value of input must not be negative") SCREAMING_SNAKE_CASE : Any = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def lowerCamelCase__ ( ): def do_benchmark(_a) -> None: SCREAMING_SNAKE_CASE : int = "import __main__ as z" print(f"Benchmark when {number = }:") print(f"{get_set_bits_count_using_modulo_operator(_a) = }") SCREAMING_SNAKE_CASE : Tuple = timeit("z.get_set_bits_count_using_modulo_operator(25)" , setup=_a) print(f"timeit() runs in {timing} seconds") print(f"{get_set_bits_count_using_brian_kernighans_algorithm(_a) = }") SCREAMING_SNAKE_CASE : str = timeit( "z.get_set_bits_count_using_brian_kernighans_algorithm(25)" , setup=_a , ) print(f"timeit() runs in {timing} seconds") for number in (25, 37, 58, 0): do_benchmark(_a) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
76
import os def lowerCamelCase__ ( ): with open(os.path.dirname(_a) + "/p022_names.txt") as file: SCREAMING_SNAKE_CASE : List[str] = str(file.readlines()[0]) SCREAMING_SNAKE_CASE : List[Any] = names.replace("\"" , "").split(",") names.sort() SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : Dict = 0 for i, name in enumerate(_a): for letter in name: name_score += ord(_a) - 64 total_score += (i + 1) * name_score SCREAMING_SNAKE_CASE : str = 0 return total_score if __name__ == "__main__": print(solution())
76
1
def lowerCamelCase__ ( _a = 4000000): SCREAMING_SNAKE_CASE : Any = [0, 1] SCREAMING_SNAKE_CASE : Union[str, Any] = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1]) if fib[i + 2] > n: break i += 1 SCREAMING_SNAKE_CASE : List[str] = 0 for j in range(len(_a) - 1): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(F'''{solution() = }''')
76
from collections.abc import Callable import numpy as np def lowerCamelCase__ ( _a , _a , _a , _a , _a): SCREAMING_SNAKE_CASE : Dict = int(np.ceil((x_end - xa) / step_size)) SCREAMING_SNAKE_CASE : Tuple = np.zeros((n + 1,)) SCREAMING_SNAKE_CASE : int = ya SCREAMING_SNAKE_CASE : int = xa for k in range(_a): SCREAMING_SNAKE_CASE : Any = y[k] + step_size * ode_func(_a , y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
76
1
import argparse import requests import torch # pip3 install salesforce-lavis # I'm actually installing a slightly modified version: pip3 install git+https://github.com/nielsrogge/LAVIS.git@fix_lavis_float32 (there's also the fix_lavis branch) # also note: to convert Vicuna checkpoints, we had to include /home/niels/python_projects/checkpoints/FastChat/vicuna-7b in lavis/configs/models/blip2/blip2_instruct_vicuna7b.yaml # same for Vicuna-13b from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipImageProcessor, InstructBlipConfig, InstructBlipForConditionalGeneration, InstructBlipProcessor, InstructBlipQFormerConfig, InstructBlipVisionConfig, LlamaConfig, LlamaTokenizerFast, TaConfig, TaTokenizerFast, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Any = "https://raw.githubusercontent.com/salesforce/LAVIS/main/docs/_static/Confusing-Pictures.jpg" SCREAMING_SNAKE_CASE : Optional[Any] = Image.open(requests.get(_a , stream=_a).raw).convert("RGB") return image def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Union[str, Any] = [] # fmt: off # vision encoder rename_keys.append(("visual_encoder.cls_token", "vision_model.embeddings.class_embedding")) rename_keys.append(("visual_encoder.pos_embed", "vision_model.embeddings.position_embedding")) rename_keys.append(("visual_encoder.patch_embed.proj.weight", "vision_model.embeddings.patch_embedding.weight")) rename_keys.append(("visual_encoder.patch_embed.proj.bias", "vision_model.embeddings.patch_embedding.bias")) rename_keys.append(("ln_vision.weight", "vision_model.post_layernorm.weight")) rename_keys.append(("ln_vision.bias", "vision_model.post_layernorm.bias")) for i in range(config.vision_config.num_hidden_layers): rename_keys.append((f"visual_encoder.blocks.{i}.norm1.weight", f"vision_model.encoder.layers.{i}.layer_norm1.weight")) rename_keys.append((f"visual_encoder.blocks.{i}.norm1.bias", f"vision_model.encoder.layers.{i}.layer_norm1.bias")) rename_keys.append((f"visual_encoder.blocks.{i}.norm2.weight", f"vision_model.encoder.layers.{i}.layer_norm2.weight")) rename_keys.append((f"visual_encoder.blocks.{i}.norm2.bias", f"vision_model.encoder.layers.{i}.layer_norm2.bias")) rename_keys.append((f"visual_encoder.blocks.{i}.attn.qkv.weight", f"vision_model.encoder.layers.{i}.self_attn.qkv.weight")) rename_keys.append((f"visual_encoder.blocks.{i}.attn.proj.weight", f"vision_model.encoder.layers.{i}.self_attn.projection.weight",)) rename_keys.append((f"visual_encoder.blocks.{i}.attn.proj.bias", f"vision_model.encoder.layers.{i}.self_attn.projection.bias")) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc1.weight", f"vision_model.encoder.layers.{i}.mlp.fc1.weight")) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc1.bias", f"vision_model.encoder.layers.{i}.mlp.fc1.bias")) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc2.weight", f"vision_model.encoder.layers.{i}.mlp.fc2.weight")) rename_keys.append((f"visual_encoder.blocks.{i}.mlp.fc2.bias", f"vision_model.encoder.layers.{i}.mlp.fc2.bias")) # QFormer rename_keys.append(("Qformer.bert.embeddings.LayerNorm.weight", "qformer.embeddings.layernorm.weight")) rename_keys.append(("Qformer.bert.embeddings.LayerNorm.bias", "qformer.embeddings.layernorm.bias")) # fmt: on return rename_keys def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : int = dct.pop(_a) SCREAMING_SNAKE_CASE : Union[str, Any] = val def lowerCamelCase__ ( _a , _a): for i in range(config.vision_config.num_hidden_layers): # read in original q and v biases SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(f"visual_encoder.blocks.{i}.attn.q_bias") SCREAMING_SNAKE_CASE : Any = state_dict.pop(f"visual_encoder.blocks.{i}.attn.v_bias") # next, set bias in the state dict SCREAMING_SNAKE_CASE : List[Any] = torch.cat((q_bias, torch.zeros_like(_a , requires_grad=_a), v_bias)) SCREAMING_SNAKE_CASE : Union[str, Any] = qkv_bias def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Tuple = 364 if "coco" in model_name else 224 SCREAMING_SNAKE_CASE : Any = InstructBlipVisionConfig(image_size=_a).to_dict() # make sure the models have proper bos_token_id and eos_token_id set (important for generation) # seems like flan-T5 models don't have bos_token_id properly set? if "t5-xl" in model_name: SCREAMING_SNAKE_CASE : Union[str, Any] = TaConfig.from_pretrained("google/flan-t5-xl" , dense_act_fn="gelu" , bos_token_id=1).to_dict() elif "t5-xxl" in model_name: SCREAMING_SNAKE_CASE : str = TaConfig.from_pretrained("google/flan-t5-xxl" , dense_act_fn="gelu" , bos_token_id=1).to_dict() elif "vicuna-7b" in model_name: SCREAMING_SNAKE_CASE : Dict = LlamaConfig.from_pretrained("decapoda-research/llama-7b-hf" , vocab_size=32001).to_dict() elif "vicuna-13b" in model_name: SCREAMING_SNAKE_CASE : int = LlamaConfig.from_pretrained("decapoda-research/llama-13b-hf" , vocab_size=32001).to_dict() else: raise ValueError("Model name not supported") # the authors add one special "[DEC]" token to the vocab of Q-Former, hence vocab size = 30522 + 1 SCREAMING_SNAKE_CASE : List[str] = InstructBlipQFormerConfig(vocab_size=30523).to_dict() SCREAMING_SNAKE_CASE : Dict = InstructBlipConfig(vision_config=_a , text_config=_a , qformer_config=_a) return config, image_size @torch.no_grad() def lowerCamelCase__ ( _a , _a=None , _a=False): SCREAMING_SNAKE_CASE : Optional[int] = AutoTokenizer.from_pretrained("bert-base-uncased" , truncation_side="left") qformer_tokenizer.add_special_tokens({"bos_token": "[DEC]"}) if "t5" in model_name: SCREAMING_SNAKE_CASE : Union[str, Any] = TaTokenizerFast.from_pretrained("google/flan-t5-xl" , truncation_side="left") elif "vicuna" in model_name: # the following was used in the original implementation: # tokenizer = LlamaTokenizer.from_pretrained("huggyllama/llama-7b", use_fast=False, truncation_side="left") # tokenizer.add_special_tokens({"pad_token": "[PAD]"}) # tokenizer.add_special_tokens({"bos_token": "</s>"}) # tokenizer.add_special_tokens({"eos_token": "</s>"}) # tokenizer.add_special_tokens({"unk_token": "</s>"}) SCREAMING_SNAKE_CASE : List[str] = LlamaTokenizerFast.from_pretrained( "huggyllama/llama-7b" , truncation_side="left" , bos_token="</s>" , unk_token="</s>") tokenizer.add_special_tokens({"pad_token": "[PAD]"}) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[Any] = get_blipa_config(_a) SCREAMING_SNAKE_CASE : int = InstructBlipForConditionalGeneration(_a).eval() SCREAMING_SNAKE_CASE : Dict = { "instructblip-vicuna-7b": ("blip2_vicuna_instruct", "vicuna7b"), "instructblip-vicuna-13b": ("blip2_vicuna_instruct", "vicuna13b"), "instructblip-flan-t5-xl": ("blip2_t5_instruct", "flant5xl"), "instructblip-flan-t5-xxl": ("blip2_t5_instruct", "flant5xxl"), } SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[Any] = model_name_to_original[model_name] # load original model print("Loading original model...") SCREAMING_SNAKE_CASE : List[str] = "cuda:1" if torch.cuda.is_available() else "cpu" SCREAMING_SNAKE_CASE : List[str] = "cuda:2" if torch.cuda.is_available() else "cpu" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[Any] = load_model_and_preprocess( name=_a , model_type=_a , is_eval=_a , device=_a) original_model.eval() print("Done!") # update state dict keys SCREAMING_SNAKE_CASE : Optional[int] = original_model.state_dict() SCREAMING_SNAKE_CASE : str = create_rename_keys(_a) for src, dest in rename_keys: rename_key(_a , _a , _a) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(_a) if key.startswith("Qformer.bert"): SCREAMING_SNAKE_CASE : str = key.replace("Qformer.bert" , "qformer") if "attention.self" in key: SCREAMING_SNAKE_CASE : Any = key.replace("self" , "attention") if "llm_proj" in key: SCREAMING_SNAKE_CASE : List[str] = key.replace("llm_proj" , "language_projection") if "t5_proj" in key: SCREAMING_SNAKE_CASE : Optional[int] = key.replace("t5_proj" , "language_projection") if key.startswith("llm_model"): SCREAMING_SNAKE_CASE : Optional[int] = key.replace("llm_model" , "language_model") if key.startswith("t5"): SCREAMING_SNAKE_CASE : int = key.replace("t5" , "language") SCREAMING_SNAKE_CASE : int = val # read in qv biases read_in_q_v_bias(_a , _a) # note: weights get loaded in torch.float32 by default hf_model.load_state_dict(_a , strict=_a) SCREAMING_SNAKE_CASE : List[str] = load_demo_image() SCREAMING_SNAKE_CASE : int = "What is unusual about this image?" # create processor SCREAMING_SNAKE_CASE : Optional[int] = BlipImageProcessor( size={"height": image_size, "width": image_size} , image_mean=_a , image_std=_a) SCREAMING_SNAKE_CASE : Dict = InstructBlipProcessor( image_processor=_a , tokenizer=_a , qformer_tokenizer=_a , ) SCREAMING_SNAKE_CASE : List[Any] = processor(images=_a , text=_a , return_tensors="pt").to(_a) # make sure processor creates exact same pixel values SCREAMING_SNAKE_CASE : Optional[int] = vis_processors["eval"](_a).unsqueeze(0).to(_a) SCREAMING_SNAKE_CASE : Dict = inputs.pixel_values assert torch.allclose(original_pixel_values.to(pixel_values.device) , _a) original_model.to(_a) hf_model.to(_a) with torch.no_grad(): if "vicuna" in model_name: SCREAMING_SNAKE_CASE : Any = original_model({"image": original_pixel_values, "text_input": [prompt]}).logits SCREAMING_SNAKE_CASE : List[str] = hf_model(**_a).logits else: SCREAMING_SNAKE_CASE : Any = original_model( {"image": original_pixel_values, "text_input": [prompt], "text_output": ["\n"]}).logits SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer("\n" , return_tensors="pt").input_ids.to(_a) SCREAMING_SNAKE_CASE : List[Any] = label_input_ids.masked_fill(label_input_ids == tokenizer.pad_token_id , -100) SCREAMING_SNAKE_CASE : List[Any] = hf_model(**_a , labels=_a).logits print("First values of original logits:" , original_logits[0, :3, :3]) print("First values of HF logits:" , logits[0, :3, :3]) # assert values assert original_logits.shape == logits.shape SCREAMING_SNAKE_CASE : Optional[int] = 1E-4 if "vicuna" in model_name else 1E-5 assert torch.allclose(original_logits.to(logits.device) , _a , atol=_a) print("Looks ok!") print("Generating with original model...") SCREAMING_SNAKE_CASE : List[Any] = original_model.generate({"image": original_pixel_values, "prompt": prompt} , num_beams=5) # important: we need to cast the weights of the HF model to the appropriate type print("Generating with HF model...") SCREAMING_SNAKE_CASE : int = hf_model.generate( **_a , do_sample=_a , num_beams=5 , max_length=256 , min_length=1 , top_p=0.9 , repetition_penalty=1.5 , length_penalty=1.0 , temperature=1 , ) if "vicuna" in model_name: # convert output id 0 to 2 (eos_token_id) # TODO add this in the generate method? SCREAMING_SNAKE_CASE : Optional[int] = 2 print("Original generation:" , _a) SCREAMING_SNAKE_CASE : List[str] = processor.batch_decode(_a , skip_special_tokens=_a) SCREAMING_SNAKE_CASE : Optional[int] = [text.strip() for text in output_text] print("HF generation:" , _a) if pytorch_dump_folder_path is not None: processor.save_pretrained(_a) hf_model.save_pretrained(_a) if push_to_hub: processor.push_to_hub(f"Salesforce/{model_name}") hf_model.push_to_hub(f"Salesforce/{model_name}") if __name__ == "__main__": a_ = argparse.ArgumentParser() a_ = [ 'instructblip-vicuna-7b', 'instructblip-vicuna-13b', 'instructblip-flan-t5-xl', 'instructblip-flan-t5-xxl', ] parser.add_argument( '--model_name', default='instructblip-flan-t5-xl', choices=choices, type=str, help='Path to hf config.json of model to convert', ) parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model and processor to the hub after converting', ) a_ = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
76
def lowerCamelCase__ ( _a , _a): return int((input_a, input_a).count(1) != 0) def lowerCamelCase__ ( ): assert or_gate(0 , 0) == 0 assert or_gate(0 , 1) == 1 assert or_gate(1 , 0) == 1 assert or_gate(1 , 1) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
76
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 a_ = random.Random() def lowerCamelCase__ ( _a , _a=1.0 , _a=None , _a=None): if rng is None: SCREAMING_SNAKE_CASE : int = global_rng SCREAMING_SNAKE_CASE : Tuple = [] for batch_idx in range(shape[0]): values.append([]) for _ in range(shape[1]): values[-1].append(rng.random() * scale) return values class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[str] , a : Any , a : Dict=7 , a : int=400 , a : Tuple=2000 , a : Union[str, Any]=2048 , a : Dict=128 , a : Union[str, Any]=1 , a : List[Any]=512 , a : Any=30 , a : int=4_4100 , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : Optional[int] = min_seq_length SCREAMING_SNAKE_CASE : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE : List[Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE : Optional[int] = spectrogram_length SCREAMING_SNAKE_CASE : List[Any] = feature_size SCREAMING_SNAKE_CASE : int = num_audio_channels SCREAMING_SNAKE_CASE : Union[str, Any] = hop_length SCREAMING_SNAKE_CASE : Optional[int] = chunk_length SCREAMING_SNAKE_CASE : str = sampling_rate def __UpperCamelCase ( self : Optional[Any] ) -> 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 __UpperCamelCase ( self : List[Any] , a : List[str]=False , a : Dict=False ) -> Any: """simple docstring""" def _flatten(a : Optional[Any] ): return list(itertools.chain(*a ) ) if equal_length: SCREAMING_SNAKE_CASE : Dict = [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 : Any = [ 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 : Any = [np.asarray(a ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =TvltFeatureExtractor def __UpperCamelCase ( self : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : int = TvltFeatureExtractionTester(self ) def __UpperCamelCase ( self : Any ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = 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 __UpperCamelCase ( self : Optional[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : str = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Tuple = feat_extract_first.save_pretrained(a )[0] check_json_file_has_correct_format(a ) SCREAMING_SNAKE_CASE : List[str] = self.feature_extraction_class.from_pretrained(a ) SCREAMING_SNAKE_CASE : str = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : List[str] = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Tuple = 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 __UpperCamelCase ( self : int ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(a , "feat_extract.json" ) feat_extract_first.to_json_file(a ) SCREAMING_SNAKE_CASE : List[Any] = self.feature_extraction_class.from_json_file(a ) SCREAMING_SNAKE_CASE : int = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE : Tuple = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE : Dict = 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 __UpperCamelCase ( self : int ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE : List[Any] = [np.asarray(a ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE : int = 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 : List[str] = 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 : Optional[int] = 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 : int = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(a ) SCREAMING_SNAKE_CASE : Union[str, 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 __UpperCamelCase ( self : Tuple , a : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : str = load_dataset("hf-internal-testing/librispeech_asr_dummy" , "clean" , split="validation" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE : List[str] = ds.sort("id" ).select(range(a ) )[:num_samples]["audio"] return [x["array"] for x in speech_samples] def __UpperCamelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE : Optional[Any] = TvltFeatureExtractor() SCREAMING_SNAKE_CASE : Optional[int] = feature_extractor(a , return_tensors="pt" ).audio_values self.assertEquals(audio_values.shape , (1, 1, 192, 128) ) SCREAMING_SNAKE_CASE : List[str] = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , a , atol=1e-4 ) )
76
a_ = 8.314_4598 def lowerCamelCase__ ( _a , _a): if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example a_ = 300 a_ = 28 a_ = rms_speed_of_molecule(temperature, molar_mass) print(F'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
76
1
import operator as op a_ = 'scaler.pt' a_ = 'pytorch_model' a_ = 'random_states' a_ = 'optimizer' a_ = 'scheduler' a_ = 'pytorch_model.bin' a_ = 'pytorch_model.bin.index.json' a_ = 'model.safetensors' a_ = 'model.safetensors.index.json' a_ = '1.10.2' a_ = 'py38' a_ = '4.17.0' a_ = ['ml.p3.16xlarge', 'ml.p3dn.24xlarge', 'ml.p4dn.24xlarge'] a_ = ['FULL_SHARD', 'SHARD_GRAD_OP', 'NO_SHARD', 'HYBRID_SHARD', 'HYBRID_SHARD_ZERO2'] a_ = ['TRANSFORMER_BASED_WRAP', 'SIZE_BASED_WRAP', 'NO_WRAP'] a_ = ['BACKWARD_PRE', 'BACKWARD_POST', 'NO_PREFETCH'] a_ = ['FULL_STATE_DICT', 'LOCAL_STATE_DICT', 'SHARDED_STATE_DICT'] a_ = '2.0.1' a_ = ['pdsh', 'standard', 'openmpi', 'mvapich'] a_ = ['default', 'reduce-overhead', 'max-autotune'] a_ = {'>': op.gt, '>=': op.ge, '==': op.eq, '!=': op.ne, '<=': op.le, '<': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 a_ = [ 'nnodes', 'nproc_per_node', 'rdzv_backend', 'rdzv_endpoint', 'rdzv_id', 'rdzv_conf', 'standalone', 'max_restarts', 'monitor_interval', 'start_method', 'role', 'module', 'm', 'no_python', 'run_path', 'log_dir', 'r', 'redirects', 't', 'tee', 'node_rank', 'master_addr', 'master_port', ] a_ = ['DEEPSPEED', 'MULTI_GPU', 'FSDP', 'MEGATRON_LM'] a_ = ['DEEPSPEED', 'MULTI_XPU', 'FSDP']
76
a_ = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : int = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE : int = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE : Optional[int] = queue.pop(0) # get the last node from the path SCREAMING_SNAKE_CASE : Union[str, Any] = path[-1] if node not in explored: SCREAMING_SNAKE_CASE : List[str] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE : List[Any] = list(_a) new_path.append(_a) queue.append(_a) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_a) # in case there's no path between the 2 nodes return [] def lowerCamelCase__ ( _a , _a , _a): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE : str = [start] SCREAMING_SNAKE_CASE : Optional[Any] = set(_a) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE : Union[str, Any] = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE : Optional[int] = queue.pop(0) if node == target: SCREAMING_SNAKE_CASE : Union[str, Any] = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node]) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_a) queue.append(_a) SCREAMING_SNAKE_CASE : Optional[Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, 'G', 'D')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, 'G', 'D')) # returns 4
76
1
from __future__ import annotations def lowerCamelCase__ ( _a , _a): print(f"Vertex\tShortest Distance from vertex {src}") for i, d in enumerate(_a): print(f"{i}\t\t{d}") def lowerCamelCase__ ( _a , _a , _a): for j in range(_a): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Tuple = (graph[j][k] for k in ["src", "dst", "weight"]) if distance[u] != float("inf") and distance[u] + w < distance[v]: return True return False def lowerCamelCase__ ( _a , _a , _a , _a): SCREAMING_SNAKE_CASE : Union[str, Any] = [float("inf")] * vertex_count SCREAMING_SNAKE_CASE : Optional[Any] = 0.0 for _ in range(vertex_count - 1): for j in range(_a): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[Any] = (graph[j][k] for k in ["src", "dst", "weight"]) if distance[u] != float("inf") and distance[u] + w < distance[v]: SCREAMING_SNAKE_CASE : Any = distance[u] + w SCREAMING_SNAKE_CASE : List[str] = check_negative_cycle(_a , _a , _a) if negative_cycle_exists: raise Exception("Negative cycle found") return distance if __name__ == "__main__": import doctest doctest.testmod() a_ = int(input('Enter number of vertices: ').strip()) a_ = int(input('Enter number of edges: ').strip()) a_ = [{} for _ in range(E)] for i in range(E): print('Edge ', i + 1) a_ , a_ , a_ = ( int(x) for x in input('Enter source, destination, weight: ').strip().split(' ') ) a_ = {'src': src, 'dst': dest, 'weight': weight} a_ = int(input('\nEnter shortest path source:').strip()) a_ = bellman_ford(graph, V, E, source) print_distance(shortest_distance, 0)
76
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE : Tuple = tokenizer("Hello there" , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer("Hi I am" , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE : str = model(a , labels=a ).loss SCREAMING_SNAKE_CASE : Any = -tf.math.reduce_mean(a ).numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = -21.22_8168 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2e-4 )
76
1
from __future__ import annotations from typing import Any class _UpperCamelCase : '''simple docstring''' def __init__( self : Any , a : int = 6 ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None self.create_linked_list(a ) def __UpperCamelCase ( self : List[str] , a : int ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : int = Node() SCREAMING_SNAKE_CASE : int = current_node SCREAMING_SNAKE_CASE : str = current_node SCREAMING_SNAKE_CASE : Any = current_node for _ in range(1 , a ): SCREAMING_SNAKE_CASE : str = Node() SCREAMING_SNAKE_CASE : List[Any] = current_node SCREAMING_SNAKE_CASE : Optional[Any] = previous_node SCREAMING_SNAKE_CASE : Optional[Any] = current_node SCREAMING_SNAKE_CASE : Any = self.front SCREAMING_SNAKE_CASE : Dict = previous_node def __UpperCamelCase ( self : Tuple ) -> bool: """simple docstring""" return ( self.front == self.rear and self.front is not None and self.front.data is None ) def __UpperCamelCase ( self : Tuple ) -> Any | None: """simple docstring""" self.check_can_perform_operation() return self.front.data if self.front else None def __UpperCamelCase ( self : Optional[int] , a : Any ) -> None: """simple docstring""" if self.rear is None: return self.check_is_full() if not self.is_empty(): SCREAMING_SNAKE_CASE : Any = self.rear.next if self.rear: SCREAMING_SNAKE_CASE : Optional[Any] = data def __UpperCamelCase ( self : List[Any] ) -> Any: """simple docstring""" self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: SCREAMING_SNAKE_CASE : List[Any] = self.front.data SCREAMING_SNAKE_CASE : Optional[int] = None return data SCREAMING_SNAKE_CASE : Optional[Any] = self.front SCREAMING_SNAKE_CASE : Any = old_front.next SCREAMING_SNAKE_CASE : Dict = old_front.data SCREAMING_SNAKE_CASE : Tuple = None return data def __UpperCamelCase ( self : List[str] ) -> None: """simple docstring""" if self.is_empty(): raise Exception("Empty Queue" ) def __UpperCamelCase ( self : Dict ) -> None: """simple docstring""" if self.rear and self.rear.next == self.front: raise Exception("Full Queue" ) class _UpperCamelCase : '''simple docstring''' def __init__( self : Dict ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : Any | None = None SCREAMING_SNAKE_CASE : Node | None = None SCREAMING_SNAKE_CASE : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
76
from math import factorial def lowerCamelCase__ ( _a , _a , _a): if successes > trials: raise ValueError("successes must be lower or equal to trials") if trials < 0 or successes < 0: raise ValueError("the function is defined for non-negative integers") if not isinstance(_a , _a) or not isinstance(_a , _a): raise ValueError("the function is defined for non-negative integers") if not 0 < prob < 1: raise ValueError("prob has to be in range of 1 - 0") SCREAMING_SNAKE_CASE : int = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! SCREAMING_SNAKE_CASE : List[Any] = float(factorial(_a)) coefficient /= factorial(_a) * factorial(trials - successes) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
76
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ = { 'configuration_roformer': ['ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RoFormerConfig', 'RoFormerOnnxConfig'], 'tokenization_roformer': ['RoFormerTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['RoFormerTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'RoFormerForCausalLM', 'RoFormerForMaskedLM', 'RoFormerForMultipleChoice', 'RoFormerForQuestionAnswering', 'RoFormerForSequenceClassification', 'RoFormerForTokenClassification', 'RoFormerLayer', 'RoFormerModel', 'RoFormerPreTrainedModel', 'load_tf_weights_in_roformer', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFRoFormerForCausalLM', 'TFRoFormerForMaskedLM', 'TFRoFormerForMultipleChoice', 'TFRoFormerForQuestionAnswering', 'TFRoFormerForSequenceClassification', 'TFRoFormerForTokenClassification', 'TFRoFormerLayer', 'TFRoFormerModel', 'TFRoFormerPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'FlaxRoFormerForMaskedLM', 'FlaxRoFormerForMultipleChoice', 'FlaxRoFormerForQuestionAnswering', 'FlaxRoFormerForSequenceClassification', 'FlaxRoFormerForTokenClassification', 'FlaxRoFormerModel', 'FlaxRoFormerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_roformer import ROFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, RoFormerConfig, RoFormerOnnxConfig from .tokenization_roformer import RoFormerTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_roformer_fast import RoFormerTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_roformer import ( ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, RoFormerForCausalLM, RoFormerForMaskedLM, RoFormerForMultipleChoice, RoFormerForQuestionAnswering, RoFormerForSequenceClassification, RoFormerForTokenClassification, RoFormerLayer, RoFormerModel, RoFormerPreTrainedModel, load_tf_weights_in_roformer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_roformer import ( TF_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFRoFormerForCausalLM, TFRoFormerForMaskedLM, TFRoFormerForMultipleChoice, TFRoFormerForQuestionAnswering, TFRoFormerForSequenceClassification, TFRoFormerForTokenClassification, TFRoFormerLayer, TFRoFormerModel, TFRoFormerPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_roformer import ( FLAX_ROFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, FlaxRoFormerPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =CustomTokenizer pass
76
1
import os from pickle import UnpicklingError from typing import Dict, Tuple import jax import jax.numpy as jnp import numpy as np from flax.serialization import from_bytes from flax.traverse_util import flatten_dict, unflatten_dict import transformers from .utils import logging a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a , _a , _a , _a=False): try: import torch # noqa: F401 except ImportError: logger.error( "Loading a PyTorch model in Flax, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions.") raise if not is_sharded: SCREAMING_SNAKE_CASE : str = os.path.abspath(_a) logger.info(f"Loading PyTorch weights from {pt_path}") SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(_a , map_location="cpu") logger.info(f"PyTorch checkpoint contains {sum(t.numel() for t in pt_state_dict.values()):,} parameters.") SCREAMING_SNAKE_CASE : str = convert_pytorch_state_dict_to_flax(_a , _a) else: # model is sharded and pytorch_checkpoint_path already contains the list of .pt shard files SCREAMING_SNAKE_CASE : List[str] = convert_pytorch_sharded_state_dict_to_flax(_a , _a) return flax_state_dict def lowerCamelCase__ ( _a , _a , _a , _a , ): def is_key_or_prefix_key_in_dict(_a) -> bool: return len(set(_a) & {key, (model_prefix,) + key}) > 0 # layer norm SCREAMING_SNAKE_CASE : Dict = pt_tuple_key[:-1] + ("scale",) if pt_tuple_key[-1] in ["weight", "gamma"] and is_key_or_prefix_key_in_dict(_a): return renamed_pt_tuple_key, pt_tensor # batch norm layer mean SCREAMING_SNAKE_CASE : Tuple = pt_tuple_key[:-1] + ("mean",) if pt_tuple_key[-1] == "running_mean" and not is_key_or_prefix_key_in_dict(_a): return renamed_pt_tuple_key, pt_tensor # batch norm layer var SCREAMING_SNAKE_CASE : List[str] = pt_tuple_key[:-1] + ("var",) if pt_tuple_key[-1] == "running_var" and not is_key_or_prefix_key_in_dict(_a): return renamed_pt_tuple_key, pt_tensor # embedding SCREAMING_SNAKE_CASE : int = pt_tuple_key[:-1] + ("embedding",) if pt_tuple_key[-1] == "weight" and is_key_or_prefix_key_in_dict(_a): return renamed_pt_tuple_key, pt_tensor # conv layer SCREAMING_SNAKE_CASE : Any = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4 and not is_key_or_prefix_key_in_dict(_a): SCREAMING_SNAKE_CASE : Optional[int] = pt_tensor.transpose(2 , 3 , 1 , 0) return renamed_pt_tuple_key, pt_tensor # linear layer SCREAMING_SNAKE_CASE : Union[str, Any] = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and not is_key_or_prefix_key_in_dict(_a): SCREAMING_SNAKE_CASE : Tuple = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight SCREAMING_SNAKE_CASE : Dict = pt_tuple_key[:-1] + ("weight",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias SCREAMING_SNAKE_CASE : List[str] = pt_tuple_key[:-1] + ("bias",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 SCREAMING_SNAKE_CASE : Optional[int] = None if pt_tuple_key[-3::2] == ("parametrizations", "original0"): SCREAMING_SNAKE_CASE : List[str] = pt_tuple_key[-2] + "_g" elif pt_tuple_key[-3::2] == ("parametrizations", "original1"): SCREAMING_SNAKE_CASE : Any = pt_tuple_key[-2] + "_v" if name is not None: SCREAMING_SNAKE_CASE : str = pt_tuple_key[:-3] + (name,) return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def lowerCamelCase__ ( _a , _a): # convert pytorch tensor to numpy SCREAMING_SNAKE_CASE : int = {k: v.numpy() for k, v in pt_state_dict.items()} SCREAMING_SNAKE_CASE : List[Any] = flax_model.base_model_prefix # use params dict if the model contains batch norm layers if "params" in flax_model.params: SCREAMING_SNAKE_CASE : Dict = flax_model.params["params"] else: SCREAMING_SNAKE_CASE : Union[str, Any] = flax_model.params SCREAMING_SNAKE_CASE : Optional[Any] = flatten_dict(_a) # add batch_stats keys,values to dict if "batch_stats" in flax_model.params: SCREAMING_SNAKE_CASE : int = flatten_dict(flax_model.params["batch_stats"]) random_flax_state_dict.update(_a) SCREAMING_SNAKE_CASE : Dict = {} SCREAMING_SNAKE_CASE : int = (model_prefix not in flax_model_params) and ( model_prefix in {k.split(".")[0] for k in pt_state_dict.keys()} ) SCREAMING_SNAKE_CASE : Union[str, Any] = (model_prefix in flax_model_params) and ( model_prefix not in {k.split(".")[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE : Optional[int] = tuple(pt_key.split(".")) # remove base model prefix if necessary SCREAMING_SNAKE_CASE : Dict = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE : Dict = pt_tuple_key[1:] # Correctly rename weight parameters SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = rename_key_and_reshape_tensor( _a , _a , _a , _a) # add model prefix if necessary SCREAMING_SNAKE_CASE : Optional[Any] = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE : Any = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.") # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1] or "var" in flax_key[-1]: SCREAMING_SNAKE_CASE : Dict = jnp.asarray(_a) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(_a , _a) continue # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE : List[Any] = jnp.asarray(_a) else: # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE : str = jnp.asarray(_a) return unflatten_dict(_a) def lowerCamelCase__ ( _a , _a): import torch # Load the index SCREAMING_SNAKE_CASE : int = {} for shard_file in shard_filenames: # load using msgpack utils SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(_a) SCREAMING_SNAKE_CASE : Tuple = {k: v.numpy() for k, v in pt_state_dict.items()} SCREAMING_SNAKE_CASE : Tuple = flax_model.base_model_prefix # use params dict if the model contains batch norm layers and then add batch_stats keys,values to dict if "batch_stats" in flax_model.params: SCREAMING_SNAKE_CASE : str = flax_model.params["params"] SCREAMING_SNAKE_CASE : Union[str, Any] = flatten_dict(_a) random_flax_state_dict.update(flatten_dict(flax_model.params["batch_stats"])) else: SCREAMING_SNAKE_CASE : Any = flax_model.params SCREAMING_SNAKE_CASE : Tuple = flatten_dict(_a) SCREAMING_SNAKE_CASE : List[Any] = (model_prefix not in flax_model_params) and ( model_prefix in {k.split(".")[0] for k in pt_state_dict.keys()} ) SCREAMING_SNAKE_CASE : Union[str, Any] = (model_prefix in flax_model_params) and ( model_prefix not in {k.split(".")[0] for k in pt_state_dict.keys()} ) # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE : int = tuple(pt_key.split(".")) # remove base model prefix if necessary SCREAMING_SNAKE_CASE : Optional[int] = pt_tuple_key[0] == model_prefix if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE : Tuple = pt_tuple_key[1:] # Correctly rename weight parameters SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = rename_key_and_reshape_tensor( _a , _a , _a , _a) # add model prefix if necessary SCREAMING_SNAKE_CASE : Optional[int] = (model_prefix,) + flax_key in random_flax_state_dict if load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE : Optional[Any] = (model_prefix,) + flax_key if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.") # add batch stats if the model contains batchnorm layers if "batch_stats" in flax_model.params: if "mean" in flax_key[-1]: SCREAMING_SNAKE_CASE : Dict = jnp.asarray(_a) continue if "var" in flax_key[-1]: SCREAMING_SNAKE_CASE : Tuple = jnp.asarray(_a) continue # remove num_batches_tracked key if "num_batches_tracked" in flax_key[-1]: flax_state_dict.pop(_a , _a) continue # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE : int = jnp.asarray(_a) else: # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE : str = jnp.asarray(_a) return unflatten_dict(_a) def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : str = os.path.abspath(_a) logger.info(f"Loading Flax weights from {flax_checkpoint_path}") # import correct flax class SCREAMING_SNAKE_CASE : int = getattr(_a , "Flax" + model.__class__.__name__) # load flax weight dict with open(_a , "rb") as state_f: try: SCREAMING_SNAKE_CASE : str = from_bytes(_a , state_f.read()) except UnpicklingError: raise EnvironmentError(f"Unable to convert {flax_checkpoint_path} to Flax deserializable object. ") return load_flax_weights_in_pytorch_model(_a , _a) def lowerCamelCase__ ( _a , _a): try: import torch # noqa: F401 except ImportError: logger.error( "Loading a Flax weights in PyTorch, requires both PyTorch and Flax to be installed. Please see" " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation" " instructions.") raise # check if we have bf16 weights SCREAMING_SNAKE_CASE : int = flatten_dict(jax.tree_util.tree_map(lambda _a: x.dtype == jnp.bfloataa , _a)).values() if any(_a): # convert all weights to fp32 if the are bf16 since torch.from_numpy can-not handle bf16 # and bf16 is not fully supported in PT yet. logger.warning( "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` " "before loading those in PyTorch model.") SCREAMING_SNAKE_CASE : Optional[Any] = jax.tree_util.tree_map( lambda _a: params.astype(np.floataa) if params.dtype == jnp.bfloataa else params , _a) SCREAMING_SNAKE_CASE : Optional[Any] = flatten_dict(_a) SCREAMING_SNAKE_CASE : Optional[int] = pt_model.state_dict() SCREAMING_SNAKE_CASE : Union[str, Any] = (pt_model.base_model_prefix in flax_state) and ( pt_model.base_model_prefix not in {k.split(".")[0] for k in pt_model_dict.keys()} ) SCREAMING_SNAKE_CASE : Dict = (pt_model.base_model_prefix not in flax_state) and ( pt_model.base_model_prefix in {k.split(".")[0] for k in pt_model_dict.keys()} ) # keep track of unexpected & missing keys SCREAMING_SNAKE_CASE : int = [] SCREAMING_SNAKE_CASE : int = set(pt_model_dict.keys()) for flax_key_tuple, flax_tensor in flax_state_dict.items(): SCREAMING_SNAKE_CASE : Dict = flax_key_tuple[0] == pt_model.base_model_prefix SCREAMING_SNAKE_CASE : Union[str, Any] = ".".join((pt_model.base_model_prefix,) + flax_key_tuple) in pt_model_dict # adapt flax_key to prepare for loading from/to base model only if load_model_with_head_into_base_model and has_base_model_prefix: SCREAMING_SNAKE_CASE : Union[str, Any] = flax_key_tuple[1:] elif load_base_model_into_model_with_head and require_base_model_prefix: SCREAMING_SNAKE_CASE : Tuple = (pt_model.base_model_prefix,) + flax_key_tuple # rename flax weights to PyTorch format if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 4 and ".".join(_a) not in pt_model_dict: # conv layer SCREAMING_SNAKE_CASE : List[str] = flax_key_tuple[:-1] + ("weight",) SCREAMING_SNAKE_CASE : Tuple = jnp.transpose(_a , (3, 2, 0, 1)) elif flax_key_tuple[-1] == "kernel" and ".".join(_a) not in pt_model_dict: # linear layer SCREAMING_SNAKE_CASE : int = flax_key_tuple[:-1] + ("weight",) SCREAMING_SNAKE_CASE : Any = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: SCREAMING_SNAKE_CASE : Union[str, Any] = flax_key_tuple[:-1] + ("weight",) # adding batch stats from flax batch norm to pt elif "mean" in flax_key_tuple[-1]: SCREAMING_SNAKE_CASE : Union[str, Any] = flax_key_tuple[:-1] + ("running_mean",) elif "var" in flax_key_tuple[-1]: SCREAMING_SNAKE_CASE : Union[str, Any] = flax_key_tuple[:-1] + ("running_var",) if "batch_stats" in flax_state: SCREAMING_SNAKE_CASE : Dict = ".".join(flax_key_tuple[1:]) # Remove the params/batch_stats header else: SCREAMING_SNAKE_CASE : List[str] = ".".join(_a) # We also need to look at `pt_model_dict` and see if there are keys requiring further transformation. SCREAMING_SNAKE_CASE : Optional[int] = {} # New `weight_norm` from https://github.com/huggingface/transformers/pull/24030 for key in pt_model_dict: SCREAMING_SNAKE_CASE : int = key.split(".") SCREAMING_SNAKE_CASE : int = None if key_components[-3::2] == ["parametrizations", "original0"]: SCREAMING_SNAKE_CASE : Union[str, Any] = key_components[-2] + "_g" elif key_components[-3::2] == ["parametrizations", "original1"]: SCREAMING_SNAKE_CASE : Dict = key_components[-2] + "_v" if name is not None: SCREAMING_SNAKE_CASE : Optional[int] = key_components[:-3] + [name] SCREAMING_SNAKE_CASE : List[str] = ".".join(_a) SCREAMING_SNAKE_CASE : str = key if flax_key in special_pt_names: SCREAMING_SNAKE_CASE : Optional[Any] = special_pt_names[flax_key] if flax_key in pt_model_dict: if flax_tensor.shape != pt_model_dict[flax_key].shape: raise ValueError( f"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected " f"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}.") else: # add weight to pytorch dict SCREAMING_SNAKE_CASE : Dict = np.asarray(_a) if not isinstance(_a , np.ndarray) else flax_tensor SCREAMING_SNAKE_CASE : int = torch.from_numpy(_a) # remove from missing keys missing_keys.remove(_a) else: # weight is not expected by PyTorch model unexpected_keys.append(_a) pt_model.load_state_dict(_a) # re-transform missing_keys to list SCREAMING_SNAKE_CASE : str = list(_a) if len(_a) > 0: logger.warning( "Some weights of the Flax model were not used when initializing the PyTorch model" f" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing" f" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture" " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This" f" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect" " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a" " FlaxBertForSequenceClassification model).") else: logger.warning(f"All Flax model weights were used when initializing {pt_model.__class__.__name__}.\n") if len(_a) > 0: logger.warning( f"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly" f" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to" " use it for predictions and inference.") else: logger.warning( f"All the weights of {pt_model.__class__.__name__} were initialized from the Flax model.\n" "If your task is similar to the task the model of the checkpoint was trained on, " f"you can already use {pt_model.__class__.__name__} for predictions without further training.") return pt_model
76
import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex a_ = logging.getLogger(__name__) class _UpperCamelCase : '''simple docstring''' def __init__( self : Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = False def __UpperCamelCase ( self : str , a : str , a : Optional[int] , a : Any , a : str ) -> List[Any]: """simple docstring""" if not self.initialized: SCREAMING_SNAKE_CASE : List[str] = RagRetriever( a , question_encoder_tokenizer=a , generator_tokenizer=a , index=a , init_retrieval=a , ) SCREAMING_SNAKE_CASE : Optional[int] = True def __UpperCamelCase ( self : List[str] ) -> Optional[int]: """simple docstring""" self.retriever.index.init_index() def __UpperCamelCase ( self : Optional[Any] , a : List[Any] , a : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = self.retriever._main_retrieve(a , a ) return doc_ids, retrieved_doc_embeds class _UpperCamelCase ( __A ): '''simple docstring''' def __init__( self : Tuple , a : Any , a : Tuple , a : Tuple , a : Tuple , a : List[Any]=None ) -> Optional[int]: """simple docstring""" if index is not None and index.is_initialized() and len(a ) > 0: raise ValueError( "When using Ray for distributed fine-tuning, " "you'll need to provide the paths instead, " "as the dataset and the index are loaded " "separately. More info in examples/rag/use_own_knowledge_dataset.py " ) super().__init__( a , question_encoder_tokenizer=a , generator_tokenizer=a , index=a , init_retrieval=a , ) SCREAMING_SNAKE_CASE : Optional[Any] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(a , a , a , a ) for worker in self.retrieval_workers ] ) def __UpperCamelCase ( self : Any ) -> Dict: """simple docstring""" logger.info("initializing retrieval" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __UpperCamelCase ( self : Tuple , a : Optional[int] , a : Any ) -> int: """simple docstring""" if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. SCREAMING_SNAKE_CASE : Optional[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = ray.get(random_worker.retrieve.remote(a , a ) ) else: SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Any = self._main_retrieve(a , a ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(a ) @classmethod def __UpperCamelCase ( cls : str , a : Optional[Any] , a : Any=None , **a : List[Any] ) -> str: """simple docstring""" return super(a , cls ).get_tokenizers(a , a , **a ) @classmethod def __UpperCamelCase ( cls : Union[str, Any] , a : int , a : Any , a : List[Any]=None , **a : Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : str = kwargs.pop("config" , a ) or RagConfig.from_pretrained(a , **a ) SCREAMING_SNAKE_CASE : List[Any] = RagTokenizer.from_pretrained(a , config=a ) SCREAMING_SNAKE_CASE : List[Any] = rag_tokenizer.question_encoder SCREAMING_SNAKE_CASE : List[Any] = rag_tokenizer.generator if indexed_dataset is not None: SCREAMING_SNAKE_CASE : str = "custom" SCREAMING_SNAKE_CASE : List[Any] = CustomHFIndex(config.retrieval_vector_size , a ) else: SCREAMING_SNAKE_CASE : List[str] = cls._build_index(a ) return cls( a , question_encoder_tokenizer=a , generator_tokenizer=a , retrieval_workers=a , index=a , )
76
1
import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch a_ = True except ImportError: a_ = False try: from torch.hub import _get_torch_home a_ = _get_torch_home() except ImportError: a_ = os.path.expanduser( os.getenv('TORCH_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'torch')) ) a_ = os.path.join(torch_cache_home, 'transformers') a_ = 'https://cdn.huggingface.co' a_ = 'https://s3.amazonaws.com/models.huggingface.co/bert' a_ = '/'.join(str(Path(__file__).resolve()).split('/')[:-1]) a_ = os.path.join(PATH, 'config.yaml') a_ = os.path.join(PATH, 'attributes.txt') a_ = os.path.join(PATH, 'objects.txt') a_ = os.getenv('PYTORCH_PRETRAINED_BERT_CACHE', default_cache_path) a_ = os.getenv('PYTORCH_TRANSFORMERS_CACHE', PYTORCH_PRETRAINED_BERT_CACHE) a_ = os.getenv('TRANSFORMERS_CACHE', PYTORCH_TRANSFORMERS_CACHE) a_ = 'pytorch_model.bin' a_ = 'config.yaml' def lowerCamelCase__ ( _a=OBJECTS , _a=ATTRIBUTES): SCREAMING_SNAKE_CASE : Tuple = [] with open(_a) as f: for object in f.readlines(): vg_classes.append(object.split(",")[0].lower().strip()) SCREAMING_SNAKE_CASE : Optional[Any] = [] with open(_a) as f: for object in f.readlines(): vg_attrs.append(object.split(",")[0].lower().strip()) return vg_classes, vg_attrs def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Optional[Any] = OrderedDict() with open(_a , "rb") as f: SCREAMING_SNAKE_CASE : Optional[int] = pkl.load(_a)["model"] for k in copy.deepcopy(list(ckp.keys())): SCREAMING_SNAKE_CASE : str = ckp.pop(_a) if isinstance(_a , np.ndarray): SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(_a) else: assert isinstance(_a , torch.tensor), type(_a) SCREAMING_SNAKE_CASE : List[str] = v return r class _UpperCamelCase : '''simple docstring''' lowerCamelCase__ ={} def __init__( self : str , a : dict , a : str = "root" , a : Dict=0 ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Any = name SCREAMING_SNAKE_CASE : Any = level SCREAMING_SNAKE_CASE : Optional[Any] = {} for k, v in dictionary.items(): if v is None: raise ValueError() SCREAMING_SNAKE_CASE : Any = copy.deepcopy(a ) SCREAMING_SNAKE_CASE : Optional[Any] = copy.deepcopy(a ) if isinstance(a , a ): SCREAMING_SNAKE_CASE : List[Any] = Config(a , name=a , level=level + 1 ) SCREAMING_SNAKE_CASE : Any = v setattr(self , a , a ) SCREAMING_SNAKE_CASE : List[Any] = d def __repr__( self : Union[str, Any] ) -> Any: """simple docstring""" return str(list((self._pointer.keys()) ) ) def __setattr__( self : Optional[Any] , a : List[Any] , a : Optional[Any] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = val SCREAMING_SNAKE_CASE : Tuple = val SCREAMING_SNAKE_CASE : Optional[Any] = key.split("." ) SCREAMING_SNAKE_CASE : str = len(a ) - 1 SCREAMING_SNAKE_CASE : List[str] = self._pointer if len(a ) > 1: for i, l in enumerate(a ): if hasattr(self , a ) and isinstance(getattr(self , a ) , a ): setattr(getattr(self , a ) , ".".join(levels[i:] ) , a ) if l == last_level: SCREAMING_SNAKE_CASE : int = val else: SCREAMING_SNAKE_CASE : Dict = pointer[l] def __UpperCamelCase ( self : List[Any] ) -> Tuple: """simple docstring""" return self._pointer def __UpperCamelCase ( self : List[Any] , a : Optional[Any] , a : Optional[int] ) -> Optional[int]: """simple docstring""" with open(F"{file_name}" , "w" ) as stream: dump(a , a ) def __UpperCamelCase ( self : str , a : int , a : int ) -> Union[str, Any]: """simple docstring""" with open(F"{file_name}" , "w" ) as stream: json.dump(a , a ) @staticmethod def __UpperCamelCase ( a : Any ) -> str: """simple docstring""" with open(a ) as stream: SCREAMING_SNAKE_CASE : Dict = load(a , Loader=a ) return data def __str__( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = " " if self._name != "root": SCREAMING_SNAKE_CASE : Optional[int] = F"{t * (self._level-1)}{self._name}:\n" else: SCREAMING_SNAKE_CASE : Any = "" SCREAMING_SNAKE_CASE : Union[str, Any] = self._level for i, (k, v) in enumerate(self._pointer.items() ): if isinstance(a , a ): r += F"{t * (self._level)}{v}\n" self._level += 1 else: r += F"{t * (self._level)}{k}: {v} ({type(a ).__name__})\n" SCREAMING_SNAKE_CASE : Union[str, Any] = level return r[:-1] @classmethod def __UpperCamelCase ( cls : Optional[int] , a : str , **a : List[str] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = cls.get_config_dict(a , **a ) return cls(a ) @classmethod def __UpperCamelCase ( cls : Optional[int] , a : str , **a : int ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = kwargs.pop("cache_dir" , a ) SCREAMING_SNAKE_CASE : Any = kwargs.pop("force_download" , a ) SCREAMING_SNAKE_CASE : Any = kwargs.pop("resume_download" , a ) SCREAMING_SNAKE_CASE : Union[str, Any] = kwargs.pop("proxies" , a ) SCREAMING_SNAKE_CASE : str = kwargs.pop("local_files_only" , a ) if os.path.isdir(a ): SCREAMING_SNAKE_CASE : List[Any] = os.path.join(a , a ) elif os.path.isfile(a ) or is_remote_url(a ): SCREAMING_SNAKE_CASE : List[Any] = pretrained_model_name_or_path else: SCREAMING_SNAKE_CASE : List[str] = hf_bucket_url(a , filename=a , use_cdn=a ) try: # Load from URL or cache if already cached SCREAMING_SNAKE_CASE : Union[str, Any] = cached_path( a , cache_dir=a , force_download=a , proxies=a , resume_download=a , local_files_only=a , ) # Load config dict if resolved_config_file is None: raise EnvironmentError SCREAMING_SNAKE_CASE : Optional[int] = Config.load_yaml(a ) except EnvironmentError: SCREAMING_SNAKE_CASE : int = "Can't load config for" raise EnvironmentError(a ) if resolved_config_file == config_file: print("loading configuration file from path" ) else: print("loading configuration file cache" ) return Config.load_yaml(a ), kwargs def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : List[str] = torch.load("dump.pt" , map_location=in_tensor.device) SCREAMING_SNAKE_CASE : Optional[int] = in_tensor.numpy() SCREAMING_SNAKE_CASE : str = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5]) print(na.shape , na[0, 0, :5]) assert np.allclose(_a , _a , rtol=0.01 , atol=0.1), ( f"{sum([1 for x in np.isclose(_a , _a , rtol=0.01 , atol=0.1).flatten() if x is False])/len(na.flatten())*100:.4f} %" " element-wise mismatch" ) raise Exception("tensors are all good") # Hugging face functions below def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Any = urlparse(_a) return parsed.scheme in ("http", "https") def lowerCamelCase__ ( _a , _a , _a=True): SCREAMING_SNAKE_CASE : str = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX SCREAMING_SNAKE_CASE : int = "/" not in model_id if legacy_format: return f"{endpoint}/{model_id}-{filename}" else: return f"{endpoint}/{model_id}/{filename}" def lowerCamelCase__ ( _a , _a , _a=None , _a=0 , _a=None , ): SCREAMING_SNAKE_CASE : Union[str, Any] = "python/{}".format(sys.version.split()[0]) if _torch_available: ua += "; torch/{}".format(torch.__version__) if isinstance(_a , _a): ua += "; " + "; ".join("{}/{}".format(_a , _a) for k, v in user_agent.items()) elif isinstance(_a , _a): ua += "; " + user_agent SCREAMING_SNAKE_CASE : int = {"user-agent": ua} if resume_size > 0: SCREAMING_SNAKE_CASE : Any = "bytes=%d-" % (resume_size,) SCREAMING_SNAKE_CASE : Optional[int] = requests.get(_a , stream=_a , proxies=_a , headers=_a) if response.status_code == 416: # Range not satisfiable return SCREAMING_SNAKE_CASE : int = response.headers.get("Content-Length") SCREAMING_SNAKE_CASE : Union[str, Any] = resume_size + int(_a) if content_length is not None else None SCREAMING_SNAKE_CASE : List[Any] = tqdm( unit="B" , unit_scale=_a , total=_a , initial=_a , desc="Downloading" , ) for chunk in response.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks progress.update(len(_a)) temp_file.write(_a) progress.close() def lowerCamelCase__ ( _a , _a=None , _a=False , _a=None , _a=10 , _a=False , _a=None , _a=False , ): if cache_dir is None: SCREAMING_SNAKE_CASE : Union[str, Any] = TRANSFORMERS_CACHE if isinstance(_a , _a): SCREAMING_SNAKE_CASE : Dict = str(_a) os.makedirs(_a , exist_ok=_a) SCREAMING_SNAKE_CASE : str = None if not local_files_only: try: SCREAMING_SNAKE_CASE : Any = requests.head(_a , allow_redirects=_a , proxies=_a , timeout=_a) if response.status_code == 200: SCREAMING_SNAKE_CASE : List[Any] = response.headers.get("ETag") except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass SCREAMING_SNAKE_CASE : Dict = url_to_filename(_a , _a) # get cache path to put the file SCREAMING_SNAKE_CASE : Tuple = os.path.join(_a , _a) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(_a): return cache_path else: SCREAMING_SNAKE_CASE : Dict = [ file for file in fnmatch.filter(os.listdir(_a) , filename + ".*") if not file.endswith(".json") and not file.endswith(".lock") ] if len(_a) > 0: return os.path.join(_a , matching_files[-1]) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( "Cannot find the requested files in the cached path and outgoing traffic has been" " disabled. To enable model look-ups and downloads online, set 'local_files_only'" " to False.") return None # From now on, etag is not None. if os.path.exists(_a) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. SCREAMING_SNAKE_CASE : Optional[int] = cache_path + ".lock" with FileLock(_a): # If the download just completed while the lock was activated. if os.path.exists(_a) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: SCREAMING_SNAKE_CASE : Optional[int] = cache_path + ".incomplete" @contextmanager def _resumable_file_manager(): with open(_a , "a+b") as f: yield f SCREAMING_SNAKE_CASE : Optional[int] = _resumable_file_manager if os.path.exists(_a): SCREAMING_SNAKE_CASE : List[Any] = os.stat(_a).st_size else: SCREAMING_SNAKE_CASE : Any = 0 else: SCREAMING_SNAKE_CASE : List[Any] = partial(tempfile.NamedTemporaryFile , dir=_a , delete=_a) SCREAMING_SNAKE_CASE : List[Any] = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( "%s not found in cache or force_download set to True, downloading to %s" , _a , temp_file.name , ) http_get( _a , _a , proxies=_a , resume_size=_a , user_agent=_a , ) os.replace(temp_file.name , _a) SCREAMING_SNAKE_CASE : List[Any] = {"url": url, "etag": etag} SCREAMING_SNAKE_CASE : List[Any] = cache_path + ".json" with open(_a , "w") as meta_file: json.dump(_a , _a) return cache_path def lowerCamelCase__ ( _a , _a=None): SCREAMING_SNAKE_CASE : str = url.encode("utf-8") SCREAMING_SNAKE_CASE : Optional[Any] = shaaaa(_a) SCREAMING_SNAKE_CASE : str = url_hash.hexdigest() if etag: SCREAMING_SNAKE_CASE : List[Any] = etag.encode("utf-8") SCREAMING_SNAKE_CASE : Optional[int] = shaaaa(_a) filename += "." + etag_hash.hexdigest() if url.endswith(".h5"): filename += ".h5" return filename def lowerCamelCase__ ( _a , _a=None , _a=False , _a=None , _a=False , _a=None , _a=False , _a=False , _a=False , ): if cache_dir is None: SCREAMING_SNAKE_CASE : str = TRANSFORMERS_CACHE if isinstance(_a , _a): SCREAMING_SNAKE_CASE : Dict = str(_a) if isinstance(_a , _a): SCREAMING_SNAKE_CASE : Tuple = str(_a) if is_remote_url(_a): # URL, so get it from the cache (downloading if necessary) SCREAMING_SNAKE_CASE : Union[str, Any] = get_from_cache( _a , cache_dir=_a , force_download=_a , proxies=_a , resume_download=_a , user_agent=_a , local_files_only=_a , ) elif os.path.exists(_a): # File, and it exists. SCREAMING_SNAKE_CASE : int = url_or_filename elif urlparse(_a).scheme == "": # File, but it doesn't exist. raise EnvironmentError("file {} not found".format(_a)) else: # Something unknown raise ValueError("unable to parse {} as a URL or as a local path".format(_a)) if extract_compressed_file: if not is_zipfile(_a) and not tarfile.is_tarfile(_a): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = os.path.split(_a) SCREAMING_SNAKE_CASE : List[Any] = output_file.replace("." , "-") + "-extracted" SCREAMING_SNAKE_CASE : str = os.path.join(_a , _a) if os.path.isdir(_a) and os.listdir(_a) and not force_extract: return output_path_extracted # Prevent parallel extractions SCREAMING_SNAKE_CASE : Union[str, Any] = output_path + ".lock" with FileLock(_a): shutil.rmtree(_a , ignore_errors=_a) os.makedirs(_a) if is_zipfile(_a): with ZipFile(_a , "r") as zip_file: zip_file.extractall(_a) zip_file.close() elif tarfile.is_tarfile(_a): SCREAMING_SNAKE_CASE : Optional[Any] = tarfile.open(_a) tar_file.extractall(_a) tar_file.close() else: raise EnvironmentError("Archive format of {} could not be identified".format(_a)) return output_path_extracted return output_path def lowerCamelCase__ ( _a , _a=","): assert isinstance(_a , _a) if os.path.isfile(_a): with open(_a) as f: SCREAMING_SNAKE_CASE : Dict = eval(f.read()) else: SCREAMING_SNAKE_CASE : Dict = requests.get(_a) try: SCREAMING_SNAKE_CASE : List[Any] = requests.json() except Exception: SCREAMING_SNAKE_CASE : Optional[Any] = req.content.decode() assert data is not None, "could not connect" try: SCREAMING_SNAKE_CASE : int = eval(_a) except Exception: SCREAMING_SNAKE_CASE : Optional[Any] = data.split("\n") req.close() return data def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Tuple = requests.get(_a) SCREAMING_SNAKE_CASE : Any = np.array(Image.open(BytesIO(response.content))) return img def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Tuple = url.split("/")[-1] if fn not in os.listdir(os.getcwd()): wget.download(_a) with open(_a , "rb") as stream: SCREAMING_SNAKE_CASE : str = pkl.load(_a) SCREAMING_SNAKE_CASE : List[str] = weights.pop("model") SCREAMING_SNAKE_CASE : int = {} for k, v in model.items(): SCREAMING_SNAKE_CASE : Union[str, Any] = torch.from_numpy(_a) if "running_var" in k: SCREAMING_SNAKE_CASE : Dict = torch.tensor([0]) SCREAMING_SNAKE_CASE : Union[str, Any] = k.replace("running_var" , "num_batches_tracked") SCREAMING_SNAKE_CASE : Optional[int] = zero return new def lowerCamelCase__ ( ): print(f"{os.path.abspath(os.path.join(_a , os.pardir))}/demo.ipynb") def lowerCamelCase__ ( _a , _a="RGB"): assert isinstance(_a , _a) if os.path.isfile(_a): SCREAMING_SNAKE_CASE : Tuple = cva.imread(_a) else: SCREAMING_SNAKE_CASE : Any = get_image_from_url(_a) assert img is not None, f"could not connect to: {im}" SCREAMING_SNAKE_CASE : List[str] = cva.cvtColor(_a , cva.COLOR_BGR2RGB) if input_format == "RGB": SCREAMING_SNAKE_CASE : Optional[Any] = img[:, :, ::-1] return img def lowerCamelCase__ ( _a , _a=1): return (images[i : i + batch] for i in range(0 , len(_a) , _a))
76
from typing import Any class _UpperCamelCase : '''simple docstring''' def __init__( self : Dict , a : Any ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : int = data SCREAMING_SNAKE_CASE : int = None def __repr__( self : str ) -> str: """simple docstring""" return F"Node({self.data})" class _UpperCamelCase : '''simple docstring''' def __init__( self : List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = None def __iter__( self : Any ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.head while node: yield node.data SCREAMING_SNAKE_CASE : List[str] = node.next def __len__( self : str ) -> int: """simple docstring""" return sum(1 for _ in self ) def __repr__( self : Optional[Any] ) -> str: """simple docstring""" return "->".join([str(a ) for item in self] ) def __getitem__( self : List[Any] , a : int ) -> Any: """simple docstring""" if not 0 <= index < len(self ): raise ValueError("list index out of range." ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Tuple , a : int , a : Any ) -> None: """simple docstring""" if not 0 <= index < len(self ): raise ValueError("list index out of range." ) SCREAMING_SNAKE_CASE : str = self.head for _ in range(a ): SCREAMING_SNAKE_CASE : str = current.next SCREAMING_SNAKE_CASE : Any = data def __UpperCamelCase ( self : List[str] , a : Any ) -> None: """simple docstring""" self.insert_nth(len(self ) , a ) def __UpperCamelCase ( self : Union[str, Any] , a : Any ) -> None: """simple docstring""" self.insert_nth(0 , a ) def __UpperCamelCase ( self : Optional[Any] , a : int , a : Any ) -> None: """simple docstring""" if not 0 <= index <= len(self ): raise IndexError("list index out of range" ) SCREAMING_SNAKE_CASE : Any = Node(a ) if self.head is None: SCREAMING_SNAKE_CASE : Optional[int] = new_node elif index == 0: SCREAMING_SNAKE_CASE : Optional[int] = self.head # link new_node to head SCREAMING_SNAKE_CASE : List[Any] = new_node else: SCREAMING_SNAKE_CASE : Optional[Any] = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : Optional[int] = temp.next SCREAMING_SNAKE_CASE : Optional[int] = temp.next SCREAMING_SNAKE_CASE : int = new_node def __UpperCamelCase ( self : Optional[int] ) -> None: # print every node data """simple docstring""" print(self ) def __UpperCamelCase ( self : int ) -> Any: """simple docstring""" return self.delete_nth(0 ) def __UpperCamelCase ( self : Any ) -> Any: # delete from tail """simple docstring""" return self.delete_nth(len(self ) - 1 ) def __UpperCamelCase ( self : List[str] , a : int = 0 ) -> Any: """simple docstring""" if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("List index out of range." ) SCREAMING_SNAKE_CASE : Tuple = self.head # default first node if index == 0: SCREAMING_SNAKE_CASE : List[str] = self.head.next else: SCREAMING_SNAKE_CASE : Optional[Any] = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : Any = temp.next SCREAMING_SNAKE_CASE : List[Any] = temp.next SCREAMING_SNAKE_CASE : List[str] = temp.next.next return delete_node.data def __UpperCamelCase ( self : List[Any] ) -> bool: """simple docstring""" return self.head is None def __UpperCamelCase ( self : Optional[int] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = None SCREAMING_SNAKE_CASE : str = self.head while current: # Store the current node's next node. SCREAMING_SNAKE_CASE : Any = current.next # Make the current node's next point backwards SCREAMING_SNAKE_CASE : List[Any] = prev # Make the previous node be the current node SCREAMING_SNAKE_CASE : Any = current # Make the current node the next node (to progress iteration) SCREAMING_SNAKE_CASE : str = next_node # Return prev in order to put the head at the end SCREAMING_SNAKE_CASE : Optional[Any] = prev def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Union[str, Any] = LinkedList() assert linked_list.is_empty() is True assert str(_a) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(_a) == i linked_list.insert_nth(_a , i + 1) assert str(_a) == "->".join(str(_a) for i in range(1 , 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(_a) == "->".join(str(_a) for i in range(0 , 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(_a) == 9 assert str(_a) == "->".join(str(_a) for i in range(1 , 10)) assert all(linked_list[i] == i + 1 for i in range(0 , 9)) is True for i in range(0 , 9): SCREAMING_SNAKE_CASE : str = -i assert all(linked_list[i] == -i for i in range(0 , 9)) is True linked_list.reverse() assert str(_a) == "->".join(str(_a) for i in range(-8 , 1)) def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Optional[Any] = [ -9, 100, Node(77345112), "dlrow olleH", 7, 5555, 0, -192.5_5555, "Hello, world!", 77.9, Node(10), None, None, 12.20, ] SCREAMING_SNAKE_CASE : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(_a) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(_a) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head SCREAMING_SNAKE_CASE : List[Any] = linked_list.delete_head() assert result == -9 assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail SCREAMING_SNAKE_CASE : Any = linked_list.delete_tail() assert result == 12.2 assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list SCREAMING_SNAKE_CASE : Any = linked_list.delete_nth(10) assert result is None assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!")) assert ( str(_a) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(_a) assert ( str(_a) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(_a) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def lowerCamelCase__ ( ): from doctest import testmod testmod() SCREAMING_SNAKE_CASE : Optional[int] = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(_a) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") SCREAMING_SNAKE_CASE : Dict = input("Enter New Value: ").strip() print("New list:") print(_a) print(f"length of linked_list is : {len(_a)}") if __name__ == "__main__": main()
76
1
from datetime import datetime as dt import os from github import Github a_ = [ 'good first issue', 'good second issue', 'good difficult issue', 'feature request', 'new model', 'wip', ] def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : int = Github(os.environ["GITHUB_TOKEN"]) SCREAMING_SNAKE_CASE : List[str] = g.get_repo("huggingface/transformers") SCREAMING_SNAKE_CASE : Optional[int] = repo.get_issues(state="open") for issue in open_issues: SCREAMING_SNAKE_CASE : List[Any] = sorted([comment for comment in issue.get_comments()] , key=lambda _a: i.created_at , reverse=_a) SCREAMING_SNAKE_CASE : str = comments[0] if len(_a) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state="closed") elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( "This issue has been automatically marked as stale because it has not had " "recent activity. If you think this still needs to be addressed " "please comment on this thread.\n\nPlease note that issues that do not follow the " "[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) " "are likely to be ignored.") if __name__ == "__main__": main()
76
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger a_ = get_logger(__name__) class _UpperCamelCase ( enum.Enum ): '''simple docstring''' lowerCamelCase__ ='all_checks' lowerCamelCase__ ='basic_checks' lowerCamelCase__ ='no_checks' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' def lowerCamelCase__ ( _a , _a , _a=None): if expected_checksums is None: logger.info("Unable to verify checksums.") return if len(set(_a) - set(_a)) > 0: raise ExpectedMoreDownloadedFiles(str(set(_a) - set(_a))) if len(set(_a) - set(_a)) > 0: raise UnexpectedDownloadedFile(str(set(_a) - set(_a))) SCREAMING_SNAKE_CASE : str = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] SCREAMING_SNAKE_CASE : Tuple = " for " + verification_name if verification_name is not None else "" if len(_a) > 0: raise NonMatchingChecksumError( f"Checksums didn't match{for_verification_name}:\n" f"{bad_urls}\n" "Set `verification_mode='no_checks'` to skip checksums verification and ignore this error") logger.info("All the checksums matched successfully" + for_verification_name) class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' def lowerCamelCase__ ( _a , _a): if expected_splits is None: logger.info("Unable to verify splits sizes.") return if len(set(_a) - set(_a)) > 0: raise ExpectedMoreSplits(str(set(_a) - set(_a))) if len(set(_a) - set(_a)) > 0: raise UnexpectedSplits(str(set(_a) - set(_a))) SCREAMING_SNAKE_CASE : List[str] = [ {"expected": expected_splits[name], "recorded": recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(_a) > 0: raise NonMatchingSplitsSizesError(str(_a)) logger.info("All the splits matched successfully.") def lowerCamelCase__ ( _a , _a = True): if record_checksum: SCREAMING_SNAKE_CASE : List[str] = shaaaa() with open(_a , "rb") as f: for chunk in iter(lambda: f.read(1 << 20) , b""): m.update(_a) SCREAMING_SNAKE_CASE : Optional[int] = m.hexdigest() else: SCREAMING_SNAKE_CASE : List[str] = None return {"num_bytes": os.path.getsize(_a), "checksum": checksum} def lowerCamelCase__ ( _a): if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
76
1
import collections import os import re from pathlib import Path a_ = 'src/transformers' # Matches is_xxx_available() a_ = re.compile(r'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} a_ = re.compile(r'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] a_ = re.compile(r'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available a_ = re.compile(r'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") a_ = re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] a_ = re.compile(r'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", a_ = re.compile(r'^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], a_ = re.compile(r'^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo a_ = re.compile(r'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: a_ = re.compile(r'^\s*try:') # Catches a line with else: a_ = re.compile(r'^\s*else:') def lowerCamelCase__ ( _a): if _re_test_backend.search(_a) is None: return None SCREAMING_SNAKE_CASE : int = [b[0] for b in _re_backend.findall(_a)] backends.sort() return "_and_".join(_a) def lowerCamelCase__ ( _a): with open(_a , "r" , encoding="utf-8" , newline="\n") as f: SCREAMING_SNAKE_CASE : List[str] = f.readlines() SCREAMING_SNAKE_CASE : Any = 0 while line_index < len(_a) and not lines[line_index].startswith("_import_structure = {"): line_index += 1 # If this is a traditional init, just return. if line_index >= len(_a): return None # First grab the objects without a specific backend in _import_structure SCREAMING_SNAKE_CASE : Dict = [] while not lines[line_index].startswith("if TYPE_CHECKING") and find_backend(lines[line_index]) is None: SCREAMING_SNAKE_CASE : Tuple = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(_a): SCREAMING_SNAKE_CASE : List[Any] = _re_one_line_import_struct.search(_a).groups()[0] SCREAMING_SNAKE_CASE : Any = re.findall(r"\[([^\]]+)\]" , _a) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(", ")]) line_index += 1 continue SCREAMING_SNAKE_CASE : Tuple = _re_import_struct_key_value.search(_a) if single_line_import_search is not None: SCREAMING_SNAKE_CASE : int = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", ") if len(_a) > 0] objects.extend(_a) elif line.startswith(" " * 8 + "\""): objects.append(line[9:-3]) line_index += 1 SCREAMING_SNAKE_CASE : Any = {"none": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("if TYPE_CHECKING"): # If the line is an if not is_backend_available, we grab all objects associated. SCREAMING_SNAKE_CASE : Any = find_backend(lines[line_index]) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1]) is None: SCREAMING_SNAKE_CASE : str = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index]) is None: line_index += 1 line_index += 1 SCREAMING_SNAKE_CASE : str = [] # Until we unindent, add backend objects to the list while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 4): SCREAMING_SNAKE_CASE : Union[str, Any] = lines[line_index] if _re_import_struct_add_one.search(_a) is not None: objects.append(_re_import_struct_add_one.search(_a).groups()[0]) elif _re_import_struct_add_many.search(_a) is not None: SCREAMING_SNAKE_CASE : Any = _re_import_struct_add_many.search(_a).groups()[0].split(", ") SCREAMING_SNAKE_CASE : Optional[int] = [obj[1:-1] for obj in imports if len(_a) > 0] objects.extend(_a) elif _re_between_brackets.search(_a) is not None: SCREAMING_SNAKE_CASE : Union[str, Any] = _re_between_brackets.search(_a).groups()[0].split(", ") SCREAMING_SNAKE_CASE : int = [obj[1:-1] for obj in imports if len(_a) > 0] objects.extend(_a) elif _re_quote_object.search(_a) is not None: objects.append(_re_quote_object.search(_a).groups()[0]) elif line.startswith(" " * 8 + "\""): objects.append(line[9:-3]) elif line.startswith(" " * 12 + "\""): objects.append(line[13:-3]) line_index += 1 SCREAMING_SNAKE_CASE : Any = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend SCREAMING_SNAKE_CASE : Any = [] while ( line_index < len(_a) and find_backend(lines[line_index]) is None and not lines[line_index].startswith("else") ): SCREAMING_SNAKE_CASE : Union[str, Any] = lines[line_index] SCREAMING_SNAKE_CASE : int = _re_import.search(_a) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", ")) elif line.startswith(" " * 8): objects.append(line[8:-2]) line_index += 1 SCREAMING_SNAKE_CASE : str = {"none": objects} # Let's continue with backend-specific objects while line_index < len(_a): # If the line is an if is_backend_available, we grab all objects associated. SCREAMING_SNAKE_CASE : int = find_backend(lines[line_index]) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1]) is None: SCREAMING_SNAKE_CASE : Union[str, Any] = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index]) is None: line_index += 1 line_index += 1 SCREAMING_SNAKE_CASE : List[str] = [] # Until we unindent, add backend objects to the list while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 8): SCREAMING_SNAKE_CASE : Optional[Any] = lines[line_index] SCREAMING_SNAKE_CASE : Dict = _re_import.search(_a) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", ")) elif line.startswith(" " * 12): objects.append(line[12:-2]) line_index += 1 SCREAMING_SNAKE_CASE : List[Any] = objects else: line_index += 1 return import_dict_objects, type_hint_objects def lowerCamelCase__ ( _a , _a): def find_duplicates(_a): return [k for k, v in collections.Counter(_a).items() if v > 1] if list(import_dict_objects.keys()) != list(type_hint_objects.keys()): return ["Both sides of the init do not have the same backends!"] SCREAMING_SNAKE_CASE : Dict = [] for key in import_dict_objects.keys(): SCREAMING_SNAKE_CASE : List[Any] = find_duplicates(import_dict_objects[key]) if duplicate_imports: errors.append(f"Duplicate _import_structure definitions for: {duplicate_imports}") SCREAMING_SNAKE_CASE : Dict = find_duplicates(type_hint_objects[key]) if duplicate_type_hints: errors.append(f"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}") if sorted(set(import_dict_objects[key])) != sorted(set(type_hint_objects[key])): SCREAMING_SNAKE_CASE : Dict = "base imports" if key == "none" else f"{key} backend" errors.append(f"Differences for {name}:") for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f" {a} in TYPE_HINT but not in _import_structure.") for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f" {a} in _import_structure but not in TYPE_HINT.") return errors def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : List[Any] = [] for root, _, files in os.walk(_a): if "__init__.py" in files: SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_a , "__init__.py") SCREAMING_SNAKE_CASE : List[str] = parse_init(_a) if objects is not None: SCREAMING_SNAKE_CASE : Union[str, Any] = analyze_results(*_a) if len(_a) > 0: SCREAMING_SNAKE_CASE : List[str] = f"Problem in {fname}, both halves do not define the same objects.\n{errors[0]}" failures.append("\n".join(_a)) if len(_a) > 0: raise ValueError("\n\n".join(_a)) def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Dict = [] for path, directories, files in os.walk(_a): for folder in directories: # Ignore private modules if folder.startswith("_"): directories.remove(_a) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(_a) / folder).glob("*.py"))) == 0: continue SCREAMING_SNAKE_CASE : Union[str, Any] = str((Path(_a) / folder).relative_to(_a)) SCREAMING_SNAKE_CASE : int = short_path.replace(os.path.sep , ".") submodules.append(_a) for fname in files: if fname == "__init__.py": continue SCREAMING_SNAKE_CASE : Dict = str((Path(_a) / fname).relative_to(_a)) SCREAMING_SNAKE_CASE : int = short_path.replace(".py" , "").replace(os.path.sep , ".") if len(submodule.split(".")) == 1: submodules.append(_a) return submodules a_ = [ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', 'models.esm.openfold_utils', ] def lowerCamelCase__ ( ): # This is to make sure the transformers module imported is the one in the repo. from transformers.utils import direct_transformers_import SCREAMING_SNAKE_CASE : str = direct_transformers_import(_a) SCREAMING_SNAKE_CASE : Optional[Any] = set(transformers._import_structure.keys()) # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and # (potentiall re-) add them. with open(os.path.join(_a , "__init__.py") , "r") as f: SCREAMING_SNAKE_CASE : Optional[int] = f.read() import_structure_keys.update(set(re.findall(r"import_structure\[\"([^\"]*)\"\]" , _a))) SCREAMING_SNAKE_CASE : str = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in import_structure_keys ] if len(_a) > 0: SCREAMING_SNAKE_CASE : int = "\n".join(f"- {module}" for module in module_not_registered) raise ValueError( "The following submodules are not properly registed in the main init of Transformers:\n" f"{list_of_modules}\n" "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.") if __name__ == "__main__": check_all_inits() check_submodules()
76
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCamelCase__ ( _a , _a): # Load checkpoint SCREAMING_SNAKE_CASE : int = torch.load(_a , map_location="cpu") SCREAMING_SNAKE_CASE : Dict = chkpt["model"] # We have the base model one level deeper than the original XLM repository SCREAMING_SNAKE_CASE : Optional[int] = {} for k, v in state_dict.items(): if "pred_layer" in k: SCREAMING_SNAKE_CASE : List[str] = v else: SCREAMING_SNAKE_CASE : int = v SCREAMING_SNAKE_CASE : int = chkpt["params"] SCREAMING_SNAKE_CASE : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(_a , (torch.FloatTensor, numpy.ndarray))} SCREAMING_SNAKE_CASE : List[Any] = chkpt["dico_word2id"] SCREAMING_SNAKE_CASE : List[Any] = {s + "</w>" if s.find("@@") == -1 and i > 13 else s.replace("@@" , ""): i for s, i in vocab.items()} # Save pytorch-model SCREAMING_SNAKE_CASE : Tuple = pytorch_dump_folder_path + "/" + WEIGHTS_NAME SCREAMING_SNAKE_CASE : Any = pytorch_dump_folder_path + "/" + CONFIG_NAME SCREAMING_SNAKE_CASE : Optional[int] = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["vocab_file"] print(f"Save PyTorch model to {pytorch_weights_dump_path}") torch.save(_a , _a) print(f"Save configuration file to {pytorch_config_dump_path}") with open(_a , "w" , encoding="utf-8") as f: f.write(json.dumps(_a , indent=2) + "\n") print(f"Save vocab file to {pytorch_config_dump_path}") with open(_a , "w" , encoding="utf-8") as f: f.write(json.dumps(_a , indent=2) + "\n") if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xlm_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) a_ = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
76
1
import math def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Optional[Any] = input("Enter message: ") SCREAMING_SNAKE_CASE : Optional[int] = int(input(f"Enter key [2-{len(_a) - 1}]: ")) SCREAMING_SNAKE_CASE : Optional[int] = input("Encryption/Decryption [e/d]: ") if mode.lower().startswith("e"): SCREAMING_SNAKE_CASE : int = encrypt_message(_a , _a) elif mode.lower().startswith("d"): SCREAMING_SNAKE_CASE : Union[str, Any] = decrypt_message(_a , _a) # Append pipe symbol (vertical bar) to identify spaces at the end. print(f"Output:\n{text + '|'}") def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Tuple = [""] * key for col in range(_a): SCREAMING_SNAKE_CASE : Dict = col while pointer < len(_a): cipher_text[col] += message[pointer] pointer += key return "".join(_a) def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Any = math.ceil(len(_a) / key) SCREAMING_SNAKE_CASE : Union[str, Any] = key SCREAMING_SNAKE_CASE : Optional[Any] = (num_cols * num_rows) - len(_a) SCREAMING_SNAKE_CASE : int = [""] * num_cols SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): SCREAMING_SNAKE_CASE : int = 0 row += 1 return "".join(_a) if __name__ == "__main__": import doctest doctest.testmod() main()
76
def lowerCamelCase__ ( _a , _a): _validate_point(_a) _validate_point(_a) if len(_a) != len(_a): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(a - b) for a, b in zip(_a , _a))) def lowerCamelCase__ ( _a): if point: if isinstance(_a , _a): for item in point: if not isinstance(_a , (int, float)): SCREAMING_SNAKE_CASE : List[Any] = ( "Expected a list of numbers as input, found " f"{type(_a).__name__}" ) raise TypeError(_a) else: SCREAMING_SNAKE_CASE : List[Any] = f"Expected a list of numbers as input, found {type(_a).__name__}" raise TypeError(_a) else: raise ValueError("Missing an input") def lowerCamelCase__ ( _a , _a): _validate_point(_a) _validate_point(_a) if len(_a) != len(_a): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(x - y) for x, y in zip(_a , _a))) if __name__ == "__main__": import doctest doctest.testmod()
76
1
from ....configuration_utils import PretrainedConfig from ....utils import logging a_ = logging.get_logger(__name__) a_ = { 'speechbrain/m-ctc-t-large': 'https://huggingface.co/speechbrain/m-ctc-t-large/resolve/main/config.json', # See all M-CTC-T models at https://huggingface.co/models?filter=mctct } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ ='mctct' def __init__( self : str , a : Tuple=8065 , a : int=1536 , a : Optional[int]=36 , a : str=6144 , a : int=4 , a : int=384 , a : Dict=920 , a : Optional[Any]=1e-5 , a : List[Any]=0.3 , a : int="relu" , a : Dict=0.02 , a : int=0.3 , a : Union[str, Any]=0.3 , a : List[str]=1 , a : int=0 , a : int=2 , a : Any=1 , a : Optional[Any]=0.3 , a : Optional[Any]=1 , a : List[Any]=(7,) , a : Union[str, Any]=(3,) , a : Optional[Any]=80 , a : Optional[int]=1 , a : Optional[int]=None , a : List[Any]="sum" , a : Union[str, Any]=False , **a : int , ) -> Optional[int]: """simple docstring""" super().__init__(**a , pad_token_id=a , bos_token_id=a , eos_token_id=a ) SCREAMING_SNAKE_CASE : Dict = vocab_size SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : int = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = attention_head_dim SCREAMING_SNAKE_CASE : Any = max_position_embeddings SCREAMING_SNAKE_CASE : str = layer_norm_eps SCREAMING_SNAKE_CASE : int = layerdrop SCREAMING_SNAKE_CASE : List[Any] = hidden_act SCREAMING_SNAKE_CASE : int = initializer_range SCREAMING_SNAKE_CASE : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[str] = pad_token_id SCREAMING_SNAKE_CASE : int = bos_token_id SCREAMING_SNAKE_CASE : Dict = eos_token_id SCREAMING_SNAKE_CASE : Union[str, Any] = conv_glu_dim SCREAMING_SNAKE_CASE : Optional[int] = conv_dropout SCREAMING_SNAKE_CASE : List[str] = num_conv_layers SCREAMING_SNAKE_CASE : Optional[Any] = input_feat_per_channel SCREAMING_SNAKE_CASE : List[str] = input_channels SCREAMING_SNAKE_CASE : List[Any] = conv_channels SCREAMING_SNAKE_CASE : Any = ctc_loss_reduction SCREAMING_SNAKE_CASE : Union[str, Any] = ctc_zero_infinity # prevents config testing fail with exporting to json SCREAMING_SNAKE_CASE : Tuple = list(a ) SCREAMING_SNAKE_CASE : List[str] = list(a ) if len(self.conv_kernel ) != self.num_conv_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.conv_kernel)` == `config.num_conv_layers` " F"but is `len(config.conv_kernel) = {len(self.conv_kernel )}`, " F"`config.num_conv_layers = {self.num_conv_layers}`." )
76
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ ='vit_msn' def __init__( self : str , a : Tuple=768 , a : Tuple=12 , a : Any=12 , a : int=3072 , a : List[Any]="gelu" , a : Dict=0.0 , a : int=0.0 , a : str=0.02 , a : List[str]=1e-06 , a : List[Any]=224 , a : Union[str, Any]=16 , a : Union[str, Any]=3 , a : Tuple=True , **a : Dict , ) -> List[Any]: """simple docstring""" super().__init__(**a ) SCREAMING_SNAKE_CASE : Dict = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = initializer_range SCREAMING_SNAKE_CASE : int = layer_norm_eps SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : Tuple = patch_size SCREAMING_SNAKE_CASE : Optional[int] = num_channels SCREAMING_SNAKE_CASE : List[str] = qkv_bias
76
1
import pyarrow.parquet as pq import pytest from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config from datasets.features.image import Image from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase__ ( _a , _a): assert isinstance(_a , _a) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True]) def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : int = tmp_path / "cache" SCREAMING_SNAKE_CASE : Optional[int] = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE : str = ParquetDatasetReader(_a , cache_dir=_a , keep_in_memory=_a).read() _check_parquet_dataset(_a , _a) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : Tuple = tmp_path / "cache" SCREAMING_SNAKE_CASE : Dict = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : Any = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE : Optional[Any] = ( Features({feature: Value(_a) for feature, dtype in features.items()}) if features is not None else None ) SCREAMING_SNAKE_CASE : List[str] = ParquetDatasetReader(_a , features=_a , cache_dir=_a).read() _check_parquet_dataset(_a , _a) @pytest.mark.parametrize("split" , [None, NamedSplit("train"), "train", "test"]) def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : List[str] = tmp_path / "cache" SCREAMING_SNAKE_CASE : Tuple = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : Union[str, Any] = ParquetDatasetReader(_a , cache_dir=_a , split=_a).read() _check_parquet_dataset(_a , _a) assert dataset.split == split if split else "train" @pytest.mark.parametrize("path_type" , [str, list]) def lowerCamelCase__ ( _a , _a , _a): if issubclass(_a , _a): SCREAMING_SNAKE_CASE : Tuple = parquet_path elif issubclass(_a , _a): SCREAMING_SNAKE_CASE : int = [parquet_path] SCREAMING_SNAKE_CASE : int = tmp_path / "cache" SCREAMING_SNAKE_CASE : Optional[int] = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : int = ParquetDatasetReader(_a , cache_dir=_a).read() _check_parquet_dataset(_a , _a) def lowerCamelCase__ ( _a , _a , _a=("train",)): assert isinstance(_a , _a) for split in splits: SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize("keep_in_memory" , [False, True]) def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : str = tmp_path / "cache" SCREAMING_SNAKE_CASE : Any = {"col_1": "string", "col_2": "int64", "col_3": "float64"} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): SCREAMING_SNAKE_CASE : Union[str, Any] = ParquetDatasetReader( {"train": parquet_path} , cache_dir=_a , keep_in_memory=_a).read() _check_parquet_datasetdict(_a , _a) @pytest.mark.parametrize( "features" , [ None, {"col_1": "string", "col_2": "int64", "col_3": "float64"}, {"col_1": "string", "col_2": "string", "col_3": "string"}, {"col_1": "int32", "col_2": "int32", "col_3": "int32"}, {"col_1": "float32", "col_2": "float32", "col_3": "float32"}, ] , ) def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : int = tmp_path / "cache" SCREAMING_SNAKE_CASE : Tuple = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : Tuple = features.copy() if features else default_expected_features SCREAMING_SNAKE_CASE : List[str] = ( Features({feature: Value(_a) for feature, dtype in features.items()}) if features is not None else None ) SCREAMING_SNAKE_CASE : List[str] = ParquetDatasetReader({"train": parquet_path} , features=_a , cache_dir=_a).read() _check_parquet_datasetdict(_a , _a) @pytest.mark.parametrize("split" , [None, NamedSplit("train"), "train", "test"]) def lowerCamelCase__ ( _a , _a , _a): if split: SCREAMING_SNAKE_CASE : List[Any] = {split: parquet_path} else: SCREAMING_SNAKE_CASE : List[str] = "train" SCREAMING_SNAKE_CASE : List[str] = {"train": parquet_path, "test": parquet_path} SCREAMING_SNAKE_CASE : int = tmp_path / "cache" SCREAMING_SNAKE_CASE : Tuple = {"col_1": "string", "col_2": "int64", "col_3": "float64"} SCREAMING_SNAKE_CASE : str = ParquetDatasetReader(_a , cache_dir=_a).read() _check_parquet_datasetdict(_a , _a , splits=list(path.keys())) assert all(dataset[split].split == split for split in path.keys()) def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Dict = ParquetDatasetWriter(_a , tmp_path / "foo.parquet") assert writer.write() > 0 SCREAMING_SNAKE_CASE : Dict = pq.ParquetFile(tmp_path / "foo.parquet") SCREAMING_SNAKE_CASE : Any = pf.read() assert dataset.data.table == output_table def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : str = str(shared_datadir / "test_image_rgb.jpg") SCREAMING_SNAKE_CASE : str = {"image": [image_path]} SCREAMING_SNAKE_CASE : Any = Features({"image": Image()}) SCREAMING_SNAKE_CASE : Any = Dataset.from_dict(_a , features=_a) SCREAMING_SNAKE_CASE : int = ParquetDatasetWriter(_a , tmp_path / "foo.parquet") assert writer.write() > 0 SCREAMING_SNAKE_CASE : Optional[Any] = Dataset.from_parquet(str(tmp_path / "foo.parquet")) assert dataset.features == reloaded_dataset.features SCREAMING_SNAKE_CASE : List[str] = ParquetDatasetReader(str(tmp_path / "foo.parquet") , streaming=_a).read() assert dataset.features == reloaded_iterable_dataset.features @pytest.mark.parametrize( "feature, expected" , [ (Features({"foo": Value("int32")}), None), (Features({"image": Image(), "foo": Value("int32")}), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS), (Features({"nested": Sequence(Audio())}), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS), ] , ) def lowerCamelCase__ ( _a , _a): assert get_writer_batch_size(_a) == expected
76
import baseaa def lowerCamelCase__ ( _a): return baseaa.aaaencode(string.encode("utf-8")) def lowerCamelCase__ ( _a): return baseaa.aaadecode(_a).decode("utf-8") if __name__ == "__main__": import doctest doctest.testmod()
76
1
from __future__ import annotations import collections import tempfile import unittest import numpy as np from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import is_tf_available, is_vision_available from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_tf_bert import TFBertModelTester from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester from ..deit.test_modeling_tf_deit import TFDeiTModelTester from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester from ..vit.test_modeling_tf_vit import TFViTModelTester if is_tf_available(): from transformers import ( TFBertModel, TFCLIPVisionModel, TFDeiTModel, TFRobertaModel, TFVisionTextDualEncoderModel, TFViTModel, VisionTextDualEncoderConfig, ) if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor def lowerCamelCase__ ( _a): if isinstance(_a , collections.abc.Iterable): return x return (x, x) @require_tf class _UpperCamelCase : '''simple docstring''' def __UpperCamelCase ( self : Optional[int] , a : List[str] , a : int ) -> Union[str, Any]: """simple docstring""" pass def __UpperCamelCase ( self : Tuple ) -> Optional[Any]: """simple docstring""" pass def __UpperCamelCase ( self : Any ) -> List[Any]: """simple docstring""" pass def __UpperCamelCase ( self : Optional[int] , a : Any , a : int , a : Optional[int] , a : List[str] , a : Optional[Any]=None , **a : List[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = VisionTextDualEncoderConfig.from_vision_text_configs(a , a ) SCREAMING_SNAKE_CASE : Dict = TFVisionTextDualEncoderModel(a ) SCREAMING_SNAKE_CASE : Any = 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 __UpperCamelCase ( self : Union[str, Any] , a : Optional[int] , a : Dict , a : List[str] , a : Tuple , a : Union[str, Any]=None , **a : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Tuple = self.get_vision_text_model(a , a ) SCREAMING_SNAKE_CASE : Tuple = TFVisionTextDualEncoderModel(vision_model=a , text_model=a ) SCREAMING_SNAKE_CASE : List[str] = 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 __UpperCamelCase ( self : str , a : int , a : List[str] , a : Optional[Any] , a : Optional[Any] , a : List[Any]=None , **a : Dict ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Tuple = self.get_vision_text_model(a , a ) SCREAMING_SNAKE_CASE : List[str] = {"vision_model": vision_model, "text_model": text_model} SCREAMING_SNAKE_CASE : Optional[int] = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**a ) SCREAMING_SNAKE_CASE : Optional[Any] = 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 __UpperCamelCase ( self : int , a : Dict , a : Tuple , a : List[str] , a : int , a : Tuple=None , **a : List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Tuple = self.get_vision_text_model(a , a ) SCREAMING_SNAKE_CASE : Optional[Any] = TFVisionTextDualEncoderModel(vision_model=a , text_model=a ) SCREAMING_SNAKE_CASE : Any = model(input_ids=a , pixel_values=a , attention_mask=a ) SCREAMING_SNAKE_CASE : str = output[0].numpy() with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(a ) SCREAMING_SNAKE_CASE : Optional[Any] = TFVisionTextDualEncoderModel.from_pretrained(a ) SCREAMING_SNAKE_CASE : List[str] = model(input_ids=a , pixel_values=a , attention_mask=a ) SCREAMING_SNAKE_CASE : Any = after_output[0].numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a , 1e-5 ) def __UpperCamelCase ( self : int , a : List[str] , a : Union[str, Any] , a : Optional[int] , a : str , a : Optional[Any]=None , **a : Optional[Any] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Any = self.get_vision_text_model(a , a ) SCREAMING_SNAKE_CASE : Union[str, Any] = TFVisionTextDualEncoderModel(vision_model=a , text_model=a ) SCREAMING_SNAKE_CASE : int = model( input_ids=a , pixel_values=a , attention_mask=a , output_attentions=a ) SCREAMING_SNAKE_CASE : Optional[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 : str = to_atuple(vision_model.config.image_size ) SCREAMING_SNAKE_CASE : Dict = to_atuple(vision_model.config.patch_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = (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 : Any = 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 __UpperCamelCase ( self : str , a : np.ndarray , a : np.ndarray , a : float ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = np.abs((a - b) ).max() self.assertLessEqual(a , a , F"Difference between torch and flax is {diff} (>= {tol})." ) def __UpperCamelCase ( self : Dict ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_model(**a ) def __UpperCamelCase ( self : Union[str, Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**a ) def __UpperCamelCase ( self : int ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**a ) def __UpperCamelCase ( self : int ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.prepare_config_and_inputs() self.check_save_load(**a ) def __UpperCamelCase ( self : Optional[Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**a ) @slow def __UpperCamelCase ( self : List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[str] = self.get_pretrained_model_and_inputs() SCREAMING_SNAKE_CASE : str = model_a(**a ) SCREAMING_SNAKE_CASE : List[str] = outputs[0].numpy() with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(a ) SCREAMING_SNAKE_CASE : Optional[int] = TFVisionTextDualEncoderModel.from_pretrained(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = model_a(**a ) SCREAMING_SNAKE_CASE : str = after_outputs[0].numpy() SCREAMING_SNAKE_CASE : Optional[int] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(a , 1e-5 ) @require_tf class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : List[str] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "hf-internal-testing/tiny-random-vit" , "hf-internal-testing/tiny-random-bert" ) SCREAMING_SNAKE_CASE : Any = 13 SCREAMING_SNAKE_CASE : str = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) SCREAMING_SNAKE_CASE : int = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) SCREAMING_SNAKE_CASE : List[str] = 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 __UpperCamelCase ( self : Optional[int] , a : List[Any] , a : Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = TFViTModel(a , name="vision_model" ) SCREAMING_SNAKE_CASE : Optional[Any] = TFBertModel(a , name="text_model" ) return vision_model, text_model def __UpperCamelCase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = TFViTModelTester(self ) SCREAMING_SNAKE_CASE : Tuple = TFBertModelTester(self ) SCREAMING_SNAKE_CASE : int = vit_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : Optional[int] = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Any = vision_config_and_inputs ( ( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) , ) : Tuple = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Dict ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-deit-tf" , "hf-internal-testing/tiny-random-roberta" ) SCREAMING_SNAKE_CASE : Any = 13 SCREAMING_SNAKE_CASE : Tuple = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) SCREAMING_SNAKE_CASE : Optional[Any] = random_attention_mask([batch_size, 4] ) SCREAMING_SNAKE_CASE : Dict = {"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask} return model, inputs def __UpperCamelCase ( self : Dict , a : Tuple , a : Any , a : Union[str, Any] , a : Tuple , a : Optional[Any]=None , **a : Optional[int] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = self.get_vision_text_model(a , a ) SCREAMING_SNAKE_CASE : str = TFVisionTextDualEncoderModel(vision_model=a , text_model=a ) SCREAMING_SNAKE_CASE : Tuple = model( input_ids=a , pixel_values=a , attention_mask=a , output_attentions=a ) SCREAMING_SNAKE_CASE : Tuple = output.vision_model_output.attentions self.assertEqual(len(a ) , vision_config.num_hidden_layers ) # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens) SCREAMING_SNAKE_CASE : int = to_atuple(vision_model.config.image_size ) SCREAMING_SNAKE_CASE : Dict = to_atuple(vision_model.config.patch_size ) SCREAMING_SNAKE_CASE : List[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) SCREAMING_SNAKE_CASE : int = num_patches + 2 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) SCREAMING_SNAKE_CASE : Union[str, Any] = 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 __UpperCamelCase ( self : str , a : Optional[Any] , a : Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = TFDeiTModel(a , name="vision_model" ) SCREAMING_SNAKE_CASE : Union[str, Any] = TFRobertaModel(a , name="text_model" ) return vision_model, text_model def __UpperCamelCase ( self : int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = TFDeiTModelTester(self ) SCREAMING_SNAKE_CASE : List[str] = TFRobertaModelTester(self ) SCREAMING_SNAKE_CASE : List[str] = vit_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : Any = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Tuple = vision_config_and_inputs ( ( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) , ) : Any = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_tf class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = TFVisionTextDualEncoderModel.from_vision_text_pretrained( "Rocketknight1/tiny-random-clip-tf" , "hf-internal-testing/tiny-random-bert" ) SCREAMING_SNAKE_CASE : Optional[int] = 13 SCREAMING_SNAKE_CASE : Union[str, Any] = floats_tensor( [ batch_size, model.vision_model.config.num_channels, model.vision_model.config.image_size, model.vision_model.config.image_size, ] ) SCREAMING_SNAKE_CASE : Dict = ids_tensor([batch_size, 4] , model.text_model.config.vocab_size ) SCREAMING_SNAKE_CASE : Dict = 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 __UpperCamelCase ( self : Union[str, Any] , a : Optional[int] , a : int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Any = TFCLIPVisionModel(a , name="vision_model" ) SCREAMING_SNAKE_CASE : List[Any] = TFBertModel(a , name="text_model" ) return vision_model, text_model def __UpperCamelCase ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = TFCLIPVisionModelTester(self ) SCREAMING_SNAKE_CASE : Optional[Any] = TFBertModelTester(self ) SCREAMING_SNAKE_CASE : Tuple = clip_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE : Optional[Any] = bert_model_tester.prepare_config_and_inputs() SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = vision_config_and_inputs ( ( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) ,( SCREAMING_SNAKE_CASE ) , ) : Union[str, Any] = text_config_and_inputs return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": input_mask, "input_ids": input_ids, "text_token_type_ids": token_type_ids, "text_sequence_labels": sequence_labels, "text_token_labels": token_labels, "text_choice_labels": choice_labels, } @require_vision @require_tf class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : List[str] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = TFVisionTextDualEncoderModel.from_pretrained( "clip-italian/clip-italian" , logit_scale_init_value=1.0 , from_pt=a ) SCREAMING_SNAKE_CASE : Any = VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian" ) SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) SCREAMING_SNAKE_CASE : List[Any] = 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 : Optional[int] = np.array([[1.228_4727, 0.310_4122]] ) self.assertTrue(np.allclose(outputs.logits_per_image.numpy() , a , atol=1e-3 ) )
76
from datetime import datetime as dt import os from github import Github a_ = [ 'good first issue', 'good second issue', 'good difficult issue', 'feature request', 'new model', 'wip', ] def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : int = Github(os.environ["GITHUB_TOKEN"]) SCREAMING_SNAKE_CASE : List[str] = g.get_repo("huggingface/transformers") SCREAMING_SNAKE_CASE : Optional[int] = repo.get_issues(state="open") for issue in open_issues: SCREAMING_SNAKE_CASE : List[Any] = sorted([comment for comment in issue.get_comments()] , key=lambda _a: i.created_at , reverse=_a) SCREAMING_SNAKE_CASE : str = comments[0] if len(_a) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state="closed") elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( "This issue has been automatically marked as stale because it has not had " "recent activity. If you think this still needs to be addressed " "please comment on this thread.\n\nPlease note that issues that do not follow the " "[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) " "are likely to be ignored.") if __name__ == "__main__": main()
76
1
import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor a_ = logging.get_logger(__name__) class _UpperCamelCase ( __A ): '''simple docstring''' def __init__( self : int , *a : List[Any] , **a : Any ) -> None: """simple docstring""" warnings.warn( "The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers." " Please use DeformableDetrImageProcessor instead." , a , ) super().__init__(*a , **a )
76
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): if isinstance(_a , (list, tuple)) and isinstance(videos[0] , (list, tuple)) and is_valid_image(videos[0][0]): return videos elif isinstance(_a , (list, tuple)) and is_valid_image(videos[0]): return [videos] elif is_valid_image(_a): return [[videos]] raise ValueError(f"Could not make batched video from {videos}") class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =['pixel_values'] def __init__( self : Optional[Any] , a : bool = True , a : Dict[str, int] = None , a : PILImageResampling = PILImageResampling.BILINEAR , a : bool = True , a : Dict[str, int] = None , a : bool = True , a : Union[int, float] = 1 / 255 , a : bool = True , a : bool = True , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , **a : Tuple , ) -> None: """simple docstring""" super().__init__(**a ) SCREAMING_SNAKE_CASE : Tuple = size if size is not None else {"shortest_edge": 256} SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE : str = get_size_dict(a , param_name="crop_size" ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : Optional[int] = do_center_crop SCREAMING_SNAKE_CASE : int = crop_size SCREAMING_SNAKE_CASE : int = resample SCREAMING_SNAKE_CASE : Any = do_rescale SCREAMING_SNAKE_CASE : int = rescale_factor SCREAMING_SNAKE_CASE : Tuple = offset SCREAMING_SNAKE_CASE : str = do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def __UpperCamelCase ( self : Optional[Any] , a : np.ndarray , a : Dict[str, int] , a : PILImageResampling = PILImageResampling.BILINEAR , a : Optional[Union[str, ChannelDimension]] = None , **a : Union[str, Any] , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) if "shortest_edge" in size: SCREAMING_SNAKE_CASE : str = get_resize_output_image_size(a , size["shortest_edge"] , default_to_square=a ) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE : Dict = (size["height"], size["width"]) else: raise ValueError(F"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a , size=a , resample=a , data_format=a , **a ) def __UpperCamelCase ( self : List[str] , a : np.ndarray , a : Dict[str, int] , a : Optional[Union[str, ChannelDimension]] = None , **a : str , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : str = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(F"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __UpperCamelCase ( self : List[Any] , a : np.ndarray , a : Union[int, float] , a : bool = True , a : Optional[Union[str, ChannelDimension]] = None , **a : Tuple , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = image.astype(np.floataa ) if offset: SCREAMING_SNAKE_CASE : Union[str, Any] = image - (scale / 2) return rescale(a , scale=a , data_format=a , **a ) def __UpperCamelCase ( self : int , a : np.ndarray , a : Union[float, List[float]] , a : Union[float, List[float]] , a : Optional[Union[str, ChannelDimension]] = None , **a : List[str] , ) -> np.ndarray: """simple docstring""" return normalize(a , mean=a , std=a , data_format=a , **a ) def __UpperCamelCase ( self : Tuple , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray: """simple docstring""" if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) if offset and not do_rescale: raise ValueError("For offset, do_rescale must also be set to True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : List[str] = to_numpy_array(a ) if do_resize: SCREAMING_SNAKE_CASE : Optional[Any] = self.resize(image=a , size=a , resample=a ) if do_center_crop: SCREAMING_SNAKE_CASE : Union[str, Any] = self.center_crop(a , size=a ) if do_rescale: SCREAMING_SNAKE_CASE : Any = self.rescale(image=a , scale=a , offset=a ) if do_normalize: SCREAMING_SNAKE_CASE : Tuple = self.normalize(image=a , mean=a , std=a ) SCREAMING_SNAKE_CASE : Optional[int] = to_channel_dimension_format(a , a ) return image def __UpperCamelCase ( self : Dict , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[str, TensorType]] = None , a : ChannelDimension = ChannelDimension.FIRST , **a : Tuple , ) -> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE : str = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Union[str, Any] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : int = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE : str = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[Any] = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Optional[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : int = size if size is not None else self.size SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : Tuple = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(a , param_name="crop_size" ) 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." ) SCREAMING_SNAKE_CASE : Optional[int] = make_batched(a ) SCREAMING_SNAKE_CASE : List[Any] = [ [ self._preprocess_image( image=a , do_resize=a , size=a , resample=a , do_center_crop=a , crop_size=a , do_rescale=a , rescale_factor=a , offset=a , do_normalize=a , image_mean=a , image_std=a , data_format=a , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE : Optional[int] = {"pixel_values": videos} return BatchFeature(data=a , tensor_type=a )
76
1
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import ScoreSdeVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =42 lowerCamelCase__ =42 def __init__( self : Optional[int] , a : UNetaDModel , a : ScoreSdeVeScheduler ) -> List[Any]: """simple docstring""" super().__init__() self.register_modules(unet=a , scheduler=a ) @torch.no_grad() def __call__( self : List[Any] , a : int = 1 , a : int = 2000 , a : Optional[Union[torch.Generator, List[torch.Generator]]] = None , a : Optional[str] = "pil" , a : bool = True , **a : List[Any] , ) -> Union[ImagePipelineOutput, Tuple]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.unet.config.sample_size SCREAMING_SNAKE_CASE : List[Any] = (batch_size, 3, img_size, img_size) SCREAMING_SNAKE_CASE : List[Any] = self.unet SCREAMING_SNAKE_CASE : List[Any] = randn_tensor(a , generator=a ) * self.scheduler.init_noise_sigma SCREAMING_SNAKE_CASE : Any = sample.to(self.device ) self.scheduler.set_timesteps(a ) self.scheduler.set_sigmas(a ) for i, t in enumerate(self.progress_bar(self.scheduler.timesteps ) ): SCREAMING_SNAKE_CASE : Tuple = self.scheduler.sigmas[i] * torch.ones(shape[0] , device=self.device ) # correction step for _ in range(self.scheduler.config.correct_steps ): SCREAMING_SNAKE_CASE : int = self.unet(a , a ).sample SCREAMING_SNAKE_CASE : str = self.scheduler.step_correct(a , a , generator=a ).prev_sample # prediction step SCREAMING_SNAKE_CASE : Optional[int] = model(a , a ).sample SCREAMING_SNAKE_CASE : List[str] = self.scheduler.step_pred(a , a , a , generator=a ) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = output.prev_sample, output.prev_sample_mean SCREAMING_SNAKE_CASE : Union[str, Any] = sample_mean.clamp(0 , 1 ) SCREAMING_SNAKE_CASE : Any = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : Any = self.numpy_to_pil(a ) if not return_dict: return (sample,) return ImagePipelineOutput(images=a )
76
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt'} a_ = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } a_ = { 'YituTech/conv-bert-base': 512, 'YituTech/conv-bert-medium-small': 512, 'YituTech/conv-bert-small': 512, } a_ = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =VOCAB_FILES_NAMES lowerCamelCase__ =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ =PRETRAINED_INIT_CONFIGURATION lowerCamelCase__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ =ConvBertTokenizer def __init__( self : List[str] , a : Union[str, Any]=None , a : Optional[int]=None , a : int=True , a : Tuple="[UNK]" , a : Dict="[SEP]" , a : Dict="[PAD]" , a : List[Any]="[CLS]" , a : Tuple="[MASK]" , a : Dict=True , a : Optional[Any]=None , **a : str , ) -> Dict: """simple docstring""" super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) SCREAMING_SNAKE_CASE : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , a ) != do_lower_case or normalizer_state.get("strip_accents" , a ) != strip_accents or normalizer_state.get("handle_chinese_chars" , a ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : List[str] = getattr(a , normalizer_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE : Any = strip_accents SCREAMING_SNAKE_CASE : Optional[int] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : List[str] = normalizer_class(**a ) SCREAMING_SNAKE_CASE : str = do_lower_case def __UpperCamelCase ( self : Union[str, Any] , a : List[Any] , a : int=None ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __UpperCamelCase ( self : Dict , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCamelCase ( self : Tuple , a : str , a : Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self._tokenizer.model.save(a , name=a ) return tuple(a )
76
1
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin a_ = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =XLMRobertaTokenizer lowerCamelCase__ =XLMRobertaTokenizerFast lowerCamelCase__ =True lowerCamelCase__ =True def __UpperCamelCase ( self : Dict ) -> Optional[int]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE : Dict = XLMRobertaTokenizer(a , keep_accents=a ) tokenizer.save_pretrained(self.tmpdirname ) def __UpperCamelCase ( self : Dict ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = "<pad>" SCREAMING_SNAKE_CASE : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a ) , a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a ) , a ) def __UpperCamelCase ( self : List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<s>" ) self.assertEqual(vocab_keys[1] , "<pad>" ) self.assertEqual(vocab_keys[-1] , "<mask>" ) self.assertEqual(len(a ) , 1002 ) def __UpperCamelCase ( self : List[Any] ) -> str: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1002 ) def __UpperCamelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = XLMRobertaTokenizer(a , keep_accents=a ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.tokenize("This is a test" ) self.assertListEqual(a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE : str = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) SCREAMING_SNAKE_CASE : List[str] = tokenizer.convert_tokens_to_ids(a ) self.assertListEqual( a , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) SCREAMING_SNAKE_CASE : List[Any] = tokenizer.convert_ids_to_tokens(a ) self.assertListEqual( a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def __UpperCamelCase ( self : str ) -> str: """simple docstring""" if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return SCREAMING_SNAKE_CASE : Union[str, Any] = (self.rust_tokenizer_class, "hf-internal-testing/tiny-xlm-roberta", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): SCREAMING_SNAKE_CASE : Dict = self.rust_tokenizer_class.from_pretrained(a , **a ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.tokenizer_class.from_pretrained(a , **a ) SCREAMING_SNAKE_CASE : List[Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer_r.save_pretrained(a ) SCREAMING_SNAKE_CASE : Tuple = tokenizer_p.save_pretrained(a ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) SCREAMING_SNAKE_CASE : int = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(a , a ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE : List[str] = tokenizer_r.from_pretrained(a ) SCREAMING_SNAKE_CASE : Any = tokenizer_p.from_pretrained(a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a , a ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(a ) # Save tokenizer rust, legacy_format=True SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer_r.save_pretrained(a , legacy_format=a ) SCREAMING_SNAKE_CASE : int = tokenizer_p.save_pretrained(a ) # Checks it save with the same files self.assertSequenceEqual(a , a ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE : Any = tokenizer_r.from_pretrained(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer_p.from_pretrained(a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a , a ) ) shutil.rmtree(a ) # Save tokenizer rust, legacy_format=False SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE : str = tokenizer_r.save_pretrained(a , legacy_format=a ) SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer_p.save_pretrained(a ) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE : List[str] = tokenizer_r.from_pretrained(a ) SCREAMING_SNAKE_CASE : int = tokenizer_p.from_pretrained(a ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a , a ) ) shutil.rmtree(a ) @cached_property def __UpperCamelCase ( self : List[Any] ) -> List[Any]: """simple docstring""" return XLMRobertaTokenizer.from_pretrained("xlm-roberta-base" ) def __UpperCamelCase ( self : int ) -> Optional[int]: """simple docstring""" with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a , f.name ) SCREAMING_SNAKE_CASE : Optional[int] = XLMRobertaTokenizer(f.name , keep_accents=a ) SCREAMING_SNAKE_CASE : Union[str, Any] = pickle.dumps(a ) pickle.loads(a ) def __UpperCamelCase ( self : str ) -> Tuple: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE : Tuple = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : str = "I was born in 92000, and this is falsé." SCREAMING_SNAKE_CASE : Dict = tokenizer.tokenize(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = rust_tokenizer.tokenize(a ) self.assertListEqual(a , a ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer.encode(a , add_special_tokens=a ) SCREAMING_SNAKE_CASE : Optional[Any] = rust_tokenizer.encode(a , add_special_tokens=a ) self.assertListEqual(a , a ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE : Dict = tokenizer.encode(a ) SCREAMING_SNAKE_CASE : List[Any] = rust_tokenizer.encode(a ) self.assertListEqual(a , a ) @slow def __UpperCamelCase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Any = "Hello World!" SCREAMING_SNAKE_CASE : List[Any] = [0, 3_5378, 6661, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(a , self.big_tokenizer.encode(a ) ) @slow def __UpperCamelCase ( self : Dict ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) SCREAMING_SNAKE_CASE : List[Any] = [ 0, 3293, 83, 10, 4552, 4989, 7986, 678, 10, 5915, 111, 17_9459, 12_4850, 4, 6044, 237, 12, 6, 5, 6, 4, 6780, 705, 15, 1388, 44, 378, 1_0114, 711, 152, 20, 6, 5, 2_2376, 642, 1221, 1_5190, 3_4153, 450, 5608, 959, 1119, 5_7702, 136, 186, 47, 1098, 2_9367, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 6044, 237, 6284, 5_0901, 528, 31, 90, 34, 927, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(a , self.big_tokenizer.encode(a ) ) @slow def __UpperCamelCase ( self : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : int = {"input_ids": [[0, 1_1062, 8_2772, 7, 15, 8_2772, 538, 5_1529, 237, 1_7198, 1290, 206, 9, 21_5175, 1314, 136, 1_7198, 1290, 206, 9, 5_6359, 42, 12_2009, 9, 1_6466, 16, 8_7344, 4537, 9, 4717, 7_8381, 6, 15_9958, 7, 15, 2_4480, 618, 4, 527, 2_2693, 5428, 4, 2777, 2_4480, 9874, 4, 4_3523, 594, 4, 803, 1_8392, 3_3189, 18, 4, 4_3523, 2_4447, 1_2399, 100, 2_4955, 8_3658, 9626, 14_4057, 15, 839, 2_2335, 16, 136, 2_4955, 8_3658, 8_3479, 15, 3_9102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 12_2009, 11_5774, 23, 805, 1328, 4_6876, 7, 136, 5_3894, 1940, 4_2227, 4_1159, 1_7721, 823, 425, 4, 2_7512, 9_8722, 206, 136, 5531, 4970, 919, 1_7336, 5, 2], [0, 2_0080, 618, 83, 8_2775, 47, 479, 9, 1517, 73, 5_3894, 333, 8_0581, 11_0117, 1_8811, 5256, 1295, 51, 15_2526, 297, 7986, 390, 12_4416, 538, 3_5431, 214, 98, 1_5044, 2_5737, 136, 7108, 4_3701, 23, 756, 13_5355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 581, 6_3773, 11_9455, 6, 14_7797, 8_8203, 7, 645, 70, 21, 3285, 1_0269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a , model_name="xlm-roberta-base" , revision="d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3" , )
76
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. a_ = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(_a) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE : Union[str, Any] = terminalreporter.config.getoption("--make-reports") if make_reports: pytest_terminal_summary_main(_a , id=_a)
76
1
def lowerCamelCase__ ( _a , _a): return number | (1 << position) def lowerCamelCase__ ( _a , _a): return number & ~(1 << position) def lowerCamelCase__ ( _a , _a): return number ^ (1 << position) def lowerCamelCase__ ( _a , _a): return ((number >> position) & 1) == 1 def lowerCamelCase__ ( _a , _a): return int((number & (1 << position)) != 0) if __name__ == "__main__": import doctest doctest.testmod()
76
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , a : int , a : Optional[int]=13 , a : Optional[int]=3 , a : int=224 , a : Optional[int]=30 , a : int=400 , a : Union[str, Any]=True , a : int=None , a : Tuple=True , a : Tuple=[0.5, 0.5, 0.5] , a : Optional[int]=[0.5, 0.5, 0.5] , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = size if size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : int = num_channels SCREAMING_SNAKE_CASE : Any = image_size SCREAMING_SNAKE_CASE : Tuple = min_resolution SCREAMING_SNAKE_CASE : str = max_resolution SCREAMING_SNAKE_CASE : int = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : int = do_normalize SCREAMING_SNAKE_CASE : Tuple = image_mean SCREAMING_SNAKE_CASE : Tuple = image_std def __UpperCamelCase ( self : Any ) -> Optional[int]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =ViTImageProcessor if is_vision_available() else None def __UpperCamelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = EfficientFormerImageProcessorTester(self ) @property def __UpperCamelCase ( self : Any ) -> List[str]: """simple docstring""" return self.image_proc_tester.prepare_image_processor_dict() def __UpperCamelCase ( self : List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , "image_mean" ) ) self.assertTrue(hasattr(a , "image_std" ) ) self.assertTrue(hasattr(a , "do_normalize" ) ) self.assertTrue(hasattr(a , "do_resize" ) ) self.assertTrue(hasattr(a , "size" ) ) def __UpperCamelCase ( self : int ) -> str: """simple docstring""" pass def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : List[str] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : str = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , numpify=a ) for image in image_inputs: self.assertIsInstance(a , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Any = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , torchify=a ) for image in image_inputs: self.assertIsInstance(a , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , )
76
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { 'configuration_clipseg': [ 'CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CLIPSegConfig', 'CLIPSegTextConfig', 'CLIPSegVisionConfig', ], 'processing_clipseg': ['CLIPSegProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST', 'CLIPSegModel', 'CLIPSegPreTrainedModel', 'CLIPSegTextModel', 'CLIPSegVisionModel', 'CLIPSegForImageSegmentation', ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = tokenizer(example["content"] , truncation=_a)["input_ids"] SCREAMING_SNAKE_CASE : Dict = len(example["content"]) / len(output["input_ids"]) return output a_ = HfArgumentParser(PretokenizationArguments) a_ = parser.parse_args() if args.num_workers is None: a_ = multiprocessing.cpu_count() a_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) a_ = time.time() a_ = load_dataset(args.dataset_name, split='train') print(F'''Dataset loaded in {time.time()-t_start:.2f}s''') a_ = time.time() a_ = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ 'repo_name', 'path', 'copies', 'size', 'content', 'license', 'hash', 'line_mean', 'line_max', 'alpha_frac', 'autogenerated', ], ) print(F'''Dataset tokenized in {time.time()-t_start:.2f}s''') a_ = time.time() ds.push_to_hub(args.tokenized_data_repo) print(F'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
76
1
import unittest from accelerate import debug_launcher from accelerate.test_utils import require_cpu, test_ops, test_script @require_cpu class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" debug_launcher(test_script.main ) def __UpperCamelCase ( self : int ) -> str: """simple docstring""" debug_launcher(test_ops.main )
76
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): # initialize config if "resnet-50" in model_name: SCREAMING_SNAKE_CASE : int = ResNetConfig.from_pretrained("microsoft/resnet-50") elif "resnet-101" in model_name: SCREAMING_SNAKE_CASE : int = ResNetConfig.from_pretrained("microsoft/resnet-101") else: raise ValueError("Model name should include either resnet50 or resnet101") SCREAMING_SNAKE_CASE : str = DetrConfig(use_timm_backbone=_a , backbone_config=_a) # set label attributes SCREAMING_SNAKE_CASE : List[str] = "panoptic" in model_name if is_panoptic: SCREAMING_SNAKE_CASE : Union[str, Any] = 250 else: SCREAMING_SNAKE_CASE : Union[str, Any] = 91 SCREAMING_SNAKE_CASE : str = "huggingface/label-files" SCREAMING_SNAKE_CASE : Union[str, Any] = "coco-detection-id2label.json" SCREAMING_SNAKE_CASE : Optional[Any] = json.load(open(hf_hub_download(_a , _a , repo_type="dataset") , "r")) SCREAMING_SNAKE_CASE : int = {int(_a): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : List[Any] = idalabel SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in idalabel.items()} return config, is_panoptic def lowerCamelCase__ ( _a): # here we list all keys to be renamed (original name on the left, our name on the right) SCREAMING_SNAKE_CASE : Union[str, Any] = [] # stem # fmt: off rename_keys.append(("backbone.0.body.conv1.weight", "backbone.conv_encoder.model.embedder.embedder.convolution.weight")) rename_keys.append(("backbone.0.body.bn1.weight", "backbone.conv_encoder.model.embedder.embedder.normalization.weight")) rename_keys.append(("backbone.0.body.bn1.bias", "backbone.conv_encoder.model.embedder.embedder.normalization.bias")) rename_keys.append(("backbone.0.body.bn1.running_mean", "backbone.conv_encoder.model.embedder.embedder.normalization.running_mean")) rename_keys.append(("backbone.0.body.bn1.running_var", "backbone.conv_encoder.model.embedder.embedder.normalization.running_var")) # stages for stage_idx in range(len(config.backbone_config.depths)): for layer_idx in range(config.backbone_config.depths[stage_idx]): # shortcut if layer_idx == 0: rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var", )) # 3 convs for i in range(3): rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var", )) # fmt: on for i in range(config.encoder_layers): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( f"transformer.encoder.layers.{i}.self_attn.out_proj.weight", f"encoder.layers.{i}.self_attn.out_proj.weight", )) rename_keys.append( (f"transformer.encoder.layers.{i}.self_attn.out_proj.bias", f"encoder.layers.{i}.self_attn.out_proj.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"encoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"encoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"encoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"encoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm1.weight", f"encoder.layers.{i}.self_attn_layer_norm.weight")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm1.bias", f"encoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm2.weight", f"encoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"encoder.layers.{i}.final_layer_norm.bias")) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"decoder.layers.{i}.self_attn.out_proj.weight", )) rename_keys.append( (f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"decoder.layers.{i}.self_attn.out_proj.bias")) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight", f"decoder.layers.{i}.encoder_attn.out_proj.weight", )) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias", f"decoder.layers.{i}.encoder_attn.out_proj.bias", )) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"decoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"decoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"decoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"decoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm1.weight", f"decoder.layers.{i}.self_attn_layer_norm.weight")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm1.bias", f"decoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.weight", f"decoder.layers.{i}.encoder_attn_layer_norm.weight")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.bias", f"decoder.layers.{i}.encoder_attn_layer_norm.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm3.weight", f"decoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"decoder.layers.{i}.final_layer_norm.bias")) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ]) return rename_keys def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : str = state_dict.pop(_a) SCREAMING_SNAKE_CASE : int = val def lowerCamelCase__ ( _a , _a=False): SCREAMING_SNAKE_CASE : Optional[Any] = "" if is_panoptic: SCREAMING_SNAKE_CASE : Optional[int] = "detr." # first: transformer encoder for i in range(6): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight") SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias") # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : int = in_proj_bias[:256] SCREAMING_SNAKE_CASE : Tuple = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : List[Any] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : str = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight") SCREAMING_SNAKE_CASE : str = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias") # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : Dict = in_proj_bias[:256] SCREAMING_SNAKE_CASE : List[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : Any = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop( f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight") SCREAMING_SNAKE_CASE : int = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias") # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE : Tuple = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE : Dict = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias_cross_attn[-256:] def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Tuple = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(_a , stream=_a).raw) return im @torch.no_grad() def lowerCamelCase__ ( _a , _a=None , _a=False): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = get_detr_config(_a) # load original model from torch hub SCREAMING_SNAKE_CASE : Union[str, Any] = { "detr-resnet-50": "detr_resnet50", "detr-resnet-101": "detr_resnet101", } logger.info(f"Converting model {model_name}...") SCREAMING_SNAKE_CASE : Optional[int] = torch.hub.load("facebookresearch/detr" , model_name_to_original_name[model_name] , pretrained=_a).eval() SCREAMING_SNAKE_CASE : Tuple = detr.state_dict() # rename keys for src, dest in create_rename_keys(_a): if is_panoptic: SCREAMING_SNAKE_CASE : List[str] = "detr." + src rename_key(_a , _a , _a) # query, key and value matrices need special treatment read_in_q_k_v(_a , is_panoptic=_a) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE : List[Any] = "detr.model." if is_panoptic else "model." for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith("detr") and not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor") ): SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Union[str, Any] = val elif "class_labels_classifier" in key or "bbox_predictor" in key: SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Optional[int] = val elif key.startswith("bbox_attention") or key.startswith("mask_head"): continue else: SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : List[Any] = val else: if not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor"): SCREAMING_SNAKE_CASE : Any = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Any = val # finally, create HuggingFace model and load state dict SCREAMING_SNAKE_CASE : int = DetrForSegmentation(_a) if is_panoptic else DetrForObjectDetection(_a) model.load_state_dict(_a) model.eval() # verify our conversion on an image SCREAMING_SNAKE_CASE : int = "coco_panoptic" if is_panoptic else "coco_detection" SCREAMING_SNAKE_CASE : Optional[int] = DetrImageProcessor(format=_a) SCREAMING_SNAKE_CASE : List[str] = processor(images=prepare_img() , return_tensors="pt") SCREAMING_SNAKE_CASE : Any = encoding["pixel_values"] SCREAMING_SNAKE_CASE : Optional[Any] = detr(_a) SCREAMING_SNAKE_CASE : Any = model(_a) assert torch.allclose(outputs.logits , original_outputs["pred_logits"] , atol=1E-3) assert torch.allclose(outputs.pred_boxes , original_outputs["pred_boxes"] , atol=1E-3) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs["pred_masks"] , atol=1E-4) print("Looks ok!") if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f"Saving PyTorch model and image processor to {pytorch_dump_folder_path}...") Path(_a).mkdir(exist_ok=_a) model.save_pretrained(_a) processor.save_pretrained(_a) if push_to_hub: # Upload model and image processor to the hub logger.info("Uploading PyTorch model and image processor to the hub...") model.push_to_hub(f"nielsr/{model_name}") processor.push_to_hub(f"nielsr/{model_name}") if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') a_ = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
76
1
from .testing import ( are_the_same_tensors, execute_subprocess_async, require_bnb, require_cpu, require_cuda, require_huggingface_suite, require_mps, require_multi_gpu, require_multi_xpu, require_safetensors, require_single_gpu, require_single_xpu, require_torch_min_version, require_tpu, require_xpu, skip, slow, ) from .training import RegressionDataset, RegressionModel, RegressionModelaXPU from .scripts import test_script, test_sync, test_ops # isort: skip
76
import os def lowerCamelCase__ ( ): with open(os.path.dirname(_a) + "/p022_names.txt") as file: SCREAMING_SNAKE_CASE : List[str] = str(file.readlines()[0]) SCREAMING_SNAKE_CASE : List[Any] = names.replace("\"" , "").split(",") names.sort() SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : Dict = 0 for i, name in enumerate(_a): for letter in name: name_score += ord(_a) - 64 total_score += (i + 1) * name_score SCREAMING_SNAKE_CASE : str = 0 return total_score if __name__ == "__main__": print(solution())
76
1
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json' ), # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ ='speech_to_text' lowerCamelCase__ =['past_key_values'] lowerCamelCase__ ={'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : Optional[int] , a : Optional[int]=1_0000 , a : Any=12 , a : List[Any]=2048 , a : Any=4 , a : str=6 , a : List[str]=2048 , a : str=4 , a : Tuple=0.0 , a : Dict=0.0 , a : Union[str, Any]=True , a : Any=True , a : Tuple="relu" , a : int=256 , a : Dict=0.1 , a : int=0.0 , a : List[str]=0.0 , a : Dict=0.02 , a : Tuple=2 , a : Tuple=True , a : Optional[Any]=1 , a : int=0 , a : Tuple=2 , a : str=6000 , a : List[Any]=1024 , a : int=2 , a : Optional[Any]=(5, 5) , a : Dict=1024 , a : int=80 , a : Optional[int]=1 , **a : str , ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE : str = d_model SCREAMING_SNAKE_CASE : Union[str, Any] = encoder_ffn_dim SCREAMING_SNAKE_CASE : Any = encoder_layers SCREAMING_SNAKE_CASE : int = encoder_attention_heads SCREAMING_SNAKE_CASE : List[Any] = decoder_ffn_dim SCREAMING_SNAKE_CASE : Any = decoder_layers SCREAMING_SNAKE_CASE : Optional[int] = decoder_attention_heads SCREAMING_SNAKE_CASE : Optional[Any] = dropout SCREAMING_SNAKE_CASE : str = attention_dropout SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout SCREAMING_SNAKE_CASE : str = activation_function SCREAMING_SNAKE_CASE : Any = init_std SCREAMING_SNAKE_CASE : Any = encoder_layerdrop SCREAMING_SNAKE_CASE : int = decoder_layerdrop SCREAMING_SNAKE_CASE : Tuple = use_cache SCREAMING_SNAKE_CASE : Optional[int] = encoder_layers SCREAMING_SNAKE_CASE : str = scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE : Union[str, Any] = max_source_positions SCREAMING_SNAKE_CASE : str = max_target_positions SCREAMING_SNAKE_CASE : Optional[int] = num_conv_layers SCREAMING_SNAKE_CASE : Union[str, Any] = list(a ) SCREAMING_SNAKE_CASE : Optional[int] = conv_channels SCREAMING_SNAKE_CASE : Dict = input_feat_per_channel SCREAMING_SNAKE_CASE : Optional[Any] = input_channels if len(self.conv_kernel_sizes ) != self.num_conv_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` " F"but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes )}`, " F"`config.num_conv_layers = {self.num_conv_layers}`." ) super().__init__( pad_token_id=a , bos_token_id=a , eos_token_id=a , is_encoder_decoder=a , decoder_start_token_id=a , **a , )
76
from collections.abc import Callable import numpy as np def lowerCamelCase__ ( _a , _a , _a , _a , _a): SCREAMING_SNAKE_CASE : Dict = int(np.ceil((x_end - xa) / step_size)) SCREAMING_SNAKE_CASE : Tuple = np.zeros((n + 1,)) SCREAMING_SNAKE_CASE : int = ya SCREAMING_SNAKE_CASE : int = xa for k in range(_a): SCREAMING_SNAKE_CASE : Any = y[k] + step_size * ode_func(_a , y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
76
1
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger a_ = get_logger(__name__) class _UpperCamelCase ( enum.Enum ): '''simple docstring''' lowerCamelCase__ ='all_checks' lowerCamelCase__ ='basic_checks' lowerCamelCase__ ='no_checks' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' def lowerCamelCase__ ( _a , _a , _a=None): if expected_checksums is None: logger.info("Unable to verify checksums.") return if len(set(_a) - set(_a)) > 0: raise ExpectedMoreDownloadedFiles(str(set(_a) - set(_a))) if len(set(_a) - set(_a)) > 0: raise UnexpectedDownloadedFile(str(set(_a) - set(_a))) SCREAMING_SNAKE_CASE : str = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] SCREAMING_SNAKE_CASE : Tuple = " for " + verification_name if verification_name is not None else "" if len(_a) > 0: raise NonMatchingChecksumError( f"Checksums didn't match{for_verification_name}:\n" f"{bad_urls}\n" "Set `verification_mode='no_checks'` to skip checksums verification and ignore this error") logger.info("All the checksums matched successfully" + for_verification_name) class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' def lowerCamelCase__ ( _a , _a): if expected_splits is None: logger.info("Unable to verify splits sizes.") return if len(set(_a) - set(_a)) > 0: raise ExpectedMoreSplits(str(set(_a) - set(_a))) if len(set(_a) - set(_a)) > 0: raise UnexpectedSplits(str(set(_a) - set(_a))) SCREAMING_SNAKE_CASE : List[str] = [ {"expected": expected_splits[name], "recorded": recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(_a) > 0: raise NonMatchingSplitsSizesError(str(_a)) logger.info("All the splits matched successfully.") def lowerCamelCase__ ( _a , _a = True): if record_checksum: SCREAMING_SNAKE_CASE : List[str] = shaaaa() with open(_a , "rb") as f: for chunk in iter(lambda: f.read(1 << 20) , b""): m.update(_a) SCREAMING_SNAKE_CASE : Optional[int] = m.hexdigest() else: SCREAMING_SNAKE_CASE : List[str] = None return {"num_bytes": os.path.getsize(_a), "checksum": checksum} def lowerCamelCase__ ( _a): if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
76
def lowerCamelCase__ ( _a , _a): return int((input_a, input_a).count(1) != 0) def lowerCamelCase__ ( ): assert or_gate(0 , 0) == 0 assert or_gate(0 , 1) == 1 assert or_gate(1 , 0) == 1 assert or_gate(1 , 1) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
76
1
from __future__ import annotations def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Tuple = get_failure_array(_a) # 2) Step through text searching for pattern SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Union[str, Any] = 0, 0 # index into text, pattern while i < len(_a): if pattern[j] == text[i]: if j == (len(_a) - 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 : List[str] = failure[j - 1] continue i += 1 return False def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Any = [0] SCREAMING_SNAKE_CASE : Tuple = 0 SCREAMING_SNAKE_CASE : Optional[int] = 1 while j < len(_a): if pattern[i] == pattern[j]: i += 1 elif i > 0: SCREAMING_SNAKE_CASE : Union[str, Any] = failure[i - 1] continue j += 1 failure.append(_a) return failure if __name__ == "__main__": # Test 1) a_ = 'abc1abc12' a_ = 'alskfjaldsabc1abc1abc12k23adsfabcabc' a_ = 'alskfjaldsk23adsfabcabc' assert kmp(pattern, texta) and not kmp(pattern, texta) # Test 2) a_ = 'ABABX' a_ = 'ABABZABABYABABX' assert kmp(pattern, text) # Test 3) a_ = 'AAAB' a_ = 'ABAAAAAB' assert kmp(pattern, text) # Test 4) a_ = 'abcdabcy' a_ = 'abcxabcdabxabcdabcdabcy' assert kmp(pattern, text) # Test 5) a_ = 'aabaabaaa' assert get_failure_array(pattern) == [0, 1, 0, 1, 2, 3, 4, 5, 2]
76
a_ = 8.314_4598 def lowerCamelCase__ ( _a , _a): if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example a_ = 300 a_ = 28 a_ = rms_speed_of_molecule(temperature, molar_mass) print(F'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
76
1
import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home a_ = HUGGINGFACE_HUB_CACHE a_ = 'config.json' a_ = 'diffusion_pytorch_model.bin' a_ = 'diffusion_flax_model.msgpack' a_ = 'model.onnx' a_ = 'diffusion_pytorch_model.safetensors' a_ = 'weights.pb' a_ = 'https://huggingface.co' a_ = default_cache_path a_ = 'diffusers_modules' a_ = os.getenv('HF_MODULES_CACHE', os.path.join(hf_cache_home, 'modules')) a_ = ['fp16', 'non-ema'] a_ = '.self_attn'
76
a_ = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : int = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE : int = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE : Optional[int] = queue.pop(0) # get the last node from the path SCREAMING_SNAKE_CASE : Union[str, Any] = path[-1] if node not in explored: SCREAMING_SNAKE_CASE : List[str] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE : List[Any] = list(_a) new_path.append(_a) queue.append(_a) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_a) # in case there's no path between the 2 nodes return [] def lowerCamelCase__ ( _a , _a , _a): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE : str = [start] SCREAMING_SNAKE_CASE : Optional[Any] = set(_a) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE : Union[str, Any] = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE : Optional[int] = queue.pop(0) if node == target: SCREAMING_SNAKE_CASE : Union[str, Any] = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node]) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_a) queue.append(_a) SCREAMING_SNAKE_CASE : Optional[Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, 'G', 'D')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, 'G', 'D')) # returns 4
76
1
import operator as op def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : List[str] = [] SCREAMING_SNAKE_CASE : Union[str, Any] = lambda _a , _a: int(x / y) # noqa: E731 integer division operation SCREAMING_SNAKE_CASE : Tuple = { "^": op.pow, "*": op.mul, "/": div, "+": op.add, "-": op.sub, } # operators & their respective operation # print table header print("Symbol".center(8) , "Action".center(12) , "Stack" , sep=" | ") print("-" * (30 + len(_a))) for x in post_fix: if x.isdigit(): # if x in digit stack.append(_a) # append x to stack # output in tabular format print(x.rjust(8) , ("push(" + x + ")").ljust(12) , ",".join(_a) , sep=" | ") else: SCREAMING_SNAKE_CASE : List[Any] = stack.pop() # pop stack # output in tabular format print("".rjust(8) , ("pop(" + b + ")").ljust(12) , ",".join(_a) , sep=" | ") SCREAMING_SNAKE_CASE : Optional[int] = stack.pop() # pop stack # output in tabular format print("".rjust(8) , ("pop(" + a + ")").ljust(12) , ",".join(_a) , sep=" | ") stack.append( str(opr[x](int(_a) , int(_a)))) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8) , ("push(" + a + x + b + ")").ljust(12) , ",".join(_a) , sep=" | " , ) return int(stack[0]) if __name__ == "__main__": a_ = input('\n\nEnter a Postfix Equation (space separated) = ').split(' ') print('\n\tResult = ', solve(Postfix))
76
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : str ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE : List[str] = AutoTokenizer.from_pretrained("google/mt5-small" ) SCREAMING_SNAKE_CASE : Tuple = tokenizer("Hello there" , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer("Hi I am" , return_tensors="tf" ).input_ids SCREAMING_SNAKE_CASE : str = model(a , labels=a ).loss SCREAMING_SNAKE_CASE : Any = -tf.math.reduce_mean(a ).numpy() SCREAMING_SNAKE_CASE : Union[str, Any] = -21.22_8168 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2e-4 )
76
1
import json import os from collections import Counter import torch import torchvision import torchvision.transforms as transforms from PIL import Image from torch import nn from torch.utils.data import Dataset a_ = {1: (1, 1), 2: (2, 1), 3: (3, 1), 4: (2, 2), 5: (5, 1), 6: (3, 2), 7: (7, 1), 8: (4, 2), 9: (3, 3)} class _UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self : int , a : List[Any] ) -> str: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : List[str] = torchvision.models.resnetaaa(pretrained=a ) SCREAMING_SNAKE_CASE : Any = list(model.children() )[:-2] SCREAMING_SNAKE_CASE : Optional[int] = nn.Sequential(*a ) SCREAMING_SNAKE_CASE : Optional[int] = nn.AdaptiveAvgPoolad(POOLING_BREAKDOWN[args.num_image_embeds] ) def __UpperCamelCase ( self : Union[str, Any] , a : List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = self.pool(self.model(a ) ) SCREAMING_SNAKE_CASE : int = torch.flatten(a , start_dim=2 ) SCREAMING_SNAKE_CASE : int = out.transpose(1 , 2 ).contiguous() return out # BxNx2048 class _UpperCamelCase ( __A ): '''simple docstring''' def __init__( self : Optional[int] , a : str , a : Tuple , a : int , a : Tuple , a : List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = [json.loads(a ) for l in open(a )] SCREAMING_SNAKE_CASE : int = os.path.dirname(a ) SCREAMING_SNAKE_CASE : Dict = tokenizer SCREAMING_SNAKE_CASE : Tuple = labels SCREAMING_SNAKE_CASE : int = len(a ) SCREAMING_SNAKE_CASE : Optional[Any] = max_seq_length SCREAMING_SNAKE_CASE : Optional[Any] = transforms def __len__( self : List[str] ) -> List[Any]: """simple docstring""" return len(self.data ) def __getitem__( self : List[str] , a : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = torch.LongTensor(self.tokenizer.encode(self.data[index]["text"] , add_special_tokens=a ) ) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = sentence[0], sentence[1:-1], sentence[-1] SCREAMING_SNAKE_CASE : List[Any] = sentence[: self.max_seq_length] SCREAMING_SNAKE_CASE : Union[str, Any] = torch.zeros(self.n_classes ) SCREAMING_SNAKE_CASE : int = 1 SCREAMING_SNAKE_CASE : List[Any] = Image.open(os.path.join(self.data_dir , self.data[index]["img"] ) ).convert("RGB" ) SCREAMING_SNAKE_CASE : str = self.transforms(a ) return { "image_start_token": start_token, "image_end_token": end_token, "sentence": sentence, "image": image, "label": label, } def __UpperCamelCase ( self : str ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = Counter() for row in self.data: label_freqs.update(row["label"] ) return label_freqs def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : str = [len(row["sentence"]) for row in batch] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[Any] = len(_a), max(_a) SCREAMING_SNAKE_CASE : Any = torch.zeros(_a , _a , dtype=torch.long) SCREAMING_SNAKE_CASE : List[str] = torch.zeros(_a , _a , dtype=torch.long) for i_batch, (input_row, length) in enumerate(zip(_a , _a)): SCREAMING_SNAKE_CASE : str = input_row["sentence"] SCREAMING_SNAKE_CASE : Any = 1 SCREAMING_SNAKE_CASE : str = torch.stack([row["image"] for row in batch]) SCREAMING_SNAKE_CASE : str = torch.stack([row["label"] for row in batch]) SCREAMING_SNAKE_CASE : Tuple = torch.stack([row["image_start_token"] for row in batch]) SCREAMING_SNAKE_CASE : Optional[int] = torch.stack([row["image_end_token"] for row in batch]) return text_tensor, mask_tensor, img_tensor, img_start_token, img_end_token, tgt_tensor def lowerCamelCase__ ( ): return [ "Crime", "Drama", "Thriller", "Action", "Comedy", "Romance", "Documentary", "Short", "Mystery", "History", "Family", "Adventure", "Fantasy", "Sci-Fi", "Western", "Horror", "Sport", "War", "Music", "Musical", "Animation", "Biography", "Film-Noir", ] def lowerCamelCase__ ( ): return transforms.Compose( [ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize( mean=[0.4677_7044, 0.4453_1429, 0.4066_1017] , std=[0.1222_1994, 0.1214_5835, 0.1438_0469] , ), ])
76
from math import factorial def lowerCamelCase__ ( _a , _a , _a): if successes > trials: raise ValueError("successes must be lower or equal to trials") if trials < 0 or successes < 0: raise ValueError("the function is defined for non-negative integers") if not isinstance(_a , _a) or not isinstance(_a , _a): raise ValueError("the function is defined for non-negative integers") if not 0 < prob < 1: raise ValueError("prob has to be in range of 1 - 0") SCREAMING_SNAKE_CASE : int = (prob**successes) * ((1 - prob) ** (trials - successes)) # Calculate the binomial coefficient: n! / k!(n-k)! SCREAMING_SNAKE_CASE : List[Any] = float(factorial(_a)) coefficient /= factorial(_a) * factorial(trials - successes) return probability * coefficient if __name__ == "__main__": from doctest import testmod testmod() print('Probability of 2 successes out of 4 trails') print('with probability of 0.75 is:', end=' ') print(binomial_distribution(2, 4, 0.75))
76
1
from collections.abc import Callable def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : float = a SCREAMING_SNAKE_CASE : float = b if function(_a) == 0: # one of the a or b is a root for the function return a elif function(_a) == 0: return b elif ( function(_a) * function(_a) > 0 ): # if none of these are root and they are both positive or negative, # then this algorithm can't find the root raise ValueError("could not find root in given interval.") else: SCREAMING_SNAKE_CASE : float = start + (end - start) / 2.0 while abs(start - mid) > 10**-7: # until precisely equals to 10^-7 if function(_a) == 0: return mid elif function(_a) * function(_a) < 0: SCREAMING_SNAKE_CASE : List[Any] = mid else: SCREAMING_SNAKE_CASE : List[str] = mid SCREAMING_SNAKE_CASE : Any = start + (end - start) / 2.0 return mid def lowerCamelCase__ ( _a): return x**3 - 2 * x - 5 if __name__ == "__main__": print(bisection(f, 1, 1000)) import doctest doctest.testmod()
76
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =CustomTokenizer pass
76
1
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available a_ = { 'configuration_megatron_bert': ['MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegatronBertConfig'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'MegatronBertForCausalLM', 'MegatronBertForMaskedLM', 'MegatronBertForMultipleChoice', 'MegatronBertForNextSentencePrediction', 'MegatronBertForPreTraining', 'MegatronBertForQuestionAnswering', 'MegatronBertForSequenceClassification', 'MegatronBertForTokenClassification', 'MegatronBertModel', 'MegatronBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_megatron_bert import MEGATRON_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MegatronBertConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_megatron_bert import ( MEGATRON_BERT_PRETRAINED_MODEL_ARCHIVE_LIST, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, MegatronBertPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex a_ = logging.getLogger(__name__) class _UpperCamelCase : '''simple docstring''' def __init__( self : Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = False def __UpperCamelCase ( self : str , a : str , a : Optional[int] , a : Any , a : str ) -> List[Any]: """simple docstring""" if not self.initialized: SCREAMING_SNAKE_CASE : List[str] = RagRetriever( a , question_encoder_tokenizer=a , generator_tokenizer=a , index=a , init_retrieval=a , ) SCREAMING_SNAKE_CASE : Optional[int] = True def __UpperCamelCase ( self : List[str] ) -> Optional[int]: """simple docstring""" self.retriever.index.init_index() def __UpperCamelCase ( self : Optional[Any] , a : List[Any] , a : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = self.retriever._main_retrieve(a , a ) return doc_ids, retrieved_doc_embeds class _UpperCamelCase ( __A ): '''simple docstring''' def __init__( self : Tuple , a : Any , a : Tuple , a : Tuple , a : Tuple , a : List[Any]=None ) -> Optional[int]: """simple docstring""" if index is not None and index.is_initialized() and len(a ) > 0: raise ValueError( "When using Ray for distributed fine-tuning, " "you'll need to provide the paths instead, " "as the dataset and the index are loaded " "separately. More info in examples/rag/use_own_knowledge_dataset.py " ) super().__init__( a , question_encoder_tokenizer=a , generator_tokenizer=a , index=a , init_retrieval=a , ) SCREAMING_SNAKE_CASE : Optional[Any] = retrieval_workers if len(self.retrieval_workers ) > 0: ray.get( [ worker.create_rag_retriever.remote(a , a , a , a ) for worker in self.retrieval_workers ] ) def __UpperCamelCase ( self : Any ) -> Dict: """simple docstring""" logger.info("initializing retrieval" ) if len(self.retrieval_workers ) > 0: ray.get([worker.init_retrieval.remote() for worker in self.retrieval_workers] ) else: # Non-distributed training. Load index into this same process. self.index.init_index() def __UpperCamelCase ( self : Tuple , a : Optional[int] , a : Any ) -> int: """simple docstring""" if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. SCREAMING_SNAKE_CASE : Optional[Any] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = ray.get(random_worker.retrieve.remote(a , a ) ) else: SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Any = self._main_retrieve(a , a ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(a ) @classmethod def __UpperCamelCase ( cls : str , a : Optional[Any] , a : Any=None , **a : List[Any] ) -> str: """simple docstring""" return super(a , cls ).get_tokenizers(a , a , **a ) @classmethod def __UpperCamelCase ( cls : Union[str, Any] , a : int , a : Any , a : List[Any]=None , **a : Optional[Any] ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : str = kwargs.pop("config" , a ) or RagConfig.from_pretrained(a , **a ) SCREAMING_SNAKE_CASE : List[Any] = RagTokenizer.from_pretrained(a , config=a ) SCREAMING_SNAKE_CASE : List[Any] = rag_tokenizer.question_encoder SCREAMING_SNAKE_CASE : List[Any] = rag_tokenizer.generator if indexed_dataset is not None: SCREAMING_SNAKE_CASE : str = "custom" SCREAMING_SNAKE_CASE : List[Any] = CustomHFIndex(config.retrieval_vector_size , a ) else: SCREAMING_SNAKE_CASE : List[str] = cls._build_index(a ) return cls( a , question_encoder_tokenizer=a , generator_tokenizer=a , retrieval_workers=a , index=a , )
76
1
from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel from ...schedulers import KarrasVeScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =42 lowerCamelCase__ =42 def __init__( self : Dict , a : UNetaDModel , a : KarrasVeScheduler ) -> Tuple: """simple docstring""" super().__init__() self.register_modules(unet=a , scheduler=a ) @torch.no_grad() def __call__( self : List[str] , a : int = 1 , a : int = 50 , a : Optional[Union[torch.Generator, List[torch.Generator]]] = None , a : Optional[str] = "pil" , a : bool = True , **a : Optional[Any] , ) -> Union[Tuple, ImagePipelineOutput]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.unet.config.sample_size SCREAMING_SNAKE_CASE : Union[str, Any] = (batch_size, 3, img_size, img_size) SCREAMING_SNAKE_CASE : str = self.unet # sample x_0 ~ N(0, sigma_0^2 * I) SCREAMING_SNAKE_CASE : Optional[int] = randn_tensor(a , generator=a , device=self.device ) * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(a ) for t in self.progress_bar(self.scheduler.timesteps ): # here sigma_t == t_i from the paper SCREAMING_SNAKE_CASE : str = self.scheduler.schedule[t] SCREAMING_SNAKE_CASE : Union[str, Any] = self.scheduler.schedule[t - 1] if t > 0 else 0 # 1. Select temporarily increased noise level sigma_hat # 2. Add new noise to move from sample_i to sample_hat SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.add_noise_to_input(a , a , generator=a ) # 3. Predict the noise residual given the noise magnitude `sigma_hat` # The model inputs and output are adjusted by following eq. (213) in [1]. SCREAMING_SNAKE_CASE : Tuple = (sigma_hat / 2) * model((sample_hat + 1) / 2 , sigma_hat / 2 ).sample # 4. Evaluate dx/dt at sigma_hat # 5. Take Euler step from sigma to sigma_prev SCREAMING_SNAKE_CASE : List[str] = self.scheduler.step(a , a , a , a ) if sigma_prev != 0: # 6. Apply 2nd order correction # The model inputs and output are adjusted by following eq. (213) in [1]. SCREAMING_SNAKE_CASE : Any = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 , sigma_prev / 2 ).sample SCREAMING_SNAKE_CASE : Tuple = self.scheduler.step_correct( a , a , a , a , step_output.prev_sample , step_output["derivative"] , ) SCREAMING_SNAKE_CASE : Dict = step_output.prev_sample SCREAMING_SNAKE_CASE : Tuple = (sample / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE : List[Any] = sample.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": SCREAMING_SNAKE_CASE : Tuple = self.numpy_to_pil(a ) if not return_dict: return (image,) return ImagePipelineOutput(images=a )
76
from typing import Any class _UpperCamelCase : '''simple docstring''' def __init__( self : Dict , a : Any ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : int = data SCREAMING_SNAKE_CASE : int = None def __repr__( self : str ) -> str: """simple docstring""" return F"Node({self.data})" class _UpperCamelCase : '''simple docstring''' def __init__( self : List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Any = None def __iter__( self : Any ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.head while node: yield node.data SCREAMING_SNAKE_CASE : List[str] = node.next def __len__( self : str ) -> int: """simple docstring""" return sum(1 for _ in self ) def __repr__( self : Optional[Any] ) -> str: """simple docstring""" return "->".join([str(a ) for item in self] ) def __getitem__( self : List[Any] , a : int ) -> Any: """simple docstring""" if not 0 <= index < len(self ): raise ValueError("list index out of range." ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Tuple , a : int , a : Any ) -> None: """simple docstring""" if not 0 <= index < len(self ): raise ValueError("list index out of range." ) SCREAMING_SNAKE_CASE : str = self.head for _ in range(a ): SCREAMING_SNAKE_CASE : str = current.next SCREAMING_SNAKE_CASE : Any = data def __UpperCamelCase ( self : List[str] , a : Any ) -> None: """simple docstring""" self.insert_nth(len(self ) , a ) def __UpperCamelCase ( self : Union[str, Any] , a : Any ) -> None: """simple docstring""" self.insert_nth(0 , a ) def __UpperCamelCase ( self : Optional[Any] , a : int , a : Any ) -> None: """simple docstring""" if not 0 <= index <= len(self ): raise IndexError("list index out of range" ) SCREAMING_SNAKE_CASE : Any = Node(a ) if self.head is None: SCREAMING_SNAKE_CASE : Optional[int] = new_node elif index == 0: SCREAMING_SNAKE_CASE : Optional[int] = self.head # link new_node to head SCREAMING_SNAKE_CASE : List[Any] = new_node else: SCREAMING_SNAKE_CASE : Optional[Any] = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : Optional[int] = temp.next SCREAMING_SNAKE_CASE : Optional[int] = temp.next SCREAMING_SNAKE_CASE : int = new_node def __UpperCamelCase ( self : Optional[int] ) -> None: # print every node data """simple docstring""" print(self ) def __UpperCamelCase ( self : int ) -> Any: """simple docstring""" return self.delete_nth(0 ) def __UpperCamelCase ( self : Any ) -> Any: # delete from tail """simple docstring""" return self.delete_nth(len(self ) - 1 ) def __UpperCamelCase ( self : List[str] , a : int = 0 ) -> Any: """simple docstring""" if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError("List index out of range." ) SCREAMING_SNAKE_CASE : Tuple = self.head # default first node if index == 0: SCREAMING_SNAKE_CASE : List[str] = self.head.next else: SCREAMING_SNAKE_CASE : Optional[Any] = self.head for _ in range(index - 1 ): SCREAMING_SNAKE_CASE : Any = temp.next SCREAMING_SNAKE_CASE : List[Any] = temp.next SCREAMING_SNAKE_CASE : List[str] = temp.next.next return delete_node.data def __UpperCamelCase ( self : List[Any] ) -> bool: """simple docstring""" return self.head is None def __UpperCamelCase ( self : Optional[int] ) -> None: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = None SCREAMING_SNAKE_CASE : str = self.head while current: # Store the current node's next node. SCREAMING_SNAKE_CASE : Any = current.next # Make the current node's next point backwards SCREAMING_SNAKE_CASE : List[Any] = prev # Make the previous node be the current node SCREAMING_SNAKE_CASE : Any = current # Make the current node the next node (to progress iteration) SCREAMING_SNAKE_CASE : str = next_node # Return prev in order to put the head at the end SCREAMING_SNAKE_CASE : Optional[Any] = prev def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Union[str, Any] = LinkedList() assert linked_list.is_empty() is True assert str(_a) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10): assert len(_a) == i linked_list.insert_nth(_a , i + 1) assert str(_a) == "->".join(str(_a) for i in range(1 , 11)) linked_list.insert_head(0) linked_list.insert_tail(11) assert str(_a) == "->".join(str(_a) for i in range(0 , 12)) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9) == 10 assert linked_list.delete_tail() == 11 assert len(_a) == 9 assert str(_a) == "->".join(str(_a) for i in range(1 , 10)) assert all(linked_list[i] == i + 1 for i in range(0 , 9)) is True for i in range(0 , 9): SCREAMING_SNAKE_CASE : str = -i assert all(linked_list[i] == -i for i in range(0 , 9)) is True linked_list.reverse() assert str(_a) == "->".join(str(_a) for i in range(-8 , 1)) def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Optional[Any] = [ -9, 100, Node(77345112), "dlrow olleH", 7, 5555, 0, -192.5_5555, "Hello, world!", 77.9, Node(10), None, None, 12.20, ] SCREAMING_SNAKE_CASE : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(_a) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(_a) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head SCREAMING_SNAKE_CASE : List[Any] = linked_list.delete_head() assert result == -9 assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail SCREAMING_SNAKE_CASE : Any = linked_list.delete_tail() assert result == 12.2 assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list SCREAMING_SNAKE_CASE : Any = linked_list.delete_nth(10) assert result is None assert ( str(_a) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node("Hello again, world!")) assert ( str(_a) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(_a) assert ( str(_a) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(_a) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def lowerCamelCase__ ( ): from doctest import testmod testmod() SCREAMING_SNAKE_CASE : Optional[int] = LinkedList() linked_list.insert_head(input("Inserting 1st at head ").strip()) linked_list.insert_head(input("Inserting 2nd at head ").strip()) print("\nPrint list:") linked_list.print_list() linked_list.insert_tail(input("\nInserting 1st at tail ").strip()) linked_list.insert_tail(input("Inserting 2nd at tail ").strip()) print("\nPrint list:") linked_list.print_list() print("\nDelete head") linked_list.delete_head() print("Delete tail") linked_list.delete_tail() print("\nPrint list:") linked_list.print_list() print("\nReverse linked list") linked_list.reverse() print("\nPrint list:") linked_list.print_list() print("\nString representation of linked list:") print(_a) print("\nReading/changing Node data using indexing:") print(f"Element at Position 1: {linked_list[1]}") SCREAMING_SNAKE_CASE : Dict = input("Enter New Value: ").strip() print("New list:") print(_a) print(f"length of linked_list is : {len(_a)}") if __name__ == "__main__": main()
76
1
import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Optional[Any] = f"{sampling_rate}" SCREAMING_SNAKE_CASE : Optional[int] = "1" SCREAMING_SNAKE_CASE : Any = "f32le" SCREAMING_SNAKE_CASE : Union[str, Any] = [ "ffmpeg", "-i", "pipe:0", "-ac", ac, "-ar", ar, "-f", format_for_conversion, "-hide_banner", "-loglevel", "quiet", "pipe:1", ] try: with subprocess.Popen(_a , stdin=subprocess.PIPE , stdout=subprocess.PIPE) as ffmpeg_process: SCREAMING_SNAKE_CASE : List[str] = ffmpeg_process.communicate(_a) except FileNotFoundError as error: raise ValueError("ffmpeg was not found but is required to load audio files from filename") from error SCREAMING_SNAKE_CASE : List[Any] = output_stream[0] SCREAMING_SNAKE_CASE : Any = np.frombuffer(_a , np.floataa) if audio.shape[0] == 0: raise ValueError("Malformed soundfile") return audio def lowerCamelCase__ ( _a , _a , _a = "f32le" , ): SCREAMING_SNAKE_CASE : Any = f"{sampling_rate}" SCREAMING_SNAKE_CASE : Dict = "1" if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE : Tuple = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE : Dict = 4 else: raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`") SCREAMING_SNAKE_CASE : Optional[int] = platform.system() if system == "Linux": SCREAMING_SNAKE_CASE : Dict = "alsa" SCREAMING_SNAKE_CASE : Any = "default" elif system == "Darwin": SCREAMING_SNAKE_CASE : Optional[Any] = "avfoundation" SCREAMING_SNAKE_CASE : Optional[int] = ":0" elif system == "Windows": SCREAMING_SNAKE_CASE : str = "dshow" SCREAMING_SNAKE_CASE : Tuple = "default" SCREAMING_SNAKE_CASE : Union[str, Any] = [ "ffmpeg", "-f", format_, "-i", input_, "-ac", ac, "-ar", ar, "-f", format_for_conversion, "-fflags", "nobuffer", "-hide_banner", "-loglevel", "quiet", "pipe:1", ] SCREAMING_SNAKE_CASE : List[str] = int(round(sampling_rate * chunk_length_s)) * size_of_sample SCREAMING_SNAKE_CASE : Tuple = _ffmpeg_stream(_a , _a) for item in iterator: yield item def lowerCamelCase__ ( _a , _a , _a = None , _a = None , _a = "f32le" , ): if stream_chunk_s is not None: SCREAMING_SNAKE_CASE : List[Any] = stream_chunk_s else: SCREAMING_SNAKE_CASE : Tuple = chunk_length_s SCREAMING_SNAKE_CASE : str = ffmpeg_microphone(_a , _a , format_for_conversion=_a) if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE : Tuple = np.intaa SCREAMING_SNAKE_CASE : Union[str, Any] = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE : Union[str, Any] = np.floataa SCREAMING_SNAKE_CASE : Dict = 4 else: raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`") if stride_length_s is None: SCREAMING_SNAKE_CASE : Tuple = chunk_length_s / 6 SCREAMING_SNAKE_CASE : Tuple = int(round(sampling_rate * chunk_length_s)) * size_of_sample if isinstance(_a , (int, float)): SCREAMING_SNAKE_CASE : Any = [stride_length_s, stride_length_s] SCREAMING_SNAKE_CASE : Any = int(round(sampling_rate * stride_length_s[0])) * size_of_sample SCREAMING_SNAKE_CASE : int = int(round(sampling_rate * stride_length_s[1])) * size_of_sample SCREAMING_SNAKE_CASE : Optional[int] = datetime.datetime.now() SCREAMING_SNAKE_CASE : Union[str, Any] = datetime.timedelta(seconds=_a) for item in chunk_bytes_iter(_a , _a , stride=(stride_left, stride_right) , stream=_a): # Put everything back in numpy scale SCREAMING_SNAKE_CASE : List[Any] = np.frombuffer(item["raw"] , dtype=_a) SCREAMING_SNAKE_CASE : Optional[Any] = ( item["stride"][0] // size_of_sample, item["stride"][1] // size_of_sample, ) SCREAMING_SNAKE_CASE : List[str] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def lowerCamelCase__ ( _a , _a , _a , _a = False): SCREAMING_SNAKE_CASE : int = b"" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[str] = stride if stride_left + stride_right >= chunk_len: raise ValueError( f"Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}") SCREAMING_SNAKE_CASE : List[str] = 0 for raw in iterator: acc += raw if stream and len(_a) < chunk_len: SCREAMING_SNAKE_CASE : Any = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(_a) >= chunk_len: # We are flushing the accumulator SCREAMING_SNAKE_CASE : Tuple = (_stride_left, stride_right) SCREAMING_SNAKE_CASE : Optional[Any] = {"raw": acc[:chunk_len], "stride": stride} if stream: SCREAMING_SNAKE_CASE : Optional[Any] = False yield item SCREAMING_SNAKE_CASE : Union[str, Any] = stride_left SCREAMING_SNAKE_CASE : List[str] = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(_a) > stride_left: SCREAMING_SNAKE_CASE : Optional[int] = {"raw": acc, "stride": (_stride_left, 0)} if stream: SCREAMING_SNAKE_CASE : str = False yield item def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Tuple = 2**24 # 16Mo try: with subprocess.Popen(_a , stdout=subprocess.PIPE , bufsize=_a) as ffmpeg_process: while True: SCREAMING_SNAKE_CASE : Tuple = ffmpeg_process.stdout.read(_a) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError("ffmpeg was not found but is required to stream audio files from filename") from error
76
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger a_ = get_logger(__name__) class _UpperCamelCase ( enum.Enum ): '''simple docstring''' lowerCamelCase__ ='all_checks' lowerCamelCase__ ='basic_checks' lowerCamelCase__ ='no_checks' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' def lowerCamelCase__ ( _a , _a , _a=None): if expected_checksums is None: logger.info("Unable to verify checksums.") return if len(set(_a) - set(_a)) > 0: raise ExpectedMoreDownloadedFiles(str(set(_a) - set(_a))) if len(set(_a) - set(_a)) > 0: raise UnexpectedDownloadedFile(str(set(_a) - set(_a))) SCREAMING_SNAKE_CASE : str = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] SCREAMING_SNAKE_CASE : Tuple = " for " + verification_name if verification_name is not None else "" if len(_a) > 0: raise NonMatchingChecksumError( f"Checksums didn't match{for_verification_name}:\n" f"{bad_urls}\n" "Set `verification_mode='no_checks'` to skip checksums verification and ignore this error") logger.info("All the checksums matched successfully" + for_verification_name) class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' class _UpperCamelCase ( __A ): '''simple docstring''' def lowerCamelCase__ ( _a , _a): if expected_splits is None: logger.info("Unable to verify splits sizes.") return if len(set(_a) - set(_a)) > 0: raise ExpectedMoreSplits(str(set(_a) - set(_a))) if len(set(_a) - set(_a)) > 0: raise UnexpectedSplits(str(set(_a) - set(_a))) SCREAMING_SNAKE_CASE : List[str] = [ {"expected": expected_splits[name], "recorded": recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(_a) > 0: raise NonMatchingSplitsSizesError(str(_a)) logger.info("All the splits matched successfully.") def lowerCamelCase__ ( _a , _a = True): if record_checksum: SCREAMING_SNAKE_CASE : List[str] = shaaaa() with open(_a , "rb") as f: for chunk in iter(lambda: f.read(1 << 20) , b""): m.update(_a) SCREAMING_SNAKE_CASE : Optional[int] = m.hexdigest() else: SCREAMING_SNAKE_CASE : List[str] = None return {"num_bytes": os.path.getsize(_a), "checksum": checksum} def lowerCamelCase__ ( _a): if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
76
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) a_ = { 'configuration_perceiver': ['PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PerceiverConfig', 'PerceiverOnnxConfig'], 'tokenization_perceiver': ['PerceiverTokenizer'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = ['PerceiverFeatureExtractor'] a_ = ['PerceiverImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ = [ 'PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST', 'PerceiverForImageClassificationConvProcessing', 'PerceiverForImageClassificationFourier', 'PerceiverForImageClassificationLearned', 'PerceiverForMaskedLM', 'PerceiverForMultimodalAutoencoding', 'PerceiverForOpticalFlow', 'PerceiverForSequenceClassification', 'PerceiverLayer', 'PerceiverModel', 'PerceiverPreTrainedModel', ] if TYPE_CHECKING: from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig from .tokenization_perceiver import PerceiverTokenizer try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_perceiver import PerceiverFeatureExtractor from .image_processing_perceiver import PerceiverImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_perceiver import ( PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST, PerceiverForImageClassificationConvProcessing, PerceiverForImageClassificationFourier, PerceiverForImageClassificationLearned, PerceiverForMaskedLM, PerceiverForMultimodalAutoencoding, PerceiverForOpticalFlow, PerceiverForSequenceClassification, PerceiverLayer, PerceiverModel, PerceiverPreTrainedModel, ) else: import sys a_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
76
import argparse import json import numpy import torch from transformers.models.xlm.tokenization_xlm import VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() def lowerCamelCase__ ( _a , _a): # Load checkpoint SCREAMING_SNAKE_CASE : int = torch.load(_a , map_location="cpu") SCREAMING_SNAKE_CASE : Dict = chkpt["model"] # We have the base model one level deeper than the original XLM repository SCREAMING_SNAKE_CASE : Optional[int] = {} for k, v in state_dict.items(): if "pred_layer" in k: SCREAMING_SNAKE_CASE : List[str] = v else: SCREAMING_SNAKE_CASE : int = v SCREAMING_SNAKE_CASE : int = chkpt["params"] SCREAMING_SNAKE_CASE : Union[str, Any] = {n: v for n, v in config.items() if not isinstance(_a , (torch.FloatTensor, numpy.ndarray))} SCREAMING_SNAKE_CASE : List[Any] = chkpt["dico_word2id"] SCREAMING_SNAKE_CASE : List[Any] = {s + "</w>" if s.find("@@") == -1 and i > 13 else s.replace("@@" , ""): i for s, i in vocab.items()} # Save pytorch-model SCREAMING_SNAKE_CASE : Tuple = pytorch_dump_folder_path + "/" + WEIGHTS_NAME SCREAMING_SNAKE_CASE : Any = pytorch_dump_folder_path + "/" + CONFIG_NAME SCREAMING_SNAKE_CASE : Optional[int] = pytorch_dump_folder_path + "/" + VOCAB_FILES_NAMES["vocab_file"] print(f"Save PyTorch model to {pytorch_weights_dump_path}") torch.save(_a , _a) print(f"Save configuration file to {pytorch_config_dump_path}") with open(_a , "w" , encoding="utf-8") as f: f.write(json.dumps(_a , indent=2) + "\n") print(f"Save vocab file to {pytorch_config_dump_path}") with open(_a , "w" , encoding="utf-8") as f: f.write(json.dumps(_a , indent=2) + "\n") if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xlm_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) a_ = parser.parse_args() convert_xlm_checkpoint_to_pytorch(args.xlm_checkpoint_path, args.pytorch_dump_folder_path)
76
1
import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Any ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = "ZinengTang/tvlt-base" SCREAMING_SNAKE_CASE : str = tempfile.mkdtemp() def __UpperCamelCase ( self : Dict , **a : List[Any] ) -> List[Any]: """simple docstring""" return TvltImageProcessor.from_pretrained(self.checkpoint , **a ) def __UpperCamelCase ( self : List[Any] , **a : List[Any] ) -> List[Any]: """simple docstring""" return TvltFeatureExtractor.from_pretrained(self.checkpoint , **a ) def __UpperCamelCase ( self : int ) -> Any: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __UpperCamelCase ( self : Any ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : int = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = self.get_feature_extractor() SCREAMING_SNAKE_CASE : Dict = TvltProcessor(image_processor=a , feature_extractor=a ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE : Optional[Any] = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , a ) self.assertIsInstance(processor.image_processor , a ) def __UpperCamelCase ( self : str ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = self.get_feature_extractor() SCREAMING_SNAKE_CASE : Dict = TvltProcessor(image_processor=a , feature_extractor=a ) SCREAMING_SNAKE_CASE : Optional[Any] = np.ones([1_2000] ) SCREAMING_SNAKE_CASE : Any = feature_extractor(a , return_tensors="np" ) SCREAMING_SNAKE_CASE : Tuple = processor(audio=a , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __UpperCamelCase ( self : Union[str, Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE : str = self.get_feature_extractor() SCREAMING_SNAKE_CASE : Union[str, Any] = TvltProcessor(image_processor=a , feature_extractor=a ) SCREAMING_SNAKE_CASE : Optional[Any] = np.ones([3, 224, 224] ) SCREAMING_SNAKE_CASE : Optional[int] = image_processor(a , return_tensors="np" ) SCREAMING_SNAKE_CASE : str = processor(images=a , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __UpperCamelCase ( self : Tuple ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : List[Any] = self.get_feature_extractor() SCREAMING_SNAKE_CASE : Dict = TvltProcessor(image_processor=a , feature_extractor=a ) SCREAMING_SNAKE_CASE : Optional[Any] = np.ones([1_2000] ) SCREAMING_SNAKE_CASE : str = np.ones([3, 224, 224] ) SCREAMING_SNAKE_CASE : Union[str, Any] = processor(audio=a , images=a ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(a ): processor() def __UpperCamelCase ( self : Optional[int] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE : Optional[int] = self.get_feature_extractor() SCREAMING_SNAKE_CASE : Union[str, Any] = TvltProcessor(image_processor=a , feature_extractor=a ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
76
def lowerCamelCase__ ( _a , _a): _validate_point(_a) _validate_point(_a) if len(_a) != len(_a): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(a - b) for a, b in zip(_a , _a))) def lowerCamelCase__ ( _a): if point: if isinstance(_a , _a): for item in point: if not isinstance(_a , (int, float)): SCREAMING_SNAKE_CASE : List[Any] = ( "Expected a list of numbers as input, found " f"{type(_a).__name__}" ) raise TypeError(_a) else: SCREAMING_SNAKE_CASE : List[Any] = f"Expected a list of numbers as input, found {type(_a).__name__}" raise TypeError(_a) else: raise ValueError("Missing an input") def lowerCamelCase__ ( _a , _a): _validate_point(_a) _validate_point(_a) if len(_a) != len(_a): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(x - y) for x, y in zip(_a , _a))) if __name__ == "__main__": import doctest doctest.testmod()
76
1
import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Union[str, Any] , a : Optional[int] , a : str=13 , a : str=7 , a : List[Any]=True , a : List[str]=True , a : int=True , a : Any=True , a : Tuple=99 , a : int=32 , a : Union[str, Any]=5 , a : str=4 , a : Optional[Any]=37 , a : Optional[Any]="gelu" , a : Any=0.1 , a : Optional[Any]=0.1 , a : Any=512 , a : int=16 , a : Optional[int]=2 , a : Optional[int]=0.02 , a : str=4 , ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : str = parent SCREAMING_SNAKE_CASE : List[str] = batch_size SCREAMING_SNAKE_CASE : Optional[Any] = seq_length SCREAMING_SNAKE_CASE : List[Any] = is_training SCREAMING_SNAKE_CASE : Optional[Any] = use_attention_mask SCREAMING_SNAKE_CASE : Any = use_token_type_ids SCREAMING_SNAKE_CASE : Optional[Any] = use_labels SCREAMING_SNAKE_CASE : List[Any] = vocab_size SCREAMING_SNAKE_CASE : int = hidden_size SCREAMING_SNAKE_CASE : int = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE : List[str] = intermediate_size SCREAMING_SNAKE_CASE : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE : int = type_vocab_size SCREAMING_SNAKE_CASE : List[Any] = type_sequence_label_size SCREAMING_SNAKE_CASE : List[str] = initializer_range SCREAMING_SNAKE_CASE : str = num_choices def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE : Union[str, Any] = None if self.use_attention_mask: SCREAMING_SNAKE_CASE : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE : Optional[Any] = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def __UpperCamelCase ( self : Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE : Dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =True lowerCamelCase__ =( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def __UpperCamelCase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = FlaxRoFormerModelTester(self ) @slow def __UpperCamelCase ( self : int ) -> Optional[Any]: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE : int = model_class_name.from_pretrained("junnyu/roformer_chinese_small" , from_pt=a ) SCREAMING_SNAKE_CASE : Any = model(np.ones((1, 1) ) ) self.assertIsNotNone(a ) @require_flax class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def __UpperCamelCase ( self : Tuple ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[Any] = FlaxRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base" ) SCREAMING_SNAKE_CASE : Tuple = jnp.array([[0, 1, 2, 3, 4, 5]] ) SCREAMING_SNAKE_CASE : Tuple = model(a )[0] SCREAMING_SNAKE_CASE : Optional[int] = 5_0000 SCREAMING_SNAKE_CASE : Any = (1, 6, vocab_size) self.assertEqual(output.shape , a ) SCREAMING_SNAKE_CASE : Any = jnp.array( [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , a , atol=1e-4 ) )
76
from ...configuration_utils import PretrainedConfig from ...utils import logging a_ = logging.get_logger(__name__) a_ = { 'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json', # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ ='vit_msn' def __init__( self : str , a : Tuple=768 , a : Tuple=12 , a : Any=12 , a : int=3072 , a : List[Any]="gelu" , a : Dict=0.0 , a : int=0.0 , a : str=0.02 , a : List[str]=1e-06 , a : List[Any]=224 , a : Union[str, Any]=16 , a : Union[str, Any]=3 , a : Tuple=True , **a : Dict , ) -> List[Any]: """simple docstring""" super().__init__(**a ) SCREAMING_SNAKE_CASE : Dict = hidden_size SCREAMING_SNAKE_CASE : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE : Optional[Any] = num_attention_heads SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE : int = hidden_act SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Any = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : List[Any] = initializer_range SCREAMING_SNAKE_CASE : int = layer_norm_eps SCREAMING_SNAKE_CASE : Dict = image_size SCREAMING_SNAKE_CASE : Tuple = patch_size SCREAMING_SNAKE_CASE : Optional[int] = num_channels SCREAMING_SNAKE_CASE : List[str] = qkv_bias
76
1
import re import jax.numpy as jnp from flax.traverse_util import flatten_dict, unflatten_dict from jax.random import PRNGKey from ..utils import logging a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Any = r"\w+[.]\d+" SCREAMING_SNAKE_CASE : List[str] = re.findall(_a , _a) for pat in pats: SCREAMING_SNAKE_CASE : List[str] = key.replace(_a , "_".join(pat.split("."))) return key def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : Optional[int] = pt_tuple_key[:-1] + ("scale",) if ( any("norm" in str_ for str_ in pt_tuple_key) and (pt_tuple_key[-1] == "bias") and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict) and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict) ): SCREAMING_SNAKE_CASE : List[Any] = pt_tuple_key[:-1] + ("scale",) return renamed_pt_tuple_key, pt_tensor elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict: SCREAMING_SNAKE_CASE : int = pt_tuple_key[:-1] + ("scale",) return renamed_pt_tuple_key, pt_tensor # embedding if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict: SCREAMING_SNAKE_CASE : List[Any] = pt_tuple_key[:-1] + ("embedding",) return renamed_pt_tuple_key, pt_tensor # conv layer SCREAMING_SNAKE_CASE : int = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4: SCREAMING_SNAKE_CASE : Union[str, Any] = pt_tensor.transpose(2 , 3 , 1 , 0) return renamed_pt_tuple_key, pt_tensor # linear layer SCREAMING_SNAKE_CASE : str = pt_tuple_key[:-1] + ("kernel",) if pt_tuple_key[-1] == "weight": SCREAMING_SNAKE_CASE : Tuple = pt_tensor.T return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm weight SCREAMING_SNAKE_CASE : Tuple = pt_tuple_key[:-1] + ("weight",) if pt_tuple_key[-1] == "gamma": return renamed_pt_tuple_key, pt_tensor # old PyTorch layer norm bias SCREAMING_SNAKE_CASE : Dict = pt_tuple_key[:-1] + ("bias",) if pt_tuple_key[-1] == "beta": return renamed_pt_tuple_key, pt_tensor return pt_tuple_key, pt_tensor def lowerCamelCase__ ( _a , _a , _a=42): # Step 1: Convert pytorch tensor to numpy SCREAMING_SNAKE_CASE : Optional[int] = {k: v.numpy() for k, v in pt_state_dict.items()} # Step 2: Since the model is stateless, get random Flax params SCREAMING_SNAKE_CASE : str = flax_model.init_weights(PRNGKey(_a)) SCREAMING_SNAKE_CASE : str = flatten_dict(_a) SCREAMING_SNAKE_CASE : Any = {} # Need to change some parameters name to match Flax names for pt_key, pt_tensor in pt_state_dict.items(): SCREAMING_SNAKE_CASE : Tuple = rename_key(_a) SCREAMING_SNAKE_CASE : Any = tuple(renamed_pt_key.split(".")) # Correctly rename weight parameters SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[Any] = rename_key_and_reshape_tensor(_a , _a , _a) if flax_key in random_flax_state_dict: if flax_tensor.shape != random_flax_state_dict[flax_key].shape: raise ValueError( f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape " f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.") # also add unexpected weight so that warning is thrown SCREAMING_SNAKE_CASE : List[Any] = jnp.asarray(_a) return unflatten_dict(_a)
76
import baseaa def lowerCamelCase__ ( _a): return baseaa.aaaencode(string.encode("utf-8")) def lowerCamelCase__ ( _a): return baseaa.aaadecode(_a).decode("utf-8") if __name__ == "__main__": import doctest doctest.testmod()
76
1
from __future__ import annotations def lowerCamelCase__ ( _a , _a): if b == 0: return (1, 0) ((SCREAMING_SNAKE_CASE) ,(SCREAMING_SNAKE_CASE)) : Dict = extended_euclid(_a , a % b) SCREAMING_SNAKE_CASE : Tuple = a // b return (y, x - k * y) def lowerCamelCase__ ( _a , _a , _a , _a): ((SCREAMING_SNAKE_CASE) ,(SCREAMING_SNAKE_CASE)) : Dict = extended_euclid(_a , _a) SCREAMING_SNAKE_CASE : str = na * na SCREAMING_SNAKE_CASE : int = ra * x * na + ra * y * na return (n % m + m) % m def lowerCamelCase__ ( _a , _a): ((SCREAMING_SNAKE_CASE) ,(SCREAMING_SNAKE_CASE)) : List[str] = extended_euclid(_a , _a) if b < 0: SCREAMING_SNAKE_CASE : int = (b % n + n) % n return b def lowerCamelCase__ ( _a , _a , _a , _a): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = invert_modulo(_a , _a), invert_modulo(_a , _a) SCREAMING_SNAKE_CASE : List[Any] = na * na SCREAMING_SNAKE_CASE : str = ra * x * na + ra * y * na return (n % m + m) % m if __name__ == "__main__": from doctest import testmod testmod(name='chinese_remainder_theorem', verbose=True) testmod(name='chinese_remainder_theorem2', verbose=True) testmod(name='invert_modulo', verbose=True) testmod(name='extended_euclid', verbose=True)
76
from datetime import datetime as dt import os from github import Github a_ = [ 'good first issue', 'good second issue', 'good difficult issue', 'feature request', 'new model', 'wip', ] def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : int = Github(os.environ["GITHUB_TOKEN"]) SCREAMING_SNAKE_CASE : List[str] = g.get_repo("huggingface/transformers") SCREAMING_SNAKE_CASE : Optional[int] = repo.get_issues(state="open") for issue in open_issues: SCREAMING_SNAKE_CASE : List[Any] = sorted([comment for comment in issue.get_comments()] , key=lambda _a: i.created_at , reverse=_a) SCREAMING_SNAKE_CASE : str = comments[0] if len(_a) > 0 else None if ( last_comment is not None and last_comment.user.login == "github-actions[bot]" and (dt.utcnow() - issue.updated_at).days > 7 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would close issue {issue.number} since it has been 7 days of inactivity since bot mention.") issue.edit(state="closed") elif ( (dt.utcnow() - issue.updated_at).days > 23 and (dt.utcnow() - issue.created_at).days >= 30 and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) ): # print(f"Would add stale comment to {issue.number}") issue.create_comment( "This issue has been automatically marked as stale because it has not had " "recent activity. If you think this still needs to be addressed " "please comment on this thread.\n\nPlease note that issues that do not follow the " "[contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) " "are likely to be ignored.") if __name__ == "__main__": main()
76
1
def lowerCamelCase__ ( _a , _a): return abs(_a) if a == 0 else greatest_common_divisor(b % a , _a) def lowerCamelCase__ ( _a , _a): while y: # --> when y=0 then loop will terminate and return x as final GCD. SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Tuple = y, x % y return abs(_a) def lowerCamelCase__ ( ): try: SCREAMING_SNAKE_CASE : int = input("Enter two integers separated by comma (,): ").split(",") SCREAMING_SNAKE_CASE : Optional[int] = int(nums[0]) SCREAMING_SNAKE_CASE : Union[str, Any] = int(nums[1]) print( f"greatest_common_divisor({num_a}, {num_a}) = " f"{greatest_common_divisor(_a , _a)}") print(f"By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(_a , _a)}") except (IndexError, UnboundLocalError, ValueError): print("Wrong input") if __name__ == "__main__": main()
76
from typing import Dict, List, Optional, Union import numpy as np from transformers.utils import is_vision_available from transformers.utils.generic import TensorType from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, is_valid_image, to_numpy_array, valid_images, ) from ...utils import logging if is_vision_available(): import PIL a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): if isinstance(_a , (list, tuple)) and isinstance(videos[0] , (list, tuple)) and is_valid_image(videos[0][0]): return videos elif isinstance(_a , (list, tuple)) and is_valid_image(videos[0]): return [videos] elif is_valid_image(_a): return [[videos]] raise ValueError(f"Could not make batched video from {videos}") class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =['pixel_values'] def __init__( self : Optional[Any] , a : bool = True , a : Dict[str, int] = None , a : PILImageResampling = PILImageResampling.BILINEAR , a : bool = True , a : Dict[str, int] = None , a : bool = True , a : Union[int, float] = 1 / 255 , a : bool = True , a : bool = True , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , **a : Tuple , ) -> None: """simple docstring""" super().__init__(**a ) SCREAMING_SNAKE_CASE : Tuple = size if size is not None else {"shortest_edge": 256} SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : List[str] = crop_size if crop_size is not None else {"height": 224, "width": 224} SCREAMING_SNAKE_CASE : str = get_size_dict(a , param_name="crop_size" ) SCREAMING_SNAKE_CASE : Dict = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : Optional[int] = do_center_crop SCREAMING_SNAKE_CASE : int = crop_size SCREAMING_SNAKE_CASE : int = resample SCREAMING_SNAKE_CASE : Any = do_rescale SCREAMING_SNAKE_CASE : int = rescale_factor SCREAMING_SNAKE_CASE : Tuple = offset SCREAMING_SNAKE_CASE : str = do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN SCREAMING_SNAKE_CASE : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def __UpperCamelCase ( self : Optional[Any] , a : np.ndarray , a : Dict[str, int] , a : PILImageResampling = PILImageResampling.BILINEAR , a : Optional[Union[str, ChannelDimension]] = None , **a : Union[str, Any] , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = get_size_dict(a , default_to_square=a ) if "shortest_edge" in size: SCREAMING_SNAKE_CASE : str = get_resize_output_image_size(a , size["shortest_edge"] , default_to_square=a ) elif "height" in size and "width" in size: SCREAMING_SNAKE_CASE : Dict = (size["height"], size["width"]) else: raise ValueError(F"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}" ) return resize(a , size=a , resample=a , data_format=a , **a ) def __UpperCamelCase ( self : List[str] , a : np.ndarray , a : Dict[str, int] , a : Optional[Union[str, ChannelDimension]] = None , **a : str , ) -> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE : str = get_size_dict(a ) if "height" not in size or "width" not in size: raise ValueError(F"Size must have 'height' and 'width' as keys. Got {size.keys()}" ) return center_crop(a , size=(size["height"], size["width"]) , data_format=a , **a ) def __UpperCamelCase ( self : List[Any] , a : np.ndarray , a : Union[int, float] , a : bool = True , a : Optional[Union[str, ChannelDimension]] = None , **a : Tuple , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = image.astype(np.floataa ) if offset: SCREAMING_SNAKE_CASE : Union[str, Any] = image - (scale / 2) return rescale(a , scale=a , data_format=a , **a ) def __UpperCamelCase ( self : int , a : np.ndarray , a : Union[float, List[float]] , a : Union[float, List[float]] , a : Optional[Union[str, ChannelDimension]] = None , **a : List[str] , ) -> np.ndarray: """simple docstring""" return normalize(a , mean=a , std=a , data_format=a , **a ) def __UpperCamelCase ( self : Tuple , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[ChannelDimension] = ChannelDimension.FIRST , ) -> np.ndarray: """simple docstring""" if do_resize and size is None or resample is None: raise ValueError("Size and resample must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) if offset and not do_rescale: raise ValueError("For offset, do_rescale must also be set to True." ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE : List[str] = to_numpy_array(a ) if do_resize: SCREAMING_SNAKE_CASE : Optional[Any] = self.resize(image=a , size=a , resample=a ) if do_center_crop: SCREAMING_SNAKE_CASE : Union[str, Any] = self.center_crop(a , size=a ) if do_rescale: SCREAMING_SNAKE_CASE : Any = self.rescale(image=a , scale=a , offset=a ) if do_normalize: SCREAMING_SNAKE_CASE : Tuple = self.normalize(image=a , mean=a , std=a ) SCREAMING_SNAKE_CASE : Optional[int] = to_channel_dimension_format(a , a ) return image def __UpperCamelCase ( self : Dict , a : ImageInput , a : bool = None , a : Dict[str, int] = None , a : PILImageResampling = None , a : bool = None , a : Dict[str, int] = None , a : bool = None , a : float = None , a : bool = None , a : bool = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[float, List[float]]] = None , a : Optional[Union[str, TensorType]] = None , a : ChannelDimension = ChannelDimension.FIRST , **a : Tuple , ) -> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE : str = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE : Union[str, Any] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE : int = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE : str = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE : List[Any] = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE : Optional[Any] = offset if offset is not None else self.offset SCREAMING_SNAKE_CASE : str = do_normalize if do_normalize is not None else self.do_normalize SCREAMING_SNAKE_CASE : Optional[int] = image_mean if image_mean is not None else self.image_mean SCREAMING_SNAKE_CASE : Optional[Any] = image_std if image_std is not None else self.image_std SCREAMING_SNAKE_CASE : int = size if size is not None else self.size SCREAMING_SNAKE_CASE : List[Any] = get_size_dict(a , default_to_square=a ) SCREAMING_SNAKE_CASE : Tuple = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE : Union[str, Any] = get_size_dict(a , param_name="crop_size" ) 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." ) SCREAMING_SNAKE_CASE : Optional[int] = make_batched(a ) SCREAMING_SNAKE_CASE : List[Any] = [ [ self._preprocess_image( image=a , do_resize=a , size=a , resample=a , do_center_crop=a , crop_size=a , do_rescale=a , rescale_factor=a , offset=a , do_normalize=a , image_mean=a , image_std=a , data_format=a , ) for img in video ] for video in videos ] SCREAMING_SNAKE_CASE : Optional[int] = {"pixel_values": videos} return BatchFeature(data=a , tensor_type=a )
76
1
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =['vqvae'] def __init__( self : Dict , a : AutoencoderKL , a : UNetaDConditionModel , a : Mel , a : Union[DDIMScheduler, DDPMScheduler] , ) -> str: """simple docstring""" super().__init__() self.register_modules(unet=a , scheduler=a , mel=a , vqvae=a ) def __UpperCamelCase ( self : str ) -> int: """simple docstring""" return 50 if isinstance(self.scheduler , a ) else 1000 @torch.no_grad() def __call__( self : str , a : int = 1 , a : str = None , a : np.ndarray = None , a : int = 0 , a : int = 0 , a : int = None , a : torch.Generator = None , a : float = 0 , a : float = 0 , a : torch.Generator = None , a : float = 0 , a : torch.Tensor = None , a : torch.Tensor = None , a : Dict=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: """simple docstring""" SCREAMING_SNAKE_CASE : Optional[int] = steps or self.get_default_steps() self.scheduler.set_timesteps(a ) SCREAMING_SNAKE_CASE : str = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: SCREAMING_SNAKE_CASE : Union[str, Any] = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: SCREAMING_SNAKE_CASE : Dict = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=a , device=self.device , ) SCREAMING_SNAKE_CASE : List[Any] = noise SCREAMING_SNAKE_CASE : Optional[int] = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(a , a ) SCREAMING_SNAKE_CASE : Dict = self.mel.audio_slice_to_image(a ) SCREAMING_SNAKE_CASE : Optional[Any] = np.frombuffer(input_image.tobytes() , dtype="uint8" ).reshape( (input_image.height, input_image.width) ) SCREAMING_SNAKE_CASE : Union[str, Any] = (input_image / 255) * 2 - 1 SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: SCREAMING_SNAKE_CASE : Dict = self.vqvae.encode(torch.unsqueeze(a , 0 ) ).latent_dist.sample( generator=a )[0] SCREAMING_SNAKE_CASE : Tuple = self.vqvae.config.scaling_factor * input_images if start_step > 0: SCREAMING_SNAKE_CASE : Optional[int] = self.scheduler.add_noise(a , a , self.scheduler.timesteps[start_step - 1] ) SCREAMING_SNAKE_CASE : int = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) SCREAMING_SNAKE_CASE : int = int(mask_start_secs * pixels_per_second ) SCREAMING_SNAKE_CASE : int = int(mask_end_secs * pixels_per_second ) SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.add_noise(a , a , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , a ): SCREAMING_SNAKE_CASE : Union[str, Any] = self.unet(a , a , a )["sample"] else: SCREAMING_SNAKE_CASE : List[Any] = self.unet(a , a )["sample"] if isinstance(self.scheduler , a ): SCREAMING_SNAKE_CASE : Optional[Any] = self.scheduler.step( model_output=a , timestep=a , sample=a , eta=a , generator=a , )["prev_sample"] else: SCREAMING_SNAKE_CASE : Dict = self.scheduler.step( model_output=a , timestep=a , sample=a , generator=a , )["prev_sample"] if mask is not None: if mask_start > 0: SCREAMING_SNAKE_CASE : Optional[int] = mask[:, step, :, :mask_start] if mask_end > 0: SCREAMING_SNAKE_CASE : Union[str, Any] = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance SCREAMING_SNAKE_CASE : int = 1 / self.vqvae.config.scaling_factor * images SCREAMING_SNAKE_CASE : List[str] = self.vqvae.decode(a )["sample"] SCREAMING_SNAKE_CASE : Tuple = (images / 2 + 0.5).clamp(0 , 1 ) SCREAMING_SNAKE_CASE : Optional[Any] = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() SCREAMING_SNAKE_CASE : Optional[Any] = (images * 255).round().astype("uint8" ) SCREAMING_SNAKE_CASE : Union[str, Any] = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(a , mode="RGB" ).convert("L" ) for _ in images) ) SCREAMING_SNAKE_CASE : int = [self.mel.image_to_audio(a ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(a )[:, np.newaxis, :] ) , **ImagePipelineOutput(a ) ) @torch.no_grad() def __UpperCamelCase ( self : List[str] , a : List[Image.Image] , a : int = 50 ) -> np.ndarray: """simple docstring""" assert isinstance(self.scheduler , a ) self.scheduler.set_timesteps(a ) SCREAMING_SNAKE_CASE : str = np.array( [np.frombuffer(image.tobytes() , dtype="uint8" ).reshape((1, image.height, image.width) ) for image in images] ) SCREAMING_SNAKE_CASE : Optional[Any] = (sample / 255) * 2 - 1 SCREAMING_SNAKE_CASE : Dict = torch.Tensor(a ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): SCREAMING_SNAKE_CASE : Optional[Any] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps SCREAMING_SNAKE_CASE : int = self.scheduler.alphas_cumprod[t] SCREAMING_SNAKE_CASE : Any = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) SCREAMING_SNAKE_CASE : Optional[int] = 1 - alpha_prod_t SCREAMING_SNAKE_CASE : Dict = self.unet(a , a )["sample"] SCREAMING_SNAKE_CASE : Dict = (1 - alpha_prod_t_prev) ** 0.5 * model_output SCREAMING_SNAKE_CASE : List[str] = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) SCREAMING_SNAKE_CASE : Optional[int] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def __UpperCamelCase ( a : torch.Tensor , a : torch.Tensor , a : float ) -> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = acos(torch.dot(torch.flatten(a ) , torch.flatten(a ) ) / torch.norm(a ) / torch.norm(a ) ) return sin((1 - alpha) * theta ) * xa / sin(a ) + sin(alpha * theta ) * xa / sin(a )
76
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_convbert import ConvBertTokenizer a_ = logging.get_logger(__name__) a_ = {'vocab_file': 'vocab.txt'} a_ = { 'vocab_file': { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt', } } a_ = { 'YituTech/conv-bert-base': 512, 'YituTech/conv-bert-medium-small': 512, 'YituTech/conv-bert-small': 512, } a_ = { 'YituTech/conv-bert-base': {'do_lower_case': True}, 'YituTech/conv-bert-medium-small': {'do_lower_case': True}, 'YituTech/conv-bert-small': {'do_lower_case': True}, } class _UpperCamelCase ( __A ): '''simple docstring''' lowerCamelCase__ =VOCAB_FILES_NAMES lowerCamelCase__ =PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ =PRETRAINED_INIT_CONFIGURATION lowerCamelCase__ =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ =ConvBertTokenizer def __init__( self : List[str] , a : Union[str, Any]=None , a : Optional[int]=None , a : int=True , a : Tuple="[UNK]" , a : Dict="[SEP]" , a : Dict="[PAD]" , a : List[Any]="[CLS]" , a : Tuple="[MASK]" , a : Dict=True , a : Optional[Any]=None , **a : str , ) -> Dict: """simple docstring""" super().__init__( a , tokenizer_file=a , do_lower_case=a , unk_token=a , sep_token=a , pad_token=a , cls_token=a , mask_token=a , tokenize_chinese_chars=a , strip_accents=a , **a , ) SCREAMING_SNAKE_CASE : Optional[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , a ) != do_lower_case or normalizer_state.get("strip_accents" , a ) != strip_accents or normalizer_state.get("handle_chinese_chars" , a ) != tokenize_chinese_chars ): SCREAMING_SNAKE_CASE : List[str] = getattr(a , normalizer_state.pop("type" ) ) SCREAMING_SNAKE_CASE : Optional[Any] = do_lower_case SCREAMING_SNAKE_CASE : Any = strip_accents SCREAMING_SNAKE_CASE : Optional[int] = tokenize_chinese_chars SCREAMING_SNAKE_CASE : List[str] = normalizer_class(**a ) SCREAMING_SNAKE_CASE : str = do_lower_case def __UpperCamelCase ( self : Union[str, Any] , a : List[Any] , a : int=None ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def __UpperCamelCase ( self : Dict , a : List[int] , a : Optional[List[int]] = None ) -> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Union[str, Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __UpperCamelCase ( self : Tuple , a : str , a : Optional[str] = None ) -> Tuple[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self._tokenizer.model.save(a , name=a ) return tuple(a )
76
1
# Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) a_ = 'pytorch_model.bin' a_ = 'pytorch_model.bin.index.json' a_ = 'adapter_config.json' a_ = 'adapter_model.bin' a_ = 'adapter_model.safetensors' a_ = 'tf_model.h5' a_ = 'tf_model.h5.index.json' a_ = 'model.ckpt' a_ = 'flax_model.msgpack' a_ = 'flax_model.msgpack.index.json' a_ = 'model.safetensors' a_ = 'model.safetensors.index.json' a_ = 'config.json' a_ = 'preprocessor_config.json' a_ = FEATURE_EXTRACTOR_NAME a_ = 'generation_config.json' a_ = 'modelcard.json' a_ = '▁' a_ = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility a_ = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. a_ = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] a_ = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def lowerCamelCase__ ( _a): if version.parse(_a) < version.parse(_a): if "dev" in min_version: SCREAMING_SNAKE_CASE : Optional[Any] = ( "This example requires a source install from HuggingFace Transformers (see " "`https://huggingface.co/docs/transformers/installation#install-from-source`)," ) else: SCREAMING_SNAKE_CASE : List[Any] = f"This example requires a minimum version of {min_version}," error_message += f" but the version found is {__version__}.\n" raise ImportError( error_message + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other " "versions of HuggingFace Transformers.")
76
# tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. a_ = abspath(join(dirname(dirname(__file__)), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(_a) def lowerCamelCase__ ( _a): from diffusers.utils.testing_utils import pytest_terminal_summary_main SCREAMING_SNAKE_CASE : Union[str, Any] = terminalreporter.config.getoption("--make-reports") if make_reports: pytest_terminal_summary_main(_a , id=_a)
76
1
import unittest import torch from torch import nn from accelerate.test_utils import require_cuda from accelerate.utils.memory import find_executable_batch_size, release_memory def lowerCamelCase__ ( ): raise RuntimeError("CUDA out of memory.") class _UpperCamelCase ( nn.Module ): '''simple docstring''' def __init__( self : List[Any] ) -> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE : List[str] = nn.Linear(3 , 4 ) SCREAMING_SNAKE_CASE : List[Any] = nn.BatchNormad(4 ) SCREAMING_SNAKE_CASE : List[Any] = nn.Linear(4 , 5 ) def __UpperCamelCase ( self : Optional[int] , a : Optional[Any] ) -> Optional[int]: """simple docstring""" return self.lineara(self.batchnorm(self.lineara(a ) ) ) class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Any ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE : int = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(a : str ): nonlocal batch_sizes batch_sizes.append(a ) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() self.assertListEqual(a , [128, 64, 32, 16, 8] ) def __UpperCamelCase ( self : str ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = [] @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(a : List[Any] , a : Optional[int] ): nonlocal batch_sizes batch_sizes.append(a ) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arga SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Dict = mock_training_loop_function("hello" ) self.assertListEqual(a , [128, 64, 32, 16, 8] ) self.assertListEqual([bs, arga] , [8, "hello"] ) def __UpperCamelCase ( self : Optional[int] ) -> int: """simple docstring""" @find_executable_batch_size(starting_batch_size=0 ) def mock_training_loop_function(a : Any ): pass with self.assertRaises(a ) as cm: mock_training_loop_function() self.assertIn("No executable batch size found, reached zero." , cm.exception.args[0] ) def __UpperCamelCase ( self : List[str] ) -> Tuple: """simple docstring""" @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(a : Any ): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(a ) as cm: mock_training_loop_function() self.assertIn("No executable batch size found, reached zero." , cm.exception.args[0] ) def __UpperCamelCase ( self : List[Any] ) -> Tuple: """simple docstring""" @find_executable_batch_size(starting_batch_size=128 ) def mock_training_loop_function(a : List[str] , a : List[str] , a : Any ): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(a ) as cm: mock_training_loop_function(128 , "hello" , "world" ) self.assertIn("Batch size was passed into `f`" , cm.exception.args[0] ) self.assertIn("`f(arg1='hello', arg2='world')" , cm.exception.args[0] ) def __UpperCamelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" @find_executable_batch_size(starting_batch_size=16 ) def mock_training_loop_function(a : List[Any] ): raise ValueError("Oops, we had an error!" ) with self.assertRaises(a ) as cm: mock_training_loop_function() self.assertIn("Oops, we had an error!" , cm.exception.args[0] ) @require_cuda def __UpperCamelCase ( self : Any ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE : str = torch.cuda.memory_allocated() SCREAMING_SNAKE_CASE : Optional[Any] = ModelForTest() model.cuda() self.assertGreater(torch.cuda.memory_allocated() , a ) SCREAMING_SNAKE_CASE : List[Any] = release_memory(a ) self.assertEqual(torch.cuda.memory_allocated() , a )
76
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , a : int , a : Optional[int]=13 , a : Optional[int]=3 , a : int=224 , a : Optional[int]=30 , a : int=400 , a : Union[str, Any]=True , a : int=None , a : Tuple=True , a : Tuple=[0.5, 0.5, 0.5] , a : Optional[int]=[0.5, 0.5, 0.5] , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = size if size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : int = num_channels SCREAMING_SNAKE_CASE : Any = image_size SCREAMING_SNAKE_CASE : Tuple = min_resolution SCREAMING_SNAKE_CASE : str = max_resolution SCREAMING_SNAKE_CASE : int = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : int = do_normalize SCREAMING_SNAKE_CASE : Tuple = image_mean SCREAMING_SNAKE_CASE : Tuple = image_std def __UpperCamelCase ( self : Any ) -> Optional[int]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =ViTImageProcessor if is_vision_available() else None def __UpperCamelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = EfficientFormerImageProcessorTester(self ) @property def __UpperCamelCase ( self : Any ) -> List[str]: """simple docstring""" return self.image_proc_tester.prepare_image_processor_dict() def __UpperCamelCase ( self : List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , "image_mean" ) ) self.assertTrue(hasattr(a , "image_std" ) ) self.assertTrue(hasattr(a , "do_normalize" ) ) self.assertTrue(hasattr(a , "do_resize" ) ) self.assertTrue(hasattr(a , "size" ) ) def __UpperCamelCase ( self : int ) -> str: """simple docstring""" pass def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : List[str] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : str = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , numpify=a ) for image in image_inputs: self.assertIsInstance(a , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Any = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , torchify=a ) for image in image_inputs: self.assertIsInstance(a , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , )
76
1
# Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def lowerCamelCase__ ( _a , _a , _a , _a): SCREAMING_SNAKE_CASE : Any = { "en": "Machine learning is great, isn't it?", "ru": "Машинное обучение - это здорово, не так ли?", "de": "Maschinelles Lernen ist großartig, nicht wahr?", } # BLUE scores as follows: # "pair": [fairseq, transformers] SCREAMING_SNAKE_CASE : str = { "wmt16-en-de-dist-12-1": [28.3, 27.52], "wmt16-en-de-dist-6-1": [27.4, 27.11], "wmt16-en-de-12-1": [26.9, 25.75], } SCREAMING_SNAKE_CASE : Union[str, Any] = f"{src_lang}-{tgt_lang}" SCREAMING_SNAKE_CASE : Any = f"\n---\nlanguage:\n- {src_lang}\n- {tgt_lang}\nthumbnail:\ntags:\n- translation\n- wmt16\n- allenai\nlicense: apache-2.0\ndatasets:\n- wmt16\nmetrics:\n- bleu\n---\n\n# FSMT\n\n## Model description\n\nThis is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.\n\nFor more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).\n\nAll 3 models are available:\n\n* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)\n* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)\n* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)\n\n\n## Intended uses & limitations\n\n#### How to use\n\n```python\nfrom transformers import FSMTForConditionalGeneration, FSMTTokenizer\nmname = \"allenai/{model_name}\"\ntokenizer = FSMTTokenizer.from_pretrained(mname)\nmodel = FSMTForConditionalGeneration.from_pretrained(mname)\n\ninput = \"{texts[src_lang]}\"\ninput_ids = tokenizer.encode(input, return_tensors=\"pt\")\noutputs = model.generate(input_ids)\ndecoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\nprint(decoded) # {texts[tgt_lang]}\n\n```\n\n#### Limitations and bias\n\n\n## Training data\n\nPretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).\n\n## Eval results\n\nHere are the BLEU scores:\n\nmodel | fairseq | transformers\n-------|---------|----------\n{model_name} | {scores[model_name][0]} | {scores[model_name][1]}\n\nThe score is slightly below the score reported in the paper, as the researchers don't use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.\n\nThe score was calculated using this code:\n\n```bash\ngit clone https://github.com/huggingface/transformers\ncd transformers\nexport PAIR={pair}\nexport DATA_DIR=data/$PAIR\nexport SAVE_DIR=data/$PAIR\nexport BS=8\nexport NUM_BEAMS=5\nmkdir -p $DATA_DIR\nsacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source\nsacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target\necho $PAIR\nPYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS\n```\n\n## Data Sources\n\n- [training, etc.](http://www.statmt.org/wmt16/)\n- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)\n\n\n### BibTeX entry and citation info\n\n```\n@misc{{kasai2020deep,\n title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},\n author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},\n year={{2020}},\n eprint={{2006.10369}},\n archivePrefix={{arXiv}},\n primaryClass={{cs.CL}}\n}}\n```\n\n" model_card_dir.mkdir(parents=_a , exist_ok=_a) SCREAMING_SNAKE_CASE : Tuple = os.path.join(_a , "README.md") print(f"Generating {path}") with open(_a , "w" , encoding="utf-8") as f: f.write(_a) # make sure we are under the root of the project a_ = Path(__file__).resolve().parent.parent.parent a_ = repo_dir / 'model_cards' for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: a_ = model_cards_dir / 'allenai' / model_name write_model_card(model_card_dir, src_lang='en', tgt_lang='de', model_name=model_name)
76
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : int = {} SCREAMING_SNAKE_CASE : Any = tokenizer(example["content"] , truncation=_a)["input_ids"] SCREAMING_SNAKE_CASE : Dict = len(example["content"]) / len(output["input_ids"]) return output a_ = HfArgumentParser(PretokenizationArguments) a_ = parser.parse_args() if args.num_workers is None: a_ = multiprocessing.cpu_count() a_ = AutoTokenizer.from_pretrained(args.tokenizer_dir) a_ = time.time() a_ = load_dataset(args.dataset_name, split='train') print(F'''Dataset loaded in {time.time()-t_start:.2f}s''') a_ = time.time() a_ = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ 'repo_name', 'path', 'copies', 'size', 'content', 'license', 'hash', 'line_mean', 'line_max', 'alpha_frac', 'autogenerated', ], ) print(F'''Dataset tokenized in {time.time()-t_start:.2f}s''') a_ = time.time() ds.push_to_hub(args.tokenized_data_repo) print(F'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
76
1
import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all feature extractors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...feature_extraction_utils import FeatureExtractionMixin from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) a_ = logging.get_logger(__name__) a_ = OrderedDict( [ ('audio-spectrogram-transformer', 'ASTFeatureExtractor'), ('beit', 'BeitFeatureExtractor'), ('chinese_clip', 'ChineseCLIPFeatureExtractor'), ('clap', 'ClapFeatureExtractor'), ('clip', 'CLIPFeatureExtractor'), ('clipseg', 'ViTFeatureExtractor'), ('conditional_detr', 'ConditionalDetrFeatureExtractor'), ('convnext', 'ConvNextFeatureExtractor'), ('cvt', 'ConvNextFeatureExtractor'), ('data2vec-audio', 'Wav2Vec2FeatureExtractor'), ('data2vec-vision', 'BeitFeatureExtractor'), ('deformable_detr', 'DeformableDetrFeatureExtractor'), ('deit', 'DeiTFeatureExtractor'), ('detr', 'DetrFeatureExtractor'), ('dinat', 'ViTFeatureExtractor'), ('donut-swin', 'DonutFeatureExtractor'), ('dpt', 'DPTFeatureExtractor'), ('encodec', 'EncodecFeatureExtractor'), ('flava', 'FlavaFeatureExtractor'), ('glpn', 'GLPNFeatureExtractor'), ('groupvit', 'CLIPFeatureExtractor'), ('hubert', 'Wav2Vec2FeatureExtractor'), ('imagegpt', 'ImageGPTFeatureExtractor'), ('layoutlmv2', 'LayoutLMv2FeatureExtractor'), ('layoutlmv3', 'LayoutLMv3FeatureExtractor'), ('levit', 'LevitFeatureExtractor'), ('maskformer', 'MaskFormerFeatureExtractor'), ('mctct', 'MCTCTFeatureExtractor'), ('mobilenet_v1', 'MobileNetV1FeatureExtractor'), ('mobilenet_v2', 'MobileNetV2FeatureExtractor'), ('mobilevit', 'MobileViTFeatureExtractor'), ('nat', 'ViTFeatureExtractor'), ('owlvit', 'OwlViTFeatureExtractor'), ('perceiver', 'PerceiverFeatureExtractor'), ('poolformer', 'PoolFormerFeatureExtractor'), ('regnet', 'ConvNextFeatureExtractor'), ('resnet', 'ConvNextFeatureExtractor'), ('segformer', 'SegformerFeatureExtractor'), ('sew', 'Wav2Vec2FeatureExtractor'), ('sew-d', 'Wav2Vec2FeatureExtractor'), ('speech_to_text', 'Speech2TextFeatureExtractor'), ('speecht5', 'SpeechT5FeatureExtractor'), ('swiftformer', 'ViTFeatureExtractor'), ('swin', 'ViTFeatureExtractor'), ('swinv2', 'ViTFeatureExtractor'), ('table-transformer', 'DetrFeatureExtractor'), ('timesformer', 'VideoMAEFeatureExtractor'), ('tvlt', 'TvltFeatureExtractor'), ('unispeech', 'Wav2Vec2FeatureExtractor'), ('unispeech-sat', 'Wav2Vec2FeatureExtractor'), ('van', 'ConvNextFeatureExtractor'), ('videomae', 'VideoMAEFeatureExtractor'), ('vilt', 'ViltFeatureExtractor'), ('vit', 'ViTFeatureExtractor'), ('vit_mae', 'ViTFeatureExtractor'), ('vit_msn', 'ViTFeatureExtractor'), ('wav2vec2', 'Wav2Vec2FeatureExtractor'), ('wav2vec2-conformer', 'Wav2Vec2FeatureExtractor'), ('wavlm', 'Wav2Vec2FeatureExtractor'), ('whisper', 'WhisperFeatureExtractor'), ('xclip', 'CLIPFeatureExtractor'), ('yolos', 'YolosFeatureExtractor'), ] ) a_ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES) def lowerCamelCase__ ( _a): for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items(): if class_name in extractors: SCREAMING_SNAKE_CASE : Optional[int] = model_type_to_module_name(_a) SCREAMING_SNAKE_CASE : Optional[Any] = importlib.import_module(f".{module_name}" , "transformers.models") try: return getattr(_a , _a) except AttributeError: continue for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items(): if getattr(_a , "__name__" , _a) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. SCREAMING_SNAKE_CASE : List[Any] = importlib.import_module("transformers") if hasattr(_a , _a): return getattr(_a , _a) return None def lowerCamelCase__ ( _a , _a = None , _a = False , _a = False , _a = None , _a = None , _a = None , _a = False , **_a , ): SCREAMING_SNAKE_CASE : Union[str, Any] = get_file_from_repo( _a , _a , cache_dir=_a , force_download=_a , resume_download=_a , proxies=_a , use_auth_token=_a , revision=_a , local_files_only=_a , ) if resolved_config_file is None: logger.info( "Could not locate the feature extractor configuration file, will try to use the model config instead.") return {} with open(_a , encoding="utf-8") as reader: return json.load(_a) class _UpperCamelCase : '''simple docstring''' def __init__( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" raise EnvironmentError( "AutoFeatureExtractor is designed to be instantiated " "using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method." ) @classmethod @replace_list_option_in_docstrings(a ) def __UpperCamelCase ( cls : Union[str, Any] , a : List[Any] , **a : Dict ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = kwargs.pop("config" , a ) SCREAMING_SNAKE_CASE : Optional[int] = kwargs.pop("trust_remote_code" , a ) SCREAMING_SNAKE_CASE : List[Any] = True SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Any = FeatureExtractionMixin.get_feature_extractor_dict(a , **a ) SCREAMING_SNAKE_CASE : Optional[Any] = config_dict.get("feature_extractor_type" , a ) SCREAMING_SNAKE_CASE : Dict = None if "AutoFeatureExtractor" in config_dict.get("auto_map" , {} ): SCREAMING_SNAKE_CASE : str = config_dict["auto_map"]["AutoFeatureExtractor"] # If we don't find the feature extractor class in the feature extractor config, let's try the model config. if feature_extractor_class is None and feature_extractor_auto_map is None: if not isinstance(a , a ): SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(a , **a ) # It could be in `config.feature_extractor_type`` SCREAMING_SNAKE_CASE : Dict = getattr(a , "feature_extractor_type" , a ) if hasattr(a , "auto_map" ) and "AutoFeatureExtractor" in config.auto_map: SCREAMING_SNAKE_CASE : List[str] = config.auto_map["AutoFeatureExtractor"] if feature_extractor_class is not None: SCREAMING_SNAKE_CASE : Optional[Any] = feature_extractor_class_from_name(a ) SCREAMING_SNAKE_CASE : List[Any] = feature_extractor_auto_map is not None SCREAMING_SNAKE_CASE : Optional[Any] = feature_extractor_class is not None or type(a ) in FEATURE_EXTRACTOR_MAPPING SCREAMING_SNAKE_CASE : Any = resolve_trust_remote_code( a , a , a , a ) if has_remote_code and trust_remote_code: SCREAMING_SNAKE_CASE : Union[str, Any] = get_class_from_dynamic_module( a , a , **a ) SCREAMING_SNAKE_CASE : int = kwargs.pop("code_revision" , a ) if os.path.isdir(a ): feature_extractor_class.register_for_auto_class() return feature_extractor_class.from_dict(a , **a ) elif feature_extractor_class is not None: return feature_extractor_class.from_dict(a , **a ) # Last try: we use the FEATURE_EXTRACTOR_MAPPING. elif type(a ) in FEATURE_EXTRACTOR_MAPPING: SCREAMING_SNAKE_CASE : Tuple = FEATURE_EXTRACTOR_MAPPING[type(a )] return feature_extractor_class.from_dict(a , **a ) raise ValueError( F"Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a " F"`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following " F"`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys() )}" ) @staticmethod def __UpperCamelCase ( a : List[str] , a : Optional[int] ) -> Any: """simple docstring""" FEATURE_EXTRACTOR_MAPPING.register(a , a )
76
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) def lowerCamelCase__ ( _a): # initialize config if "resnet-50" in model_name: SCREAMING_SNAKE_CASE : int = ResNetConfig.from_pretrained("microsoft/resnet-50") elif "resnet-101" in model_name: SCREAMING_SNAKE_CASE : int = ResNetConfig.from_pretrained("microsoft/resnet-101") else: raise ValueError("Model name should include either resnet50 or resnet101") SCREAMING_SNAKE_CASE : str = DetrConfig(use_timm_backbone=_a , backbone_config=_a) # set label attributes SCREAMING_SNAKE_CASE : List[str] = "panoptic" in model_name if is_panoptic: SCREAMING_SNAKE_CASE : Union[str, Any] = 250 else: SCREAMING_SNAKE_CASE : Union[str, Any] = 91 SCREAMING_SNAKE_CASE : str = "huggingface/label-files" SCREAMING_SNAKE_CASE : Union[str, Any] = "coco-detection-id2label.json" SCREAMING_SNAKE_CASE : Optional[Any] = json.load(open(hf_hub_download(_a , _a , repo_type="dataset") , "r")) SCREAMING_SNAKE_CASE : int = {int(_a): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE : List[Any] = idalabel SCREAMING_SNAKE_CASE : List[Any] = {v: k for k, v in idalabel.items()} return config, is_panoptic def lowerCamelCase__ ( _a): # here we list all keys to be renamed (original name on the left, our name on the right) SCREAMING_SNAKE_CASE : Union[str, Any] = [] # stem # fmt: off rename_keys.append(("backbone.0.body.conv1.weight", "backbone.conv_encoder.model.embedder.embedder.convolution.weight")) rename_keys.append(("backbone.0.body.bn1.weight", "backbone.conv_encoder.model.embedder.embedder.normalization.weight")) rename_keys.append(("backbone.0.body.bn1.bias", "backbone.conv_encoder.model.embedder.embedder.normalization.bias")) rename_keys.append(("backbone.0.body.bn1.running_mean", "backbone.conv_encoder.model.embedder.embedder.normalization.running_mean")) rename_keys.append(("backbone.0.body.bn1.running_var", "backbone.conv_encoder.model.embedder.embedder.normalization.running_var")) # stages for stage_idx in range(len(config.backbone_config.depths)): for layer_idx in range(config.backbone_config.depths[stage_idx]): # shortcut if layer_idx == 0: rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var", )) # 3 convs for i in range(3): rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean", )) rename_keys.append( ( f"backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var", f"backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var", )) # fmt: on for i in range(config.encoder_layers): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( f"transformer.encoder.layers.{i}.self_attn.out_proj.weight", f"encoder.layers.{i}.self_attn.out_proj.weight", )) rename_keys.append( (f"transformer.encoder.layers.{i}.self_attn.out_proj.bias", f"encoder.layers.{i}.self_attn.out_proj.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.weight", f"encoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear1.bias", f"encoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.weight", f"encoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.linear2.bias", f"encoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm1.weight", f"encoder.layers.{i}.self_attn_layer_norm.weight")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm1.bias", f"encoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append( (f"transformer.encoder.layers.{i}.norm2.weight", f"encoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.encoder.layers.{i}.norm2.bias", f"encoder.layers.{i}.final_layer_norm.bias")) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( f"transformer.decoder.layers.{i}.self_attn.out_proj.weight", f"decoder.layers.{i}.self_attn.out_proj.weight", )) rename_keys.append( (f"transformer.decoder.layers.{i}.self_attn.out_proj.bias", f"decoder.layers.{i}.self_attn.out_proj.bias")) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.weight", f"decoder.layers.{i}.encoder_attn.out_proj.weight", )) rename_keys.append( ( f"transformer.decoder.layers.{i}.multihead_attn.out_proj.bias", f"decoder.layers.{i}.encoder_attn.out_proj.bias", )) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.weight", f"decoder.layers.{i}.fc1.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear1.bias", f"decoder.layers.{i}.fc1.bias")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.weight", f"decoder.layers.{i}.fc2.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.linear2.bias", f"decoder.layers.{i}.fc2.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm1.weight", f"decoder.layers.{i}.self_attn_layer_norm.weight")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm1.bias", f"decoder.layers.{i}.self_attn_layer_norm.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.weight", f"decoder.layers.{i}.encoder_attn_layer_norm.weight")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm2.bias", f"decoder.layers.{i}.encoder_attn_layer_norm.bias")) rename_keys.append( (f"transformer.decoder.layers.{i}.norm3.weight", f"decoder.layers.{i}.final_layer_norm.weight")) rename_keys.append((f"transformer.decoder.layers.{i}.norm3.bias", f"decoder.layers.{i}.final_layer_norm.bias")) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ]) return rename_keys def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : str = state_dict.pop(_a) SCREAMING_SNAKE_CASE : int = val def lowerCamelCase__ ( _a , _a=False): SCREAMING_SNAKE_CASE : Optional[Any] = "" if is_panoptic: SCREAMING_SNAKE_CASE : Optional[int] = "detr." # first: transformer encoder for i in range(6): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight") SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(f"{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias") # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : int = in_proj_bias[:256] SCREAMING_SNAKE_CASE : Tuple = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : List[Any] = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : str = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6): # read in weights + bias of input projection layer of self-attention SCREAMING_SNAKE_CASE : List[str] = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight") SCREAMING_SNAKE_CASE : str = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias") # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_weight[:256, :] SCREAMING_SNAKE_CASE : Dict = in_proj_bias[:256] SCREAMING_SNAKE_CASE : List[Any] = in_proj_weight[256:512, :] SCREAMING_SNAKE_CASE : Any = in_proj_bias[256:512] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight[-256:, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop( f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight") SCREAMING_SNAKE_CASE : int = state_dict.pop(f"{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias") # next, add query, keys and values (in that order) of cross-attention to the state dict SCREAMING_SNAKE_CASE : Tuple = in_proj_weight_cross_attn[:256, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias_cross_attn[:256] SCREAMING_SNAKE_CASE : Optional[Any] = in_proj_weight_cross_attn[256:512, :] SCREAMING_SNAKE_CASE : Dict = in_proj_bias_cross_attn[256:512] SCREAMING_SNAKE_CASE : Optional[int] = in_proj_weight_cross_attn[-256:, :] SCREAMING_SNAKE_CASE : Union[str, Any] = in_proj_bias_cross_attn[-256:] def lowerCamelCase__ ( ): SCREAMING_SNAKE_CASE : Tuple = "http://images.cocodataset.org/val2017/000000039769.jpg" SCREAMING_SNAKE_CASE : Union[str, Any] = Image.open(requests.get(_a , stream=_a).raw) return im @torch.no_grad() def lowerCamelCase__ ( _a , _a=None , _a=False): SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Optional[int] = get_detr_config(_a) # load original model from torch hub SCREAMING_SNAKE_CASE : Union[str, Any] = { "detr-resnet-50": "detr_resnet50", "detr-resnet-101": "detr_resnet101", } logger.info(f"Converting model {model_name}...") SCREAMING_SNAKE_CASE : Optional[int] = torch.hub.load("facebookresearch/detr" , model_name_to_original_name[model_name] , pretrained=_a).eval() SCREAMING_SNAKE_CASE : Tuple = detr.state_dict() # rename keys for src, dest in create_rename_keys(_a): if is_panoptic: SCREAMING_SNAKE_CASE : List[str] = "detr." + src rename_key(_a , _a , _a) # query, key and value matrices need special treatment read_in_q_k_v(_a , is_panoptic=_a) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them SCREAMING_SNAKE_CASE : List[Any] = "detr.model." if is_panoptic else "model." for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith("detr") and not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor") ): SCREAMING_SNAKE_CASE : Optional[int] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Union[str, Any] = val elif "class_labels_classifier" in key or "bbox_predictor" in key: SCREAMING_SNAKE_CASE : Union[str, Any] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Optional[int] = val elif key.startswith("bbox_attention") or key.startswith("mask_head"): continue else: SCREAMING_SNAKE_CASE : Optional[Any] = state_dict.pop(_a) SCREAMING_SNAKE_CASE : List[Any] = val else: if not key.startswith("class_labels_classifier") and not key.startswith("bbox_predictor"): SCREAMING_SNAKE_CASE : Any = state_dict.pop(_a) SCREAMING_SNAKE_CASE : Any = val # finally, create HuggingFace model and load state dict SCREAMING_SNAKE_CASE : int = DetrForSegmentation(_a) if is_panoptic else DetrForObjectDetection(_a) model.load_state_dict(_a) model.eval() # verify our conversion on an image SCREAMING_SNAKE_CASE : int = "coco_panoptic" if is_panoptic else "coco_detection" SCREAMING_SNAKE_CASE : Optional[int] = DetrImageProcessor(format=_a) SCREAMING_SNAKE_CASE : List[str] = processor(images=prepare_img() , return_tensors="pt") SCREAMING_SNAKE_CASE : Any = encoding["pixel_values"] SCREAMING_SNAKE_CASE : Optional[Any] = detr(_a) SCREAMING_SNAKE_CASE : Any = model(_a) assert torch.allclose(outputs.logits , original_outputs["pred_logits"] , atol=1E-3) assert torch.allclose(outputs.pred_boxes , original_outputs["pred_boxes"] , atol=1E-3) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs["pred_masks"] , atol=1E-4) print("Looks ok!") if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(f"Saving PyTorch model and image processor to {pytorch_dump_folder_path}...") Path(_a).mkdir(exist_ok=_a) model.save_pretrained(_a) processor.save_pretrained(_a) if push_to_hub: # Upload model and image processor to the hub logger.info("Uploading PyTorch model and image processor to the hub...") model.push_to_hub(f"nielsr/{model_name}") processor.push_to_hub(f"nielsr/{model_name}") if __name__ == "__main__": a_ = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') a_ = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
76
1
import os def lowerCamelCase__ ( _a = "input.txt"): with open(os.path.join(os.path.dirname(_a) , _a)) as input_file: SCREAMING_SNAKE_CASE : Dict = [ [int(_a) for element in line.split(",")] for line in input_file.readlines() ] SCREAMING_SNAKE_CASE : Tuple = len(_a) SCREAMING_SNAKE_CASE : Union[str, Any] = len(matrix[0]) SCREAMING_SNAKE_CASE : Optional[int] = [[-1 for _ in range(_a)] for _ in range(_a)] for i in range(_a): SCREAMING_SNAKE_CASE : Any = matrix[i][0] for j in range(1 , _a): for i in range(_a): SCREAMING_SNAKE_CASE : Optional[int] = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1 , _a): SCREAMING_SNAKE_CASE : Tuple = min( minimal_path_sums[i][j] , minimal_path_sums[i - 1][j] + matrix[i][j]) for i in range(rows - 2 , -1 , -1): SCREAMING_SNAKE_CASE : List[Any] = min( minimal_path_sums[i][j] , minimal_path_sums[i + 1][j] + matrix[i][j]) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums) if __name__ == "__main__": print(F'''{solution() = }''')
76
import os def lowerCamelCase__ ( ): with open(os.path.dirname(_a) + "/p022_names.txt") as file: SCREAMING_SNAKE_CASE : List[str] = str(file.readlines()[0]) SCREAMING_SNAKE_CASE : List[Any] = names.replace("\"" , "").split(",") names.sort() SCREAMING_SNAKE_CASE : Dict = 0 SCREAMING_SNAKE_CASE : Dict = 0 for i, name in enumerate(_a): for letter in name: name_score += ord(_a) - 64 total_score += (i + 1) * name_score SCREAMING_SNAKE_CASE : str = 0 return total_score if __name__ == "__main__": print(solution())
76
1
import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , a : int , a : Optional[int]=13 , a : Optional[int]=3 , a : int=224 , a : Optional[int]=30 , a : int=400 , a : Union[str, Any]=True , a : int=None , a : Tuple=True , a : Tuple=[0.5, 0.5, 0.5] , a : Optional[int]=[0.5, 0.5, 0.5] , ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : str = size if size is not None else {"height": 18, "width": 18} SCREAMING_SNAKE_CASE : Union[str, Any] = parent SCREAMING_SNAKE_CASE : int = batch_size SCREAMING_SNAKE_CASE : int = num_channels SCREAMING_SNAKE_CASE : Any = image_size SCREAMING_SNAKE_CASE : Tuple = min_resolution SCREAMING_SNAKE_CASE : str = max_resolution SCREAMING_SNAKE_CASE : int = do_resize SCREAMING_SNAKE_CASE : List[Any] = size SCREAMING_SNAKE_CASE : int = do_normalize SCREAMING_SNAKE_CASE : Tuple = image_mean SCREAMING_SNAKE_CASE : Tuple = image_std def __UpperCamelCase ( self : Any ) -> Optional[int]: """simple docstring""" return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, } @require_torch @require_vision class _UpperCamelCase ( __A , unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =ViTImageProcessor if is_vision_available() else None def __UpperCamelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = EfficientFormerImageProcessorTester(self ) @property def __UpperCamelCase ( self : Any ) -> List[str]: """simple docstring""" return self.image_proc_tester.prepare_image_processor_dict() def __UpperCamelCase ( self : List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a , "image_mean" ) ) self.assertTrue(hasattr(a , "image_std" ) ) self.assertTrue(hasattr(a , "do_normalize" ) ) self.assertTrue(hasattr(a , "do_resize" ) ) self.assertTrue(hasattr(a , "size" ) ) def __UpperCamelCase ( self : int ) -> str: """simple docstring""" pass def __UpperCamelCase ( self : Optional[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a ) for image in image_inputs: self.assertIsInstance(a , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE : List[str] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : str = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , numpify=a ) for image in image_inputs: self.assertIsInstance(a , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Any = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) def __UpperCamelCase ( self : List[str] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_proc_tester , equal_resolution=a , torchify=a ) for image in image_inputs: self.assertIsInstance(a , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , ) # Test batched SCREAMING_SNAKE_CASE : Optional[Any] = image_processor(a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_proc_tester.batch_size, self.image_proc_tester.num_channels, self.image_proc_tester.size["height"], self.image_proc_tester.size["width"], ) , )
76
from collections.abc import Callable import numpy as np def lowerCamelCase__ ( _a , _a , _a , _a , _a): SCREAMING_SNAKE_CASE : Dict = int(np.ceil((x_end - xa) / step_size)) SCREAMING_SNAKE_CASE : Tuple = np.zeros((n + 1,)) SCREAMING_SNAKE_CASE : int = ya SCREAMING_SNAKE_CASE : int = xa for k in range(_a): SCREAMING_SNAKE_CASE : Any = y[k] + step_size * ode_func(_a , y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
76
1
from collections.abc import Callable import numpy as np def lowerCamelCase__ ( _a , _a , _a , _a , _a): SCREAMING_SNAKE_CASE : Dict = int(np.ceil((x_end - xa) / step_size)) SCREAMING_SNAKE_CASE : Tuple = np.zeros((n + 1,)) SCREAMING_SNAKE_CASE : int = ya SCREAMING_SNAKE_CASE : int = xa for k in range(_a): SCREAMING_SNAKE_CASE : Any = y[k] + step_size * ode_func(_a , y[k]) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
76
def lowerCamelCase__ ( _a , _a): return int((input_a, input_a).count(1) != 0) def lowerCamelCase__ ( ): assert or_gate(0 , 0) == 0 assert or_gate(0 , 1) == 1 assert or_gate(1 , 0) == 1 assert or_gate(1 , 1) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
76
1
from __future__ import annotations from decimal import Decimal from numpy import array def lowerCamelCase__ ( _a): SCREAMING_SNAKE_CASE : Union[str, Any] = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(_a) == 2 and len(matrix[0]) == 2 and len(matrix[1]) == 2: # Calculate the determinant of the matrix SCREAMING_SNAKE_CASE : Tuple = float( d(matrix[0][0]) * d(matrix[1][1]) - d(matrix[1][0]) * d(matrix[0][1])) if determinant == 0: raise ValueError("This matrix has no inverse.") # Creates a copy of the matrix with swapped positions of the elements SCREAMING_SNAKE_CASE : int = [[0.0, 0.0], [0.0, 0.0]] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Tuple = matrix[1][1], matrix[0][0] SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : int = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(_a)) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(_a) == 3 and len(matrix[0]) == 3 and len(matrix[1]) == 3 and len(matrix[2]) == 3 ): # Calculate the determinant of the matrix using Sarrus rule SCREAMING_SNAKE_CASE : Optional[Any] = float( ( (d(matrix[0][0]) * d(matrix[1][1]) * d(matrix[2][2])) + (d(matrix[0][1]) * d(matrix[1][2]) * d(matrix[2][0])) + (d(matrix[0][2]) * d(matrix[1][0]) * d(matrix[2][1])) ) - ( (d(matrix[0][2]) * d(matrix[1][1]) * d(matrix[2][0])) + (d(matrix[0][1]) * d(matrix[1][0]) * d(matrix[2][2])) + (d(matrix[0][0]) * d(matrix[1][2]) * d(matrix[2][1])) )) if determinant == 0: raise ValueError("This matrix has no inverse.") # Creating cofactor matrix SCREAMING_SNAKE_CASE : List[str] = [ [d(0.0), d(0.0), d(0.0)], [d(0.0), d(0.0), d(0.0)], [d(0.0), d(0.0), d(0.0)], ] SCREAMING_SNAKE_CASE : Any = (d(matrix[1][1]) * d(matrix[2][2])) - ( d(matrix[1][2]) * d(matrix[2][1]) ) SCREAMING_SNAKE_CASE : Tuple = -( (d(matrix[1][0]) * d(matrix[2][2])) - (d(matrix[1][2]) * d(matrix[2][0])) ) SCREAMING_SNAKE_CASE : List[str] = (d(matrix[1][0]) * d(matrix[2][1])) - ( d(matrix[1][1]) * d(matrix[2][0]) ) SCREAMING_SNAKE_CASE : List[Any] = -( (d(matrix[0][1]) * d(matrix[2][2])) - (d(matrix[0][2]) * d(matrix[2][1])) ) SCREAMING_SNAKE_CASE : Optional[int] = (d(matrix[0][0]) * d(matrix[2][2])) - ( d(matrix[0][2]) * d(matrix[2][0]) ) SCREAMING_SNAKE_CASE : Union[str, Any] = -( (d(matrix[0][0]) * d(matrix[2][1])) - (d(matrix[0][1]) * d(matrix[2][0])) ) SCREAMING_SNAKE_CASE : Dict = (d(matrix[0][1]) * d(matrix[1][2])) - ( d(matrix[0][2]) * d(matrix[1][1]) ) SCREAMING_SNAKE_CASE : str = -( (d(matrix[0][0]) * d(matrix[1][2])) - (d(matrix[0][2]) * d(matrix[1][0])) ) SCREAMING_SNAKE_CASE : List[Any] = (d(matrix[0][0]) * d(matrix[1][1])) - ( d(matrix[0][1]) * d(matrix[1][0]) ) # Transpose the cofactor matrix (Adjoint matrix) SCREAMING_SNAKE_CASE : Tuple = array(_a) for i in range(3): for j in range(3): SCREAMING_SNAKE_CASE : Union[str, Any] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix SCREAMING_SNAKE_CASE : List[str] = array(_a) for i in range(3): for j in range(3): inverse_matrix[i][j] /= d(_a) # Calculate the inverse of the matrix return [[float(d(_a)) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("Please provide a matrix of size 2x2 or 3x3.")
76
a_ = 8.314_4598 def lowerCamelCase__ ( _a , _a): if temperature < 0: raise Exception("Temperature cannot be less than 0 K") if molar_mass <= 0: raise Exception("Molar mass cannot be less than or equal to 0 kg/mol") else: return (3 * UNIVERSAL_GAS_CONSTANT * temperature / molar_mass) ** 0.5 if __name__ == "__main__": import doctest # run doctest doctest.testmod() # example a_ = 300 a_ = 28 a_ = rms_speed_of_molecule(temperature, molar_mass) print(F'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
76
1
import gc import unittest from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline from diffusers.utils import is_flax_available, 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 _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCamelCase ( self : Tuple ) -> int: """simple docstring""" super().tearDown() gc.collect() def __UpperCamelCase ( self : str ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = FlaxStableDiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-2" , revision="bf16" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE : int = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE : Union[str, Any] = jax.device_count() SCREAMING_SNAKE_CASE : Optional[int] = num_samples * [prompt] SCREAMING_SNAKE_CASE : Any = sd_pipe.prepare_inputs(a ) SCREAMING_SNAKE_CASE : Tuple = replicate(a ) SCREAMING_SNAKE_CASE : Dict = shard(a ) SCREAMING_SNAKE_CASE : Union[str, Any] = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE : Dict = jax.random.split(a , jax.device_count() ) SCREAMING_SNAKE_CASE : str = sd_pipe(a , a , a , num_inference_steps=25 , jit=a )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE : Tuple = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE : List[str] = images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE : Optional[int] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE : Any = jnp.array([0.4238, 0.4414, 0.4395, 0.4453, 0.4629, 0.4590, 0.4531, 0.4_5508, 0.4512] ) print(F"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def __UpperCamelCase ( self : List[str] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE : int = "stabilityai/stable-diffusion-2" SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Tuple = FlaxDPMSolverMultistepScheduler.from_pretrained(a , subfolder="scheduler" ) SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : str = FlaxStableDiffusionPipeline.from_pretrained( a , scheduler=a , revision="bf16" , dtype=jnp.bfloataa , ) SCREAMING_SNAKE_CASE : Tuple = scheduler_params SCREAMING_SNAKE_CASE : List[str] = "A painting of a squirrel eating a burger" SCREAMING_SNAKE_CASE : Optional[Any] = jax.device_count() SCREAMING_SNAKE_CASE : int = num_samples * [prompt] SCREAMING_SNAKE_CASE : Union[str, Any] = sd_pipe.prepare_inputs(a ) SCREAMING_SNAKE_CASE : Tuple = replicate(a ) SCREAMING_SNAKE_CASE : Optional[int] = shard(a ) SCREAMING_SNAKE_CASE : Dict = jax.random.PRNGKey(0 ) SCREAMING_SNAKE_CASE : str = jax.random.split(a , jax.device_count() ) SCREAMING_SNAKE_CASE : str = sd_pipe(a , a , a , num_inference_steps=25 , jit=a )[0] assert images.shape == (jax.device_count(), 1, 768, 768, 3) SCREAMING_SNAKE_CASE : Any = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) SCREAMING_SNAKE_CASE : Union[str, Any] = images[0, 253:256, 253:256, -1] SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) SCREAMING_SNAKE_CASE : Union[str, Any] = jnp.array([0.4336, 0.4_2969, 0.4453, 0.4199, 0.4297, 0.4531, 0.4434, 0.4434, 0.4297] ) print(F"output_slice: {output_slice}" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
76
a_ = { 'A': ['B', 'C', 'E'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F', 'G'], 'D': ['B'], 'E': ['A', 'B', 'D'], 'F': ['C'], 'G': ['C'], } def lowerCamelCase__ ( _a , _a , _a): SCREAMING_SNAKE_CASE : int = set() # keep track of all the paths to be checked SCREAMING_SNAKE_CASE : int = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue SCREAMING_SNAKE_CASE : Optional[int] = queue.pop(0) # get the last node from the path SCREAMING_SNAKE_CASE : Union[str, Any] = path[-1] if node not in explored: SCREAMING_SNAKE_CASE : List[str] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: SCREAMING_SNAKE_CASE : List[Any] = list(_a) new_path.append(_a) queue.append(_a) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(_a) # in case there's no path between the 2 nodes return [] def lowerCamelCase__ ( _a , _a , _a): if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 SCREAMING_SNAKE_CASE : str = [start] SCREAMING_SNAKE_CASE : Optional[Any] = set(_a) # Keep tab on distances from `start` node. SCREAMING_SNAKE_CASE : Union[str, Any] = {start: 0, target: -1} while queue: SCREAMING_SNAKE_CASE : Optional[int] = queue.pop(0) if node == target: SCREAMING_SNAKE_CASE : Union[str, Any] = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node]) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(_a) queue.append(_a) SCREAMING_SNAKE_CASE : Optional[Any] = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, 'G', 'D')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, 'G', 'D')) # returns 4
76
1