code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder snake_case_ : str = "__DUMMY_TRANSFORMERS_USER__" snake_case_ : Optional[Any] = "Dummy User" snake_case_ : Optional[int] = "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" snake_case_ : Any = "https://hub-ci.huggingface.co" snake_case_ : List[str] = CI_HUB_ENDPOINT + "/datasets/{repo_id}/resolve/{revision}/{path}" snake_case_ : Tuple = CI_HUB_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}" snake_case_ : List[str] = Path("~/.huggingface/hub_ci_token").expanduser() @pytest.fixture def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[str]: monkeypatch.setattr( '''huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE''', SCREAMING_SNAKE_CASE__ ) @pytest.fixture def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Dict: monkeypatch.setattr('''datasets.config.HF_ENDPOINT''', SCREAMING_SNAKE_CASE__ ) monkeypatch.setattr('''datasets.config.HUB_DATASETS_URL''', SCREAMING_SNAKE_CASE__ ) @pytest.fixture def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[Any]: monkeypatch.setattr('''huggingface_hub.hf_api.HfFolder.path_token''', SCREAMING_SNAKE_CASE__ ) @pytest.fixture def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) yield HfFolder.delete_token() @pytest.fixture(scope='''session''' ) def lowerCamelCase_ ( ) -> Dict: return HfApi(endpoint=SCREAMING_SNAKE_CASE__ ) @pytest.fixture(scope='''session''' ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : HfApi ) -> List[str]: UpperCAmelCase_ : Dict = HfFolder.get_token() HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(SCREAMING_SNAKE_CASE__ ) @pytest.fixture def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str] ) -> Dict: def _cleanup_repo(SCREAMING_SNAKE_CASE__ : Optional[Any] ): hf_api.delete_repo(SCREAMING_SNAKE_CASE__, token=SCREAMING_SNAKE_CASE__, repo_type='''dataset''' ) return _cleanup_repo @pytest.fixture def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: @contextmanager def _temporary_repo(SCREAMING_SNAKE_CASE__ : List[str] ): try: yield repo_id finally: cleanup_repo(SCREAMING_SNAKE_CASE__ ) return _temporary_repo @pytest.fixture(scope='''session''' ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : HfApi, SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: UpperCAmelCase_ : Optional[Any] = F"""repo_txt_data-{int(time.time() * 10E3 )}""" UpperCAmelCase_ : Tuple = F"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(SCREAMING_SNAKE_CASE__, token=SCREAMING_SNAKE_CASE__, repo_type='''dataset''', private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__, path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ), path_in_repo='''data/text_data.txt''', repo_id=SCREAMING_SNAKE_CASE__, repo_type='''dataset''', ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__, token=SCREAMING_SNAKE_CASE__, repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str], SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : str ) -> Dict: return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope='''session''' ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : HfApi, SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : List[str] ) -> Union[str, Any]: UpperCAmelCase_ : Dict = F"""repo_zipped_txt_data-{int(time.time() * 10E3 )}""" UpperCAmelCase_ : str = F"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(SCREAMING_SNAKE_CASE__, token=SCREAMING_SNAKE_CASE__, repo_type='''dataset''', private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__, path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ), path_in_repo='''data.zip''', repo_id=SCREAMING_SNAKE_CASE__, repo_type='''dataset''', ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__, token=SCREAMING_SNAKE_CASE__, repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : str ) -> Optional[Any]: return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope='''session''' ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : HfApi, SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Any ) -> Tuple: UpperCAmelCase_ : str = F"""repo_zipped_img_data-{int(time.time() * 10E3 )}""" UpperCAmelCase_ : Dict = F"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(SCREAMING_SNAKE_CASE__, token=SCREAMING_SNAKE_CASE__, repo_type='''dataset''', private=SCREAMING_SNAKE_CASE__ ) hf_api.upload_file( token=SCREAMING_SNAKE_CASE__, path_or_fileobj=str(SCREAMING_SNAKE_CASE__ ), path_in_repo='''data.zip''', repo_id=SCREAMING_SNAKE_CASE__, repo_type='''dataset''', ) yield repo_id try: hf_api.delete_repo(SCREAMING_SNAKE_CASE__, token=SCREAMING_SNAKE_CASE__, repo_type='''dataset''' ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: return hf_private_dataset_repo_zipped_img_data_
700
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. UpperCAmelCase_ : List[str] = [[1, 2, 4], [1, 2, 3, 4]] UpperCAmelCase_ : List[str] = DisjunctiveConstraint(__magic_name__ ) self.assertTrue(isinstance(dc.token_ids , __magic_name__ ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). UpperCAmelCase_ : Tuple = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(__magic_name__ ) # fails here def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] UpperCAmelCase_ : List[str] = DisjunctiveConstraint(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) UpperCAmelCase_ : Dict = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : str = dc.update(2 ) UpperCAmelCase_ : Optional[Any] = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(3 ) UpperCAmelCase_ : Dict = stepped is True and completed is True and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase__ ( self : int ) -> Dict: """simple docstring""" UpperCAmelCase_ : Any = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] UpperCAmelCase_ : Tuple = DisjunctiveConstraint(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
644
0
'''simple docstring''' import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : str , __magic_name__ : str ) -> Any: """simple docstring""" for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): UpperCAmelCase_ : Optional[Any] = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(__magic_name__ ) def UpperCAmelCase__ ( self : Optional[int] ) -> int: """simple docstring""" UpperCAmelCase_ : Tuple = '''sshleifer/tiny-gpt2''' UpperCAmelCase_ : str = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=__magic_name__ , multi_process=__magic_name__ , ) UpperCAmelCase_ : Dict = TensorFlowBenchmark(__magic_name__ ) UpperCAmelCase_ : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Optional[int] = '''sgugger/tiny-distilbert-classification''' UpperCAmelCase_ : int = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , only_pretrain_model=__magic_name__ , ) UpperCAmelCase_ : Any = TensorFlowBenchmark(__magic_name__ ) UpperCAmelCase_ : int = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : List[str] = '''sshleifer/tiny-gpt2''' UpperCAmelCase_ : Any = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) UpperCAmelCase_ : Optional[Any] = TensorFlowBenchmark(__magic_name__ ) UpperCAmelCase_ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Tuple: """simple docstring""" UpperCAmelCase_ : int = '''sshleifer/tiny-gpt2''' UpperCAmelCase_ : List[str] = AutoConfig.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=__magic_name__ , multi_process=__magic_name__ , ) UpperCAmelCase_ : str = TensorFlowBenchmark(__magic_name__ , [config] ) UpperCAmelCase_ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" UpperCAmelCase_ : Dict = '''sshleifer/tiny-gpt2''' UpperCAmelCase_ : List[Any] = AutoConfig.from_pretrained(__magic_name__ ) UpperCAmelCase_ : str = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) UpperCAmelCase_ : Optional[Any] = TensorFlowBenchmark(__magic_name__ , [config] ) UpperCAmelCase_ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self : Any ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Tuple = '''sshleifer/tiny-gpt2''' UpperCAmelCase_ : Dict = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) UpperCAmelCase_ : Any = TensorFlowBenchmark(__magic_name__ ) UpperCAmelCase_ : str = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCAmelCase__ ( self : List[str] ) -> Tuple: """simple docstring""" UpperCAmelCase_ : str = '''sshleifer/tiny-gpt2''' UpperCAmelCase_ : Dict = AutoConfig.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) UpperCAmelCase_ : List[str] = TensorFlowBenchmark(__magic_name__ , [config] ) UpperCAmelCase_ : str = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def UpperCAmelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = '''patrickvonplaten/t5-tiny-random''' UpperCAmelCase_ : Union[str, Any] = AutoConfig.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=__magic_name__ , ) UpperCAmelCase_ : List[Any] = TensorFlowBenchmark(__magic_name__ , configs=[config] ) UpperCAmelCase_ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , '''Cannot do xla on CPU.''' ) def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = '''sshleifer/tiny-gpt2''' UpperCAmelCase_ : Tuple = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=__magic_name__ , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , use_xla=__magic_name__ , multi_process=__magic_name__ , ) UpperCAmelCase_ : Dict = TensorFlowBenchmark(__magic_name__ ) UpperCAmelCase_ : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" UpperCAmelCase_ : int = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase_ : Union[str, Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=__magic_name__ , save_to_csv=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(__magic_name__ , '''inf_time.csv''' ) , inference_memory_csv_file=os.path.join(__magic_name__ , '''inf_mem.csv''' ) , env_info_csv_file=os.path.join(__magic_name__ , '''env.csv''' ) , multi_process=__magic_name__ , ) UpperCAmelCase_ : Optional[int] = TensorFlowBenchmark(__magic_name__ ) benchmark.run() self.assertTrue(Path(os.path.join(__magic_name__ , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(__magic_name__ , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(__magic_name__ , '''env.csv''' ) ).exists() ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" UpperCAmelCase_ : str = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(__magic_name__ : str ): self.assertTrue(hasattr(__magic_name__ , '''sequential''' ) ) self.assertTrue(hasattr(__magic_name__ , '''cumulative''' ) ) self.assertTrue(hasattr(__magic_name__ , '''current''' ) ) self.assertTrue(hasattr(__magic_name__ , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: UpperCAmelCase_ : str = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=__magic_name__ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(__magic_name__ , '''log.txt''' ) , log_print=__magic_name__ , trace_memory_line_by_line=__magic_name__ , eager_mode=__magic_name__ , multi_process=__magic_name__ , ) UpperCAmelCase_ : Dict = TensorFlowBenchmark(__magic_name__ ) UpperCAmelCase_ : Dict = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(__magic_name__ , '''log.txt''' ) ).exists() )
701
'''simple docstring''' import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": snake_case_ : List[Any] = pd.read_csv("sample_data.csv", header=None) snake_case_ : Optional[Any] = df.shape[:1][0] # If you're using some other dataset input the target column snake_case_ : Any = df.iloc[:, 1:2] snake_case_ : str = actual_data.values.reshape(len_data, 1) snake_case_ : Optional[Any] = MinMaxScaler().fit_transform(actual_data) snake_case_ : List[str] = 10 snake_case_ : Any = 5 snake_case_ : Any = 20 snake_case_ : Tuple = len_data - periods * look_back snake_case_ : str = actual_data[:division] snake_case_ : Optional[int] = actual_data[division - look_back :] snake_case_ ,snake_case_ : Any = [], [] snake_case_ ,snake_case_ : Union[str, Any] = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) snake_case_ : Any = np.array(train_x) snake_case_ : Optional[Any] = np.array(test_x) snake_case_ : Optional[Any] = np.array([list(i.ravel()) for i in train_y]) snake_case_ : List[str] = np.array([list(i.ravel()) for i in test_y]) snake_case_ : List[Any] = Sequential() model.add(LSTM(1_28, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(1_28, 1))) model.add(Dense(forward_days)) model.compile(loss="mean_squared_error", optimizer="adam") snake_case_ : Dict = model.fit( x_train, y_train, epochs=1_50, verbose=1, shuffle=True, batch_size=4 ) snake_case_ : Optional[Any] = model.predict(x_test)
644
0
'''simple docstring''' from __future__ import annotations from statistics import mean def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : list[int], SCREAMING_SNAKE_CASE__ : list[int], SCREAMING_SNAKE_CASE__ : int ) -> list[int]: UpperCAmelCase_ : List[str] = [0] * no_of_processes UpperCAmelCase_ : Optional[int] = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : int = burst_time[i] UpperCAmelCase_ : list[int] = [] UpperCAmelCase_ : Dict = 0 UpperCAmelCase_ : Any = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: UpperCAmelCase_ : Any = [] UpperCAmelCase_ : Any = -1 for i in range(SCREAMING_SNAKE_CASE__ ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: UpperCAmelCase_ : int = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: UpperCAmelCase_ : str = i total_time += burst_time[target_process] completed += 1 UpperCAmelCase_ : Union[str, Any] = 0 UpperCAmelCase_ : Optional[int] = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : list[int], SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : list[int] ) -> list[int]: UpperCAmelCase_ : Union[str, Any] = [0] * no_of_processes for i in range(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Dict = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") snake_case_ : Tuple = 4 snake_case_ : int = [2, 5, 3, 7] snake_case_ : Union[str, Any] = [0, 0, 0, 0] snake_case_ : int = calculate_waitingtime(arrival_time, burst_time, no_of_processes) snake_case_ : Tuple = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( f'''{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t''' f'''{waiting_time[i]}\t\t\t\t{turn_around_time[i]}''' ) print(f'''\nAverage waiting time = {mean(waiting_time):.5f}''') print(f'''Average turnaround time = {mean(turn_around_time):.5f}''')
702
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker snake_case_ : Union[str, Any] = "CompVis/stable-diffusion-v1-1" snake_case_ : Dict = "CompVis/stable-diffusion-v1-2" snake_case_ : Any = "CompVis/stable-diffusion-v1-3" snake_case_ : str = "CompVis/stable-diffusion-v1-4" class __a (lowerCamelCase ): def __init__( self : Any , __magic_name__ : AutoencoderKL , __magic_name__ : CLIPTextModel , __magic_name__ : CLIPTokenizer , __magic_name__ : UNetaDConditionModel , __magic_name__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __magic_name__ : StableDiffusionSafetyChecker , __magic_name__ : CLIPImageProcessor , __magic_name__ : bool = True , ) -> str: """simple docstring""" super()._init_() UpperCAmelCase_ : Any = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Dict = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : List[Any] = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Tuple = StableDiffusionPipeline( vae=__magic_name__ , text_encoder=__magic_name__ , tokenizer=__magic_name__ , unet=__magic_name__ , scheduler=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , requires_safety_checker=__magic_name__ , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def UpperCAmelCase__ ( self : Tuple ) -> Dict[str, Any]: """simple docstring""" return {k: getattr(self , __magic_name__ ) for k in self.config.keys() if not k.startswith('''_''' )} def UpperCAmelCase__ ( self : Dict , __magic_name__ : Optional[Union[str, int]] = "auto" ) -> int: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ : List[str] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" self.enable_attention_slicing(__magic_name__ ) @torch.no_grad() def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Tuple , ) -> Optional[int]: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Any , ) -> Any: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Dict , ) -> List[str]: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : int , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Optional[int] , ) -> str: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Optional[int] , ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : int = '''cuda''' if torch.cuda.is_available() else '''cpu''' self.to(__magic_name__ ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` must be divisible by 8 but are {height} and {width}.""" ) # Get first result from Stable Diffusion Checkpoint v1.1 UpperCAmelCase_ : Optional[int] = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCAmelCase_ : int = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCAmelCase_ : str = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCAmelCase_ : str = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
644
0
'''simple docstring''' from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __a (lowerCamelCase ): __a : Optional[int] = ["image_processor", "tokenizer"] __a : Optional[Any] = "BlipImageProcessor" __a : List[str] = ("BertTokenizer", "BertTokenizerFast") def __init__( self : List[str] , __magic_name__ : Tuple , __magic_name__ : Dict ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = False super().__init__(__magic_name__ , __magic_name__ ) UpperCAmelCase_ : Union[str, Any] = self.image_processor def __call__( self : Optional[int] , __magic_name__ : ImageInput = None , __magic_name__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __magic_name__ : bool = True , __magic_name__ : Union[bool, str, PaddingStrategy] = False , __magic_name__ : Union[bool, str, TruncationStrategy] = None , __magic_name__ : Optional[int] = None , __magic_name__ : int = 0 , __magic_name__ : Optional[int] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : bool = False , __magic_name__ : bool = False , __magic_name__ : bool = False , __magic_name__ : bool = False , __magic_name__ : bool = False , __magic_name__ : bool = True , __magic_name__ : Optional[Union[str, TensorType]] = None , **__magic_name__ : Optional[int] , ) -> BatchEncoding: """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: UpperCAmelCase_ : Any = self.tokenizer UpperCAmelCase_ : Any = self.tokenizer( text=__magic_name__ , add_special_tokens=__magic_name__ , padding=__magic_name__ , truncation=__magic_name__ , max_length=__magic_name__ , stride=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_attention_mask=__magic_name__ , return_overflowing_tokens=__magic_name__ , return_special_tokens_mask=__magic_name__ , return_offsets_mapping=__magic_name__ , return_token_type_ids=__magic_name__ , return_length=__magic_name__ , verbose=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ , ) return text_encoding # add pixel_values UpperCAmelCase_ : Union[str, Any] = self.image_processor(__magic_name__ , return_tensors=__magic_name__ ) if text is not None: UpperCAmelCase_ : int = self.tokenizer( text=__magic_name__ , add_special_tokens=__magic_name__ , padding=__magic_name__ , truncation=__magic_name__ , max_length=__magic_name__ , stride=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_attention_mask=__magic_name__ , return_overflowing_tokens=__magic_name__ , return_special_tokens_mask=__magic_name__ , return_offsets_mapping=__magic_name__ , return_token_type_ids=__magic_name__ , return_length=__magic_name__ , verbose=__magic_name__ , return_tensors=__magic_name__ , **__magic_name__ , ) else: UpperCAmelCase_ : Optional[Any] = None if text_encoding is not None: encoding_image_processor.update(__magic_name__ ) return encoding_image_processor def UpperCAmelCase__ ( self : int , *__magic_name__ : Any , **__magic_name__ : Any ) -> Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : str , *__magic_name__ : Optional[Any] , **__magic_name__ : List[str] ) -> Dict: """simple docstring""" return self.tokenizer.decode(*__magic_name__ , **__magic_name__ ) @property def UpperCAmelCase__ ( self : str ) -> Dict: """simple docstring""" UpperCAmelCase_ : Tuple = self.tokenizer.model_input_names UpperCAmelCase_ : Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
703
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler snake_case_ : Optional[int] = 16 snake_case_ : Tuple = 32 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Accelerator, SCREAMING_SNAKE_CASE__ : int = 16, SCREAMING_SNAKE_CASE__ : str = "bert-base-cased" ) -> Dict: UpperCAmelCase_ : Dict = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = load_dataset('''glue''', '''mrpc''' ) def tokenize_function(SCREAMING_SNAKE_CASE__ : Optional[int] ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase_ : Union[str, Any] = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=SCREAMING_SNAKE_CASE__, max_length=SCREAMING_SNAKE_CASE__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase_ : Tuple = datasets.map( SCREAMING_SNAKE_CASE__, batched=SCREAMING_SNAKE_CASE__, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], load_from_cache_file=SCREAMING_SNAKE_CASE__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase_ : Optional[Any] = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(SCREAMING_SNAKE_CASE__ : str ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(SCREAMING_SNAKE_CASE__, padding='''max_length''', max_length=128, return_tensors='''pt''' ) return tokenizer.pad(SCREAMING_SNAKE_CASE__, padding='''longest''', return_tensors='''pt''' ) # Instantiate dataloaders. UpperCAmelCase_ : str = DataLoader( tokenized_datasets['''train'''], shuffle=SCREAMING_SNAKE_CASE__, collate_fn=SCREAMING_SNAKE_CASE__, batch_size=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = DataLoader( tokenized_datasets['''validation'''], shuffle=SCREAMING_SNAKE_CASE__, collate_fn=SCREAMING_SNAKE_CASE__, batch_size=SCREAMING_SNAKE_CASE__ ) return train_dataloader, eval_dataloader def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Optional[int], SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Any ) -> Any: model.eval() UpperCAmelCase_ : List[str] = 0 for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase_ : Dict = model(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : str = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCAmelCase_ , UpperCAmelCase_ : List[str] = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(SCREAMING_SNAKE_CASE__ ) - 1: UpperCAmelCase_ : Tuple = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCAmelCase_ : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=SCREAMING_SNAKE_CASE__, references=SCREAMING_SNAKE_CASE__, ) UpperCAmelCase_ : List[str] = metric.compute() return eval_metric["accuracy"] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : int ) -> Tuple: # Initialize accelerator UpperCAmelCase_ : Union[str, Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase_ : int = config['''lr'''] UpperCAmelCase_ : Optional[int] = int(config['''num_epochs'''] ) UpperCAmelCase_ : Optional[int] = int(config['''seed'''] ) UpperCAmelCase_ : List[str] = int(config['''batch_size'''] ) UpperCAmelCase_ : Optional[int] = args.model_name_or_path set_seed(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = get_dataloaders(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase_ : List[Any] = AutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__, return_dict=SCREAMING_SNAKE_CASE__ ) # Instantiate optimizer UpperCAmelCase_ : str = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCAmelCase_ : List[str] = optimizer_cls(params=model.parameters(), lr=SCREAMING_SNAKE_CASE__ ) if accelerator.state.deepspeed_plugin is not None: UpperCAmelCase_ : List[Any] = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: UpperCAmelCase_ : Tuple = 1 UpperCAmelCase_ : int = (len(SCREAMING_SNAKE_CASE__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCAmelCase_ : Tuple = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE__, num_warmup_steps=0, num_training_steps=SCREAMING_SNAKE_CASE__, ) else: UpperCAmelCase_ : Any = DummyScheduler(SCREAMING_SNAKE_CASE__, total_num_steps=SCREAMING_SNAKE_CASE__, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = accelerator.prepare( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase_ : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly UpperCAmelCase_ : Dict = 0 UpperCAmelCase_ : int = evaluate.load('''glue''', '''mrpc''' ) UpperCAmelCase_ : Optional[Any] = num_epochs if args.partial_train_epoch is not None: UpperCAmelCase_ : List[Any] = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) UpperCAmelCase_ : Tuple = args.resume_from_checkpoint.split('''epoch_''' )[1] UpperCAmelCase_ : int = '''''' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break UpperCAmelCase_ : Union[str, Any] = int(SCREAMING_SNAKE_CASE__ ) + 1 UpperCAmelCase_ : Dict = evaluation_loop(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) accelerator.print('''resumed checkpoint performance:''', SCREAMING_SNAKE_CASE__ ) accelerator.print('''resumed checkpoint\'s scheduler\'s lr:''', lr_scheduler.get_lr()[0] ) accelerator.print('''resumed optimizers\'s lr:''', optimizer.param_groups[0]['''lr'''] ) with open(os.path.join(args.output_dir, F"""state_{starting_epoch-1}.json""" ), '''r''' ) as f: UpperCAmelCase_ : Optional[int] = json.load(SCREAMING_SNAKE_CASE__ ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model UpperCAmelCase_ : int = {} for epoch in range(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Optional[int] = model(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Any = outputs.loss UpperCAmelCase_ : Tuple = loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 UpperCAmelCase_ : Tuple = F"""epoch_{epoch}""" UpperCAmelCase_ : Optional[int] = os.path.join(args.output_dir, SCREAMING_SNAKE_CASE__ ) accelerator.save_state(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = evaluation_loop(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[Any] = accuracy UpperCAmelCase_ : Any = lr_scheduler.get_lr()[0] UpperCAmelCase_ : List[str] = optimizer.param_groups[0]['''lr'''] UpperCAmelCase_ : Tuple = epoch UpperCAmelCase_ : Dict = overall_step accelerator.print(F"""epoch {epoch}:""", SCREAMING_SNAKE_CASE__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F"""state_{epoch}.json""" ), '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( ) -> List[str]: UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''', type=SCREAMING_SNAKE_CASE__, default='''bert-base-cased''', help='''Path to pretrained model or model identifier from huggingface.co/models.''', required=SCREAMING_SNAKE_CASE__, ) parser.add_argument( '''--output_dir''', type=SCREAMING_SNAKE_CASE__, default='''.''', help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''', ) parser.add_argument( '''--resume_from_checkpoint''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''If the training should continue from a checkpoint folder.''', ) parser.add_argument( '''--partial_train_epoch''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''If passed, the training will stop after this number of epochs.''', ) parser.add_argument( '''--num_epochs''', type=SCREAMING_SNAKE_CASE__, default=2, help='''Number of train epochs.''', ) UpperCAmelCase_ : Optional[int] = parser.parse_args() UpperCAmelCase_ : List[Any] = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
644
0
import math class __a : def UpperCAmelCase__ ( self : str , __magic_name__ : list[list[float]] , __magic_name__ : list[int] ) -> int: """simple docstring""" UpperCAmelCase_ : str = 0.0 UpperCAmelCase_ : Tuple = 0.0 for i in range(len(__magic_name__ ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def UpperCAmelCase__ ( self : str , __magic_name__ : list[list[int | float]] , __magic_name__ : list[int] , __magic_name__ : int , __magic_name__ : float ) -> list[list[int | float]]: """simple docstring""" for i in range(len(__magic_name__ ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def lowerCamelCase_ ( ) -> None: # Training Examples ( m, n ) UpperCAmelCase_ : Dict = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) UpperCAmelCase_ : Tuple = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training UpperCAmelCase_ : int = SelfOrganizingMap() UpperCAmelCase_ : Optional[int] = 3 UpperCAmelCase_ : Optional[Any] = 0.5 for _ in range(SCREAMING_SNAKE_CASE__ ): for j in range(len(SCREAMING_SNAKE_CASE__ ) ): # training sample UpperCAmelCase_ : List[Any] = training_samples[j] # Compute the winning vector UpperCAmelCase_ : Tuple = self_organizing_map.get_winner(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # Update the winning vector UpperCAmelCase_ : int = self_organizing_map.update(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # classify test sample UpperCAmelCase_ : List[str] = [0, 0, 0, 1] UpperCAmelCase_ : List[str] = self_organizing_map.get_winner(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # results print(F"""Clusters that the test sample belongs to : {winner}""" ) print(F"""Weights that have been trained : {weights}""" ) # running the main() function if __name__ == "__main__": main()
704
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : list[int] ) -> list[list[int]]: UpperCAmelCase_ : int = [] if len(SCREAMING_SNAKE_CASE__ ) == 1: return [nums.copy()] for _ in range(len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ : List[Any] = nums.pop(0 ) UpperCAmelCase_ : Optional[Any] = permute(SCREAMING_SNAKE_CASE__ ) for perm in permutations: perm.append(SCREAMING_SNAKE_CASE__ ) result.extend(SCREAMING_SNAKE_CASE__ ) nums.append(SCREAMING_SNAKE_CASE__ ) return result def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: def backtrack(SCREAMING_SNAKE_CASE__ : Union[str, Any] ): if start == len(SCREAMING_SNAKE_CASE__ ) - 1: output.append(nums[:] ) else: for i in range(SCREAMING_SNAKE_CASE__, len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ , UpperCAmelCase_ : Tuple = nums[i], nums[start] backtrack(start + 1 ) UpperCAmelCase_ , UpperCAmelCase_ : int = nums[i], nums[start] # backtrack UpperCAmelCase_ : Optional[int] = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function snake_case_ : Tuple = permutea([1, 2, 3]) print(res) doctest.testmod()
644
0
'''simple docstring''' from typing import Dict, Iterable, List, Optional, Union import numpy as np 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_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging snake_case_ : List[Any] = logging.get_logger(__name__) class __a (lowerCamelCase ): __a : Any = ["pixel_values"] def __init__( self : Optional[Any] , __magic_name__ : bool = True , __magic_name__ : Dict[str, int] = None , __magic_name__ : PILImageResampling = PILImageResampling.BICUBIC , __magic_name__ : bool = True , __magic_name__ : Dict[str, int] = None , __magic_name__ : bool = True , __magic_name__ : Union[int, float] = 1 / 2_55 , __magic_name__ : bool = True , __magic_name__ : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN , __magic_name__ : Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD , **__magic_name__ : List[str] , ) -> None: """simple docstring""" super().__init__(**__magic_name__ ) UpperCAmelCase_ : Any = size if size is not None else {'''shortest_edge''': 2_24} UpperCAmelCase_ : int = get_size_dict(__magic_name__ , default_to_square=__magic_name__ ) UpperCAmelCase_ : Any = crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24} UpperCAmelCase_ : Tuple = get_size_dict(__magic_name__ , param_name='''crop_size''' ) UpperCAmelCase_ : Tuple = do_resize UpperCAmelCase_ : List[str] = size UpperCAmelCase_ : int = resample UpperCAmelCase_ : Optional[int] = do_center_crop UpperCAmelCase_ : Dict = crop_size UpperCAmelCase_ : str = do_rescale UpperCAmelCase_ : List[str] = rescale_factor UpperCAmelCase_ : Tuple = do_normalize UpperCAmelCase_ : List[str] = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN UpperCAmelCase_ : Any = image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCAmelCase__ ( self : Any , __magic_name__ : np.ndarray , __magic_name__ : Dict[str, int] , __magic_name__ : PILImageResampling = PILImageResampling.BICUBIC , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : int , ) -> np.ndarray: """simple docstring""" UpperCAmelCase_ : Optional[int] = get_size_dict(__magic_name__ , default_to_square=__magic_name__ ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: UpperCAmelCase_ : Dict = int((2_56 / 2_24) * size['''shortest_edge'''] ) UpperCAmelCase_ : Optional[Any] = get_resize_output_image_size(__magic_name__ , size=__magic_name__ , default_to_square=__magic_name__ ) UpperCAmelCase_ : Any = {'''height''': output_size[0], '''width''': output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( F"""Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}""" ) return resize( __magic_name__ , size=(size_dict['''height'''], size_dict['''width''']) , resample=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : np.ndarray , __magic_name__ : Dict[str, int] , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : Dict , ) -> np.ndarray: """simple docstring""" UpperCAmelCase_ : Optional[Any] = get_size_dict(__magic_name__ ) if "height" not in size or "width" not in size: raise ValueError(F"""Size dict must have keys 'height' and 'width'. Got {size.keys()}""" ) return center_crop(__magic_name__ , size=(size['''height'''], size['''width''']) , data_format=__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : np.ndarray , __magic_name__ : Union[int, float] , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : int , ) -> np.ndarray: """simple docstring""" return rescale(__magic_name__ , scale=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : np.ndarray , __magic_name__ : Union[float, List[float]] , __magic_name__ : Union[float, List[float]] , __magic_name__ : Optional[Union[str, ChannelDimension]] = None , **__magic_name__ : Tuple , ) -> np.ndarray: """simple docstring""" return normalize(__magic_name__ , mean=__magic_name__ , std=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : ImageInput , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[Dict[str, int]] = None , __magic_name__ : PILImageResampling = None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[Dict[str, int]] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[float] = None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[Union[float, Iterable[float]]] = None , __magic_name__ : Optional[Union[float, Iterable[float]]] = None , __magic_name__ : Optional[TensorType] = None , __magic_name__ : ChannelDimension = ChannelDimension.FIRST , **__magic_name__ : Any , ) -> BatchFeature: """simple docstring""" UpperCAmelCase_ : Optional[int] = do_resize if do_resize is not None else self.do_resize UpperCAmelCase_ : List[Any] = resample if resample is not None else self.resample UpperCAmelCase_ : List[str] = do_center_crop if do_center_crop is not None else self.do_center_crop UpperCAmelCase_ : List[Any] = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ : Optional[int] = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase_ : Tuple = do_normalize if do_normalize is not None else self.do_normalize UpperCAmelCase_ : str = image_mean if image_mean is not None else self.image_mean UpperCAmelCase_ : Any = image_std if image_std is not None else self.image_std UpperCAmelCase_ : Optional[int] = size if size is not None else self.size UpperCAmelCase_ : List[Any] = get_size_dict(__magic_name__ , default_to_square=__magic_name__ ) UpperCAmelCase_ : Optional[int] = crop_size if crop_size is not None else self.crop_size UpperCAmelCase_ : int = get_size_dict(__magic_name__ , param_name='''crop_size''' ) UpperCAmelCase_ : int = make_list_of_images(__magic_name__ ) if not valid_images(__magic_name__ ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size 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.''' ) # All transformations expect numpy arrays. UpperCAmelCase_ : str = [to_numpy_array(__magic_name__ ) for image in images] if do_resize: UpperCAmelCase_ : Union[str, Any] = [self.resize(__magic_name__ , __magic_name__ , __magic_name__ ) for image in images] if do_center_crop: UpperCAmelCase_ : Optional[int] = [self.center_crop(__magic_name__ , __magic_name__ ) for image in images] if do_rescale: UpperCAmelCase_ : Optional[Any] = [self.rescale(__magic_name__ , __magic_name__ ) for image in images] if do_normalize: UpperCAmelCase_ : Union[str, Any] = [self.normalize(__magic_name__ , __magic_name__ , __magic_name__ ) for image in images] UpperCAmelCase_ : List[str] = [to_channel_dimension_format(__magic_name__ , __magic_name__ ) for image in images] UpperCAmelCase_ : Dict = {'''pixel_values''': images} return BatchFeature(data=__magic_name__ , tensor_type=__magic_name__ )
705
'''simple docstring''' class __a : def __init__( self : List[Any] , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : Optional[Any] = size UpperCAmelCase_ : Tuple = [0] * size UpperCAmelCase_ : Optional[Any] = [0] * size @staticmethod def UpperCAmelCase__ ( __magic_name__ : int ) -> int: """simple docstring""" return index | (index + 1) @staticmethod def UpperCAmelCase__ ( __magic_name__ : int ) -> int: """simple docstring""" return (index & (index + 1)) - 1 def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : int , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : int = value while index < self.size: UpperCAmelCase_ : str = self.get_prev(__magic_name__ ) + 1 if current_left_border == index: UpperCAmelCase_ : List[str] = value else: UpperCAmelCase_ : Optional[int] = max(__magic_name__ , __magic_name__ , __magic_name__ ) UpperCAmelCase_ : Tuple = self.get_next(__magic_name__ ) def UpperCAmelCase__ ( self : Any , __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" right -= 1 # Because of right is exclusive UpperCAmelCase_ : List[str] = 0 while left <= right: UpperCAmelCase_ : Optional[Any] = self.get_prev(__magic_name__ ) if left <= current_left: UpperCAmelCase_ : Dict = max(__magic_name__ , self.tree[right] ) UpperCAmelCase_ : Optional[Any] = current_left else: UpperCAmelCase_ : str = max(__magic_name__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
644
0
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Dict: UpperCAmelCase_ : Union[str, Any] = len(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = sum(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1, n + 1 ): UpperCAmelCase_ : Tuple = True for i in range(1, s + 1 ): UpperCAmelCase_ : str = False for i in range(1, n + 1 ): for j in range(1, s + 1 ): UpperCAmelCase_ : Any = dp[i][j - 1] if arr[i - 1] <= j: UpperCAmelCase_ : Dict = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ), -1, -1 ): if dp[n][j] is True: UpperCAmelCase_ : Dict = s - 2 * j break return diff
706
'''simple docstring''' import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __a : def __init__( self : List[str] , __magic_name__ : List[str] , __magic_name__ : str=13 , __magic_name__ : Union[str, Any]=7 , __magic_name__ : Union[str, Any]=True , __magic_name__ : Any=True , __magic_name__ : List[str]=False , __magic_name__ : Optional[int]=True , __magic_name__ : Dict=99 , __magic_name__ : Tuple=32 , __magic_name__ : int=5 , __magic_name__ : Dict=4 , __magic_name__ : Tuple=37 , __magic_name__ : Optional[int]="gelu" , __magic_name__ : List[str]=0.1 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : str=5_12 , __magic_name__ : Union[str, Any]=16 , __magic_name__ : int=2 , __magic_name__ : List[Any]=0.0_2 , __magic_name__ : Tuple=3 , __magic_name__ : Union[str, Any]=4 , __magic_name__ : Optional[int]=None , ) -> str: """simple docstring""" UpperCAmelCase_ : Any = parent UpperCAmelCase_ : Union[str, Any] = batch_size UpperCAmelCase_ : List[Any] = seq_length UpperCAmelCase_ : str = is_training UpperCAmelCase_ : Any = use_input_mask UpperCAmelCase_ : List[str] = use_token_type_ids UpperCAmelCase_ : Union[str, Any] = use_labels UpperCAmelCase_ : Dict = vocab_size UpperCAmelCase_ : Optional[Any] = hidden_size UpperCAmelCase_ : Dict = num_hidden_layers UpperCAmelCase_ : List[Any] = num_attention_heads UpperCAmelCase_ : Optional[int] = intermediate_size UpperCAmelCase_ : Union[str, Any] = hidden_act UpperCAmelCase_ : str = hidden_dropout_prob UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase_ : Any = max_position_embeddings UpperCAmelCase_ : str = type_vocab_size UpperCAmelCase_ : Optional[Any] = type_sequence_label_size UpperCAmelCase_ : List[Any] = initializer_range UpperCAmelCase_ : int = num_labels UpperCAmelCase_ : Optional[int] = num_choices UpperCAmelCase_ : Tuple = scope def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : Union[str, Any] = None if self.use_input_mask: UpperCAmelCase_ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ : str = None if self.use_token_type_ids: UpperCAmelCase_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Tuple = None UpperCAmelCase_ : List[str] = None UpperCAmelCase_ : Union[str, Any] = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase_ : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" return BioGptConfig( 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=__magic_name__ , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : Tuple , __magic_name__ : str , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = BioGptModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Dict = model(__magic_name__ , attention_mask=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Tuple , __magic_name__ : List[str] , __magic_name__ : Optional[int] , ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptForCausalLM(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : List[Any] = model(__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase__ ( self : str , __magic_name__ : Optional[int] , __magic_name__ : Tuple , __magic_name__ : List[str] , __magic_name__ : int , __magic_name__ : str , *__magic_name__ : Any ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() # create attention mask UpperCAmelCase_ : Optional[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=__magic_name__ ) UpperCAmelCase_ : Any = self.seq_length // 2 UpperCAmelCase_ : Tuple = 0 # first forward pass UpperCAmelCase_ , UpperCAmelCase_ : Dict = model(__magic_name__ , attention_mask=__magic_name__ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase_ : Tuple = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCAmelCase_ : List[str] = ids_tensor((1,) , __magic_name__ ).item() + 1 UpperCAmelCase_ : Tuple = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCAmelCase_ : str = random_other_next_tokens # append to next input_ids and attn_mask UpperCAmelCase_ : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase_ : int = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=__magic_name__ )] , dim=1 , ) # get two different outputs UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] UpperCAmelCase_ : int = model(__magic_name__ , past_key_values=__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] # select random slice UpperCAmelCase_ : Optional[int] = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase_ : Union[str, Any] = output_from_no_past[:, -1, random_slice_idx].detach() UpperCAmelCase_ : Dict = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Dict , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , *__magic_name__ : str ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptModel(config=__magic_name__ ).to(__magic_name__ ).eval() UpperCAmelCase_ : Optional[int] = torch.ones(input_ids.shape , dtype=torch.long , device=__magic_name__ ) # first forward pass UpperCAmelCase_ : Union[str, Any] = model(__magic_name__ , attention_mask=__magic_name__ , use_cache=__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ : int = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCAmelCase_ : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase_ : Any = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCAmelCase_ : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase_ : List[str] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] UpperCAmelCase_ : Optional[Any] = model(__magic_name__ , attention_mask=__magic_name__ , past_key_values=__magic_name__ )[ '''last_hidden_state''' ] # select random slice UpperCAmelCase_ : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase_ : str = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCAmelCase_ : Optional[int] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-3 ) ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : str , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , *__magic_name__ : Any , __magic_name__ : List[Any]=False ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = BioGptForCausalLM(__magic_name__ ) model.to(__magic_name__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCAmelCase_ : List[str] = model(__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Optional[int] , *__magic_name__ : List[str] ) -> str: """simple docstring""" UpperCAmelCase_ : int = BioGptModel(__magic_name__ ) UpperCAmelCase_ : Dict = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.0_0_1 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.0_1 ) def UpperCAmelCase__ ( self : int , __magic_name__ : Tuple , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , *__magic_name__ : Any ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : str = self.num_labels UpperCAmelCase_ : Any = BioGptForTokenClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" UpperCAmelCase_ : List[Any] = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : int = config_and_inputs UpperCAmelCase_ : Any = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __a (lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : str = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) __a : List[Any] = (BioGptForCausalLM,) if is_torch_available() else () __a : Union[str, Any] = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) __a : List[str] = False def UpperCAmelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" UpperCAmelCase_ : List[str] = BioGptModelTester(self ) UpperCAmelCase_ : Optional[Any] = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ : str = type self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*__magic_name__ , gradient_checkpointing=__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*__magic_name__ ) def UpperCAmelCase__ ( self : Dict ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*__magic_name__ ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*__magic_name__ ) @slow def UpperCAmelCase__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) model.to(__magic_name__ ) UpperCAmelCase_ : List[str] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : Tuple = '''left''' # Define PAD Token = EOS Token = 50256 UpperCAmelCase_ : List[Any] = tokenizer.eos_token UpperCAmelCase_ : List[Any] = model.config.eos_token_id # use different length sentences to test batching UpperCAmelCase_ : Tuple = [ '''Hello, my dog is a little''', '''Today, I''', ] UpperCAmelCase_ : Optional[Any] = tokenizer(__magic_name__ , return_tensors='''pt''' , padding=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = inputs['''input_ids'''].to(__magic_name__ ) UpperCAmelCase_ : Any = model.generate( input_ids=__magic_name__ , attention_mask=inputs['''attention_mask'''].to(__magic_name__ ) , ) UpperCAmelCase_ : Union[str, Any] = tokenizer(sentences[0] , return_tensors='''pt''' ).input_ids.to(__magic_name__ ) UpperCAmelCase_ : Tuple = model.generate(input_ids=__magic_name__ ) UpperCAmelCase_ : List[str] = inputs_non_padded.shape[-1] - inputs['''attention_mask'''][-1].long().sum().cpu().item() UpperCAmelCase_ : List[Any] = tokenizer(sentences[1] , return_tensors='''pt''' ).input_ids.to(__magic_name__ ) UpperCAmelCase_ : Tuple = model.generate(input_ids=__magic_name__ , max_length=model.config.max_length - num_paddings ) UpperCAmelCase_ : int = tokenizer.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Dict = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = [ '''Hello, my dog is a little bit bigger than a little bit.''', '''Today, I have a good idea of how to use the information''', ] self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertListEqual(__magic_name__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : List[Any] = BioGptModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : str = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : List[str] = 3 UpperCAmelCase_ : Tuple = input_dict['''input_ids'''] UpperCAmelCase_ : Dict = input_ids.ne(1 ).to(__magic_name__ ) UpperCAmelCase_ : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCAmelCase_ : Dict = BioGptForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : int = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : List[Any] = 3 UpperCAmelCase_ : Optional[int] = '''multi_label_classification''' UpperCAmelCase_ : int = input_dict['''input_ids'''] UpperCAmelCase_ : str = input_ids.ne(1 ).to(__magic_name__ ) UpperCAmelCase_ : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCAmelCase_ : Union[str, Any] = BioGptForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : str = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __a (unittest.TestCase ): @slow def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" UpperCAmelCase_ : str = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : List[str] = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCAmelCase_ : str = model(__magic_name__ )[0] UpperCAmelCase_ : Optional[int] = 4_23_84 UpperCAmelCase_ : Tuple = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , __magic_name__ ) UpperCAmelCase_ : List[Any] = torch.tensor( [[[-9.5_2_3_6, -9.8_9_1_8, 1_0.4_5_5_7], [-1_1.0_4_6_9, -9.6_4_2_3, 8.1_0_2_2], [-8.8_6_6_4, -7.8_8_2_6, 5.5_3_2_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __magic_name__ , atol=1E-4 ) ) @slow def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Any = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : str = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) model.to(__magic_name__ ) torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = tokenizer('''COVID-19 is''' , return_tensors='''pt''' ).to(__magic_name__ ) UpperCAmelCase_ : Optional[int] = model.generate( **__magic_name__ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=__magic_name__ , ) UpperCAmelCase_ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = ( '''COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the''' ''' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and''' ''' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),''' ''' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and''' ''' more than 800,000 deaths.''' ) self.assertEqual(__magic_name__ , __magic_name__ )
644
0
'''simple docstring''' 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 from lavis.models import load_model_and_preprocess from PIL import Image from transformers import ( AutoTokenizer, BlipaConfig, BlipaForConditionalGeneration, BlipaProcessor, BlipaVisionConfig, BlipImageProcessor, OPTConfig, TaConfig, ) from transformers.utils.constants import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD def lowerCamelCase_ ( ) -> int: UpperCAmelCase_ : Dict = '''https://storage.googleapis.com/sfr-vision-language-research/LAVIS/assets/merlion.png''' UpperCAmelCase_ : Optional[Any] = Image.open(requests.get(SCREAMING_SNAKE_CASE__, stream=SCREAMING_SNAKE_CASE__ ).raw ).convert('''RGB''' ) return image def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: UpperCAmelCase_ : 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.layernorm.weight''') ) rename_keys.append(('''Qformer.bert.embeddings.LayerNorm.bias''', '''qformer.layernorm.bias''') ) # fmt: on return rename_keys def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : List[Any] ) -> Any: UpperCAmelCase_ : int = dct.pop(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Union[str, Any] = val def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[Any], SCREAMING_SNAKE_CASE__ : Tuple ) -> List[str]: for i in range(config.vision_config.num_hidden_layers ): # read in original q and v biases UpperCAmelCase_ : Optional[int] = state_dict.pop(F"""visual_encoder.blocks.{i}.attn.q_bias""" ) UpperCAmelCase_ : Any = state_dict.pop(F"""visual_encoder.blocks.{i}.attn.v_bias""" ) # next, set bias in the state dict UpperCAmelCase_ : Dict = torch.cat((q_bias, torch.zeros_like(SCREAMING_SNAKE_CASE__, requires_grad=SCREAMING_SNAKE_CASE__ ), v_bias) ) UpperCAmelCase_ : Union[str, Any] = qkv_bias def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: UpperCAmelCase_ : Optional[int] = 364 if '''coco''' in model_name else 224 UpperCAmelCase_ : List[str] = BlipaVisionConfig(image_size=SCREAMING_SNAKE_CASE__ ).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 "opt-2.7b" in model_name: UpperCAmelCase_ : Dict = OPTConfig.from_pretrained('''facebook/opt-2.7b''', eos_token_id=SCREAMING_SNAKE_CASE__ ).to_dict() elif "opt-6.7b" in model_name: UpperCAmelCase_ : int = OPTConfig.from_pretrained('''facebook/opt-6.7b''', eos_token_id=SCREAMING_SNAKE_CASE__ ).to_dict() elif "t5-xl" in model_name: UpperCAmelCase_ : Any = TaConfig.from_pretrained('''google/flan-t5-xl''', dense_act_fn='''gelu''', bos_token_id=1 ).to_dict() elif "t5-xxl" in model_name: UpperCAmelCase_ : str = TaConfig.from_pretrained('''google/flan-t5-xxl''', dense_act_fn='''gelu''', bos_token_id=1 ).to_dict() UpperCAmelCase_ : str = BlipaConfig(vision_config=SCREAMING_SNAKE_CASE__, text_config=SCREAMING_SNAKE_CASE__ ) return config, image_size @torch.no_grad() def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : List[str]=None, SCREAMING_SNAKE_CASE__ : Tuple=False ) -> Optional[Any]: UpperCAmelCase_ : Union[str, Any] = ( AutoTokenizer.from_pretrained('''facebook/opt-2.7b''' ) if '''opt''' in model_name else AutoTokenizer.from_pretrained('''google/flan-t5-xl''' ) ) UpperCAmelCase_ : Union[str, Any] = tokenizer('''\n''', add_special_tokens=SCREAMING_SNAKE_CASE__ ).input_ids[0] UpperCAmelCase_ : List[str] = get_blipa_config(SCREAMING_SNAKE_CASE__, eos_token_id=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[int] = BlipaForConditionalGeneration(SCREAMING_SNAKE_CASE__ ).eval() UpperCAmelCase_ : Optional[int] = { '''blip2-opt-2.7b''': ('''blip2_opt''', '''pretrain_opt2.7b'''), '''blip2-opt-6.7b''': ('''blip2_opt''', '''pretrain_opt6.7b'''), '''blip2-opt-2.7b-coco''': ('''blip2_opt''', '''caption_coco_opt2.7b'''), '''blip2-opt-6.7b-coco''': ('''blip2_opt''', '''caption_coco_opt6.7b'''), '''blip2-flan-t5-xl''': ('''blip2_t5''', '''pretrain_flant5xl'''), '''blip2-flan-t5-xl-coco''': ('''blip2_t5''', '''caption_coco_flant5xl'''), '''blip2-flan-t5-xxl''': ('''blip2_t5''', '''pretrain_flant5xxl'''), } UpperCAmelCase_ : List[str] = model_name_to_original[model_name] # load original model print('''Loading original model...''' ) UpperCAmelCase_ : List[Any] = '''cuda''' if torch.cuda.is_available() else '''cpu''' UpperCAmelCase_ : List[Any] = load_model_and_preprocess( name=SCREAMING_SNAKE_CASE__, model_type=SCREAMING_SNAKE_CASE__, is_eval=SCREAMING_SNAKE_CASE__, device=SCREAMING_SNAKE_CASE__ ) original_model.eval() print('''Done!''' ) # update state dict keys UpperCAmelCase_ : Union[str, Any] = original_model.state_dict() UpperCAmelCase_ : Dict = create_rename_keys(SCREAMING_SNAKE_CASE__ ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # some keys can be renamed efficiently for key, val in state_dict.copy().items(): UpperCAmelCase_ : int = state_dict.pop(SCREAMING_SNAKE_CASE__ ) if key.startswith('''Qformer.bert''' ): UpperCAmelCase_ : Optional[int] = key.replace('''Qformer.bert''', '''qformer''' ) if "attention.self" in key: UpperCAmelCase_ : Any = key.replace('''self''', '''attention''' ) if "opt_proj" in key: UpperCAmelCase_ : Tuple = key.replace('''opt_proj''', '''language_projection''' ) if "t5_proj" in key: UpperCAmelCase_ : int = key.replace('''t5_proj''', '''language_projection''' ) if key.startswith('''opt''' ): UpperCAmelCase_ : int = key.replace('''opt''', '''language''' ) if key.startswith('''t5''' ): UpperCAmelCase_ : Union[str, Any] = key.replace('''t5''', '''language''' ) UpperCAmelCase_ : str = val # read in qv biases read_in_q_v_bias(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[Any] = hf_model.load_state_dict(SCREAMING_SNAKE_CASE__, strict=SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == 0 assert unexpected_keys == ["qformer.embeddings.position_ids"] UpperCAmelCase_ : Optional[Any] = load_demo_image() UpperCAmelCase_ : Optional[int] = vis_processors['''eval'''](SCREAMING_SNAKE_CASE__ ).unsqueeze(0 ).to(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = tokenizer(['''\n'''], return_tensors='''pt''' ).input_ids.to(SCREAMING_SNAKE_CASE__ ) # create processor UpperCAmelCase_ : Any = BlipImageProcessor( size={'''height''': image_size, '''width''': image_size}, image_mean=SCREAMING_SNAKE_CASE__, image_std=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Tuple = BlipaProcessor(image_processor=SCREAMING_SNAKE_CASE__, tokenizer=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Dict = processor(images=SCREAMING_SNAKE_CASE__, return_tensors='''pt''' ).pixel_values.to(SCREAMING_SNAKE_CASE__ ) # make sure processor creates exact same pixel values assert torch.allclose(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) original_model.to(SCREAMING_SNAKE_CASE__ ) hf_model.to(SCREAMING_SNAKE_CASE__ ) with torch.no_grad(): if "opt" in model_name: UpperCAmelCase_ : List[Any] = original_model({'''image''': original_pixel_values, '''text_input''': ['''''']} ).logits UpperCAmelCase_ : Any = hf_model(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ).logits else: UpperCAmelCase_ : List[Any] = original_model( {'''image''': original_pixel_values, '''text_input''': ['''\n'''], '''text_output''': ['''\n''']} ).logits UpperCAmelCase_ : Dict = input_ids.masked_fill(input_ids == tokenizer.pad_token_id, -100 ) UpperCAmelCase_ : List[str] = hf_model(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, labels=SCREAMING_SNAKE_CASE__ ).logits assert original_logits.shape == logits.shape print('''First values of original logits:''', original_logits[0, :3, :3] ) print('''First values of HF logits:''', logits[0, :3, :3] ) # assert values if model_name == "blip2-flan-t5-xl": UpperCAmelCase_ : Any = torch.tensor( [[-41.58_50, -4.44_40, -8.99_22], [-47.43_22, -5.91_43, -1.73_40]], device=SCREAMING_SNAKE_CASE__ ) assert torch.allclose(logits[0, :3, :3], SCREAMING_SNAKE_CASE__, atol=1E-4 ) elif model_name == "blip2-flan-t5-xl-coco": UpperCAmelCase_ : Optional[Any] = torch.tensor( [[-57.01_09, -9.89_67, -12.62_80], [-68.65_78, -12.71_91, -10.50_65]], device=SCREAMING_SNAKE_CASE__ ) else: # cast to same type UpperCAmelCase_ : List[str] = logits.dtype assert torch.allclose(original_logits.to(SCREAMING_SNAKE_CASE__ ), SCREAMING_SNAKE_CASE__, atol=1E-2 ) print('''Looks ok!''' ) print('''Generating a caption...''' ) UpperCAmelCase_ : Tuple = '''''' UpperCAmelCase_ : Any = tokenizer(SCREAMING_SNAKE_CASE__, return_tensors='''pt''' ).input_ids.to(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = original_model.generate({'''image''': original_pixel_values} ) UpperCAmelCase_ : str = hf_model.generate( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, do_sample=SCREAMING_SNAKE_CASE__, num_beams=5, max_length=30, min_length=1, top_p=0.9, repetition_penalty=1.0, length_penalty=1.0, temperature=1, ) print('''Original generation:''', SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : str = input_ids.shape[1] UpperCAmelCase_ : Tuple = processor.batch_decode(outputs[:, prompt_length:], skip_special_tokens=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Union[str, Any] = [text.strip() for text in output_text] print('''HF generation:''', SCREAMING_SNAKE_CASE__ ) if pytorch_dump_folder_path is not None: processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: processor.push_to_hub(F"""nielsr/{model_name}""" ) hf_model.push_to_hub(F"""nielsr/{model_name}""" ) if __name__ == "__main__": lowerCamelCase : int = argparse.ArgumentParser() lowerCamelCase : int = [ "blip2-opt-2.7b", "blip2-opt-6.7b", "blip2-opt-2.7b-coco", "blip2-opt-6.7b-coco", "blip2-flan-t5-xl", "blip2-flan-t5-xl-coco", "blip2-flan-t5-xxl", ] parser.add_argument( "--model_name", default="blip2-opt-2.7b", 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", ) lowerCamelCase : List[str] = parser.parse_args() convert_blipa_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
707
'''simple docstring''' import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class __a (lowerCamelCase , unittest.TestCase ): __a : List[str] = BlenderbotSmallTokenizer __a : List[Any] = False def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" super().setUp() UpperCAmelCase_ : Tuple = ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__'''] UpperCAmelCase_ : Optional[Any] = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) UpperCAmelCase_ : int = ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', ''''''] UpperCAmelCase_ : Optional[Any] = {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''} UpperCAmelCase_ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__magic_name__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__magic_name__ ) ) def UpperCAmelCase__ ( self : List[Any] , **__magic_name__ : Dict ) -> Tuple: """simple docstring""" kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : List[str] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : str = '''adapt act apte''' UpperCAmelCase_ : Tuple = '''adapt act apte''' return input_text, output_text def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" UpperCAmelCase_ : str = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCAmelCase_ : List[Any] = '''adapt act apte''' UpperCAmelCase_ : Dict = ['''adapt''', '''act''', '''ap@@''', '''te'''] UpperCAmelCase_ : Dict = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) UpperCAmelCase_ : Tuple = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" UpperCAmelCase_ : List[Any] = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) assert tok('''sam''' ).input_ids == [13_84] UpperCAmelCase_ : Optional[int] = '''I am a small frog.''' UpperCAmelCase_ : List[str] = tok([src_text] , padding=__magic_name__ , truncation=__magic_name__ )['''input_ids'''] UpperCAmelCase_ : Dict = tok.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ , clean_up_tokenization_spaces=__magic_name__ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) UpperCAmelCase_ : List[Any] = '''I am a small frog .''' UpperCAmelCase_ : Any = '''.''' UpperCAmelCase_ : List[Any] = tok(__magic_name__ )['''input_ids'''] UpperCAmelCase_ : Optional[int] = tok(__magic_name__ )['''input_ids'''] assert encoded[-1] == encoded_dot[0]
644
0
'''simple docstring''' import argparse import logging import pickle import random import time import numpy as np from transformers import BertTokenizer, GPTaTokenizer, RobertaTokenizer logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) snake_case_ : str = logging.getLogger(__name__) def lowerCamelCase_ ( ) -> Tuple: UpperCAmelCase_ : int = argparse.ArgumentParser( description='''Preprocess the data to avoid re-doing it several times by (tokenization + token_to_ids).''' ) parser.add_argument('''--file_path''', type=SCREAMING_SNAKE_CASE__, default='''data/dump.txt''', help='''The path to the data.''' ) parser.add_argument('''--tokenizer_type''', type=SCREAMING_SNAKE_CASE__, default='''bert''', choices=['''bert''', '''roberta''', '''gpt2'''] ) parser.add_argument('''--tokenizer_name''', type=SCREAMING_SNAKE_CASE__, default='''bert-base-uncased''', help='''The tokenizer to use.''' ) parser.add_argument('''--dump_file''', type=SCREAMING_SNAKE_CASE__, default='''data/dump''', help='''The dump file prefix.''' ) UpperCAmelCase_ : int = parser.parse_args() logger.info(F"""Loading Tokenizer ({args.tokenizer_name})""" ) if args.tokenizer_type == "bert": UpperCAmelCase_ : Any = BertTokenizer.from_pretrained(args.tokenizer_name ) UpperCAmelCase_ : Tuple = tokenizer.special_tokens_map['''cls_token'''] # `[CLS]` UpperCAmelCase_ : Optional[int] = tokenizer.special_tokens_map['''sep_token'''] # `[SEP]` elif args.tokenizer_type == "roberta": UpperCAmelCase_ : Optional[Any] = RobertaTokenizer.from_pretrained(args.tokenizer_name ) UpperCAmelCase_ : str = tokenizer.special_tokens_map['''cls_token'''] # `<s>` UpperCAmelCase_ : Any = tokenizer.special_tokens_map['''sep_token'''] # `</s>` elif args.tokenizer_type == "gpt2": UpperCAmelCase_ : int = GPTaTokenizer.from_pretrained(args.tokenizer_name ) UpperCAmelCase_ : Optional[Any] = tokenizer.special_tokens_map['''bos_token'''] # `<|endoftext|>` UpperCAmelCase_ : List[Any] = tokenizer.special_tokens_map['''eos_token'''] # `<|endoftext|>` logger.info(F"""Loading text from {args.file_path}""" ) with open(args.file_path, '''r''', encoding='''utf8''' ) as fp: UpperCAmelCase_ : List[str] = fp.readlines() logger.info('''Start encoding''' ) logger.info(F"""{len(SCREAMING_SNAKE_CASE__ )} examples to process.""" ) UpperCAmelCase_ : str = [] UpperCAmelCase_ : Tuple = 0 UpperCAmelCase_ : List[str] = 10000 UpperCAmelCase_ : Any = time.time() for text in data: UpperCAmelCase_ : Optional[int] = F"""{bos} {text.strip()} {sep}""" UpperCAmelCase_ : str = tokenizer.encode(SCREAMING_SNAKE_CASE__, add_special_tokens=SCREAMING_SNAKE_CASE__ ) rslt.append(SCREAMING_SNAKE_CASE__ ) iter += 1 if iter % interval == 0: UpperCAmelCase_ : int = time.time() logger.info(F"""{iter} examples processed. - {(end-start):.2f}s/{interval}expl""" ) UpperCAmelCase_ : Tuple = time.time() logger.info('''Finished binarization''' ) logger.info(F"""{len(SCREAMING_SNAKE_CASE__ )} examples processed.""" ) UpperCAmelCase_ : int = F"""{args.dump_file}.{args.tokenizer_name}.pickle""" UpperCAmelCase_ : Optional[Any] = tokenizer.vocab_size if vocab_size < (1 << 16): UpperCAmelCase_ : Tuple = [np.uintaa(SCREAMING_SNAKE_CASE__ ) for d in rslt] else: UpperCAmelCase_ : List[str] = [np.intaa(SCREAMING_SNAKE_CASE__ ) for d in rslt] random.shuffle(rslt_ ) logger.info(F"""Dump to {dp_file}""" ) with open(SCREAMING_SNAKE_CASE__, '''wb''' ) as handle: pickle.dump(rslt_, SCREAMING_SNAKE_CASE__, protocol=pickle.HIGHEST_PROTOCOL ) if __name__ == "__main__": main()
708
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" UpperCAmelCase_ : Dict = get_activation('''swish''' ) self.assertIsInstance(__magic_name__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , 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 : Tuple ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = get_activation('''silu''' ) self.assertIsInstance(__magic_name__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , 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 : Tuple ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Optional[int] = get_activation('''mish''' ) self.assertIsInstance(__magic_name__ , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , 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 : str ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = get_activation('''gelu''' ) self.assertIsInstance(__magic_name__ , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , 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 )
644
0
'''simple docstring''' from __future__ import annotations from typing import Any class __a : def __init__( self : str , __magic_name__ : int , __magic_name__ : int , __magic_name__ : float = 0 ) -> None: """simple docstring""" UpperCAmelCase_ : Optional[Any] = row, column UpperCAmelCase_ : Any = [[default_value for c in range(__magic_name__ )] for r in range(__magic_name__ )] def __str__( self : Any ) -> str: """simple docstring""" UpperCAmelCase_ : Dict = F"""Matrix consist of {self.row} rows and {self.column} columns\n""" # Make string identifier UpperCAmelCase_ : Tuple = 0 for row_vector in self.array: for obj in row_vector: UpperCAmelCase_ : Optional[Any] = max(__magic_name__ , len(str(__magic_name__ ) ) ) UpperCAmelCase_ : Union[str, Any] = F"""%{max_element_length}s""" # Make string and return def single_line(__magic_name__ : list[float] ) -> str: nonlocal string_format_identifier UpperCAmelCase_ : Dict = '''[''' line += ", ".join(string_format_identifier % (obj,) for obj in row_vector ) line += "]" return line s += "\n".join(single_line(__magic_name__ ) for row_vector in self.array ) return s def __repr__( self : Tuple ) -> str: """simple docstring""" return str(self ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : tuple[int, int] ) -> bool: """simple docstring""" if not (isinstance(__magic_name__ , (list, tuple) ) and len(__magic_name__ ) == 2): return False elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column): return False else: return True def __getitem__( self : Optional[Any] , __magic_name__ : tuple[int, int] ) -> Any: """simple docstring""" assert self.validate_indicies(__magic_name__ ) return self.array[loc[0]][loc[1]] def __setitem__( self : str , __magic_name__ : tuple[int, int] , __magic_name__ : float ) -> None: """simple docstring""" assert self.validate_indicies(__magic_name__ ) UpperCAmelCase_ : Optional[int] = value def __add__( self : Any , __magic_name__ : Matrix ) -> Matrix: """simple docstring""" assert isinstance(__magic_name__ , __magic_name__ ) assert self.row == another.row and self.column == another.column # Add UpperCAmelCase_ : Optional[Any] = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase_ : str = self[r, c] + another[r, c] return result def __neg__( self : Optional[Any] ) -> Matrix: """simple docstring""" UpperCAmelCase_ : Dict = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase_ : str = -self[r, c] return result def __sub__( self : Dict , __magic_name__ : Matrix ) -> Matrix: """simple docstring""" return self + (-another) def __mul__( self : Tuple , __magic_name__ : int | float | Matrix ) -> Matrix: """simple docstring""" if isinstance(__magic_name__ , (int, float) ): # Scalar multiplication UpperCAmelCase_ : Tuple = Matrix(self.row , self.column ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase_ : List[str] = self[r, c] * another return result elif isinstance(__magic_name__ , __magic_name__ ): # Matrix multiplication assert self.column == another.row UpperCAmelCase_ : Dict = Matrix(self.row , another.column ) for r in range(self.row ): for c in range(another.column ): for i in range(self.column ): result[r, c] += self[r, i] * another[i, c] return result else: UpperCAmelCase_ : List[str] = F"""Unsupported type given for another ({type(__magic_name__ )})""" raise TypeError(__magic_name__ ) def UpperCAmelCase__ ( self : List[str] ) -> Matrix: """simple docstring""" UpperCAmelCase_ : Tuple = Matrix(self.column , self.row ) for r in range(self.row ): for c in range(self.column ): UpperCAmelCase_ : List[Any] = self[r, c] return result def UpperCAmelCase__ ( self : Any , __magic_name__ : Matrix , __magic_name__ : Matrix ) -> Any: """simple docstring""" assert isinstance(__magic_name__ , __magic_name__ ) and isinstance(__magic_name__ , __magic_name__ ) assert self.row == self.column == u.row == v.row # u, v should be column vector assert u.column == v.column == 1 # u, v should be column vector # Calculate UpperCAmelCase_ : str = v.transpose() UpperCAmelCase_ : Dict = (v_t * self * u)[0, 0] + 1 if numerator_factor == 0: return None # It's not invertable return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor)) # Testing if __name__ == "__main__": def lowerCamelCase_ ( ) -> None: # a^(-1) UpperCAmelCase_ : Any = Matrix(3, 3, 0 ) for i in range(3 ): UpperCAmelCase_ : List[str] = 1 print(F"""a^(-1) is {ainv}""" ) # u, v UpperCAmelCase_ : List[Any] = Matrix(3, 1, 0 ) UpperCAmelCase_ : Tuple = 1, 2, -3 UpperCAmelCase_ : Optional[Any] = Matrix(3, 1, 0 ) UpperCAmelCase_ : Tuple = 4, -2, 5 print(F"""u is {u}""" ) print(F"""v is {v}""" ) print(F"""uv^T is {u * v.transpose()}""" ) # Sherman Morrison print(F"""(a + uv^T)^(-1) is {ainv.sherman_morrison(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )}""" ) def lowerCamelCase_ ( ) -> None: import doctest doctest.testmod() testa()
709
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging snake_case_ : Union[str, Any] = logging.get_logger(__name__) class __a (lowerCamelCase ): __a : Tuple = ["pixel_values"] def __init__( self : List[Any] , __magic_name__ : bool = True , __magic_name__ : int = 32 , __magic_name__ : Union[str, Any]=PILImageResampling.BILINEAR , __magic_name__ : bool = True , **__magic_name__ : List[str] , ) -> None: """simple docstring""" UpperCAmelCase_ : int = do_resize UpperCAmelCase_ : Tuple = do_rescale UpperCAmelCase_ : List[Any] = size_divisor UpperCAmelCase_ : Any = resample super().__init__(**__magic_name__ ) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : np.ndarray , __magic_name__ : int , __magic_name__ : str , __magic_name__ : Optional[ChannelDimension] = None , **__magic_name__ : Tuple ) -> np.ndarray: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : List[str] = get_image_size(__magic_name__ ) # Rounds the height and width down to the closest multiple of size_divisor UpperCAmelCase_ : Dict = height // size_divisor * size_divisor UpperCAmelCase_ : Dict = width // size_divisor * size_divisor UpperCAmelCase_ : Any = resize(__magic_name__ , (new_h, new_w) , resample=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) return image def UpperCAmelCase__ ( self : int , __magic_name__ : np.ndarray , __magic_name__ : float , __magic_name__ : Optional[ChannelDimension] = None , **__magic_name__ : Optional[Any] ) -> np.ndarray: """simple docstring""" return rescale(image=__magic_name__ , scale=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : str , __magic_name__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[int] = None , __magic_name__ : Any=None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[Union[TensorType, str]] = None , __magic_name__ : ChannelDimension = ChannelDimension.FIRST , **__magic_name__ : Tuple , ) -> BatchFeature: """simple docstring""" UpperCAmelCase_ : Dict = do_resize if do_resize is not None else self.do_resize UpperCAmelCase_ : str = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ : Any = size_divisor if size_divisor is not None else self.size_divisor UpperCAmelCase_ : Dict = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('''size_divisor is required for resizing''' ) UpperCAmelCase_ : Optional[int] = make_list_of_images(__magic_name__ ) if not valid_images(__magic_name__ ): raise ValueError('''Invalid image(s)''' ) # All transformations expect numpy arrays. UpperCAmelCase_ : List[str] = [to_numpy_array(__magic_name__ ) for img in images] if do_resize: UpperCAmelCase_ : str = [self.resize(__magic_name__ , size_divisor=__magic_name__ , resample=__magic_name__ ) for image in images] if do_rescale: UpperCAmelCase_ : Tuple = [self.rescale(__magic_name__ , scale=1 / 2_55 ) for image in images] UpperCAmelCase_ : Union[str, Any] = [to_channel_dimension_format(__magic_name__ , __magic_name__ ) for image in images] UpperCAmelCase_ : int = {'''pixel_values''': images} return BatchFeature(data=__magic_name__ , tensor_type=__magic_name__ )
644
0
'''simple docstring''' from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case_ = { "configuration_autoformer": [ "AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "AutoformerConfig", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ "AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "AutoformerForPrediction", "AutoformerModel", "AutoformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
710
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int = 10, SCREAMING_SNAKE_CASE__ : int = 22 ) -> int: UpperCAmelCase_ : Optional[int] = range(1, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = range(1, SCREAMING_SNAKE_CASE__ ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(f'''{solution(10, 22) = }''')
644
0
'''simple docstring''' snake_case_ : List[Any] = 8.314_4598 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : float, SCREAMING_SNAKE_CASE__ : float ) -> float: 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 snake_case_ : int = 3_00 snake_case_ : Dict = 28 snake_case_ : Optional[Any] = rms_speed_of_molecule(temperature, molar_mass) print(f'''Vrms of Nitrogen gas at 300 K is {vrms} m/s''')
711
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __a (lowerCamelCase ): __a : int = "dandelin/vilt-b32-finetuned-vqa" __a : Any = ( "This is a tool that answers a question about an image. It takes an input named `image` which should be the " "image containing the information, as well as a `question` which should be the question in English. It " "returns a text that is the answer to the question." ) __a : Any = "image_qa" __a : str = AutoProcessor __a : Any = AutoModelForVisualQuestionAnswering __a : List[Any] = ["image", "text"] __a : int = ["text"] def __init__( self : Tuple , *__magic_name__ : Any , **__magic_name__ : Any ) -> Tuple: """simple docstring""" requires_backends(self , ['''vision'''] ) super().__init__(*__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : "Image" , __magic_name__ : str ) -> Tuple: """simple docstring""" return self.pre_processor(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) def UpperCAmelCase__ ( self : Any , __magic_name__ : List[str] ) -> Optional[Any]: """simple docstring""" with torch.no_grad(): return self.model(**__magic_name__ ).logits def UpperCAmelCase__ ( self : int , __magic_name__ : int ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Dict = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
644
0
'''simple docstring''' import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py snake_case_ : Optional[int] = "src/transformers" # This is to make sure the transformers module imported is the one in the repo. snake_case_ : Optional[int] = direct_transformers_import(PATH_TO_TRANSFORMERS) snake_case_ : Optional[Any] = transformers.models.auto.configuration_auto.CONFIG_MAPPING snake_case_ : int = { # used to compute the property `self.chunk_length` "EncodecConfig": ["overlap"], # used as `self.bert_model = BertModel(config, ...)` "DPRConfig": True, # not used in modeling files, but it's an important information "FSMTConfig": ["langs"], # used internally in the configuration class file "GPTNeoConfig": ["attention_types"], # used internally in the configuration class file "EsmConfig": ["is_folding_model"], # used during training (despite we don't have training script for these models yet) "Mask2FormerConfig": ["ignore_value"], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) "OneFormerConfig": ["ignore_value", "norm"], # used during preprocessing and collation, see `collating_graphormer.py` "GraphormerConfig": ["spatial_pos_max"], # used internally in the configuration class file "T5Config": ["feed_forward_proj"], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally "MT5Config": ["feed_forward_proj", "tokenizer_class"], "UMT5Config": ["feed_forward_proj", "tokenizer_class"], # used internally in the configuration class file "LongT5Config": ["feed_forward_proj"], # used internally in the configuration class file "SwitchTransformersConfig": ["feed_forward_proj"], # having default values other than `1e-5` - we can't fix them without breaking "BioGptConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "GLPNConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "SegformerConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "CvtConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "PerceiverConfig": ["layer_norm_eps"], # used internally to calculate the feature size "InformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate the feature size "TimeSeriesTransformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate the feature size "AutoformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate `mlp_dim` "SamVisionConfig": ["mlp_ratio"], # For (head) training, but so far not implemented "ClapAudioConfig": ["num_classes"], # Not used, but providing useful information to users "SpeechT5HifiGanConfig": ["sampling_rate"], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { "CLIPSegConfig": True, "DeformableDetrConfig": True, "DetaConfig": True, "DinatConfig": True, "DonutSwinConfig": True, "EfficientFormerConfig": True, "FSMTConfig": True, "JukeboxConfig": True, "LayoutLMv2Config": True, "MaskFormerSwinConfig": True, "MT5Config": True, "NatConfig": True, "OneFormerConfig": True, "PerceiverConfig": True, "RagConfig": True, "SpeechT5Config": True, "SwinConfig": True, "Swin2SRConfig": True, "Swinv2Config": True, "SwitchTransformersConfig": True, "TableTransformerConfig": True, "TapasConfig": True, "TransfoXLConfig": True, "UniSpeechConfig": True, "UniSpeechSatConfig": True, "WavLMConfig": True, "WhisperConfig": True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) "JukeboxPriorConfig": True, # TODO: @Younes (for `is_decoder`) "Pix2StructTextConfig": True, } ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : List[Any], SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: UpperCAmelCase_ : Union[str, Any] = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( F"""config.{attribute}""" in modeling_source or F"""getattr(config, \"{attribute}\"""" in modeling_source or F"""getattr(self.config, \"{attribute}\"""" in modeling_source ): UpperCAmelCase_ : int = True # Deal with multi-line cases elif ( re.search( RF"""getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*\"{attribute}\"""", SCREAMING_SNAKE_CASE__, ) is not None ): UpperCAmelCase_ : Any = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: UpperCAmelCase_ : Optional[int] = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files UpperCAmelCase_ : Union[str, Any] = [ '''bos_index''', '''eos_index''', '''pad_index''', '''unk_index''', '''mask_index''', '''image_size''', '''use_cache''', '''out_features''', '''out_indices''', ] UpperCAmelCase_ : Any = ['''encoder_no_repeat_ngram_size'''] # Special cases to be allowed UpperCAmelCase_ : Union[str, Any] = True if not attribute_used: UpperCAmelCase_ : List[str] = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: UpperCAmelCase_ : Tuple = True elif attribute in ["tie_word_embeddings"] and default_value is False: UpperCAmelCase_ : Any = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: UpperCAmelCase_ : Optional[int] = True elif attribute.endswith('''_token_id''' ): UpperCAmelCase_ : Any = True # configuration class specific cases if not case_allowed: UpperCAmelCase_ : str = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__, [] ) UpperCAmelCase_ : Tuple = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int ) -> str: UpperCAmelCase_ : Any = dict(inspect.signature(config_class.__init__ ).parameters ) UpperCAmelCase_ : List[Any] = [x for x in list(signature.keys() ) if x not in ['''self''', '''kwargs''']] UpperCAmelCase_ : str = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass UpperCAmelCase_ : Tuple = {} if len(config_class.attribute_map ) > 0: UpperCAmelCase_ : Optional[int] = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files UpperCAmelCase_ : Optional[int] = inspect.getsourcefile(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[int] = os.path.dirname(SCREAMING_SNAKE_CASE__ ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. UpperCAmelCase_ : Optional[int] = [os.path.join(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) for fn in os.listdir(SCREAMING_SNAKE_CASE__ ) if fn.startswith('''modeling_''' )] # Get the source code strings UpperCAmelCase_ : List[str] = [] for path in modeling_paths: if os.path.isfile(SCREAMING_SNAKE_CASE__ ): with open(SCREAMING_SNAKE_CASE__ ) as fp: modeling_sources.append(fp.read() ) UpperCAmelCase_ : Dict = [] for config_param, default_value in zip(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): # `attributes` here is all the variant names for `config_param` UpperCAmelCase_ : List[Any] = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): unused_attributes.append(attributes[0] ) return sorted(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( ) -> List[str]: UpperCAmelCase_ : str = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) UpperCAmelCase_ : Any = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ), lambda SCREAMING_SNAKE_CASE__ : inspect.isclass(SCREAMING_SNAKE_CASE__ ) and issubclass(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) and inspect.getmodule(SCREAMING_SNAKE_CASE__ ) == inspect.getmodule(_config_class ), ) ] for config_class in config_classes_in_module: UpperCAmelCase_ : Optional[Any] = check_config_attributes_being_used(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) > 0: UpperCAmelCase_ : Optional[int] = unused_attributes if len(SCREAMING_SNAKE_CASE__ ) > 0: UpperCAmelCase_ : Dict = '''The following configuration classes contain unused attributes in the corresponding modeling files:\n''' for name, attributes in configs_with_unused_attributes.items(): error += F"""{name}: {attributes}\n""" raise ValueError(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": check_config_attributes()
712
'''simple docstring''' from collections.abc import Iterable from typing import Any class __a : def __init__( self : Optional[Any] , __magic_name__ : int | None = None ) -> Tuple: """simple docstring""" UpperCAmelCase_ : List[str] = value UpperCAmelCase_ : Node | None = None # Added in order to delete a node easier UpperCAmelCase_ : Node | None = None UpperCAmelCase_ : Node | None = None def __repr__( self : List[str] ) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({F"""{self.value}""": (self.left, self.right)} , indent=1 ) class __a : def __init__( self : int , __magic_name__ : Node | None = None ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : str = root def __str__( self : Any ) -> str: """simple docstring""" return str(self.root ) def UpperCAmelCase__ ( self : Any , __magic_name__ : Node , __magic_name__ : Node | None ) -> None: """simple docstring""" if new_children is not None: # reset its kids UpperCAmelCase_ : Dict = node.parent if node.parent is not None: # reset its parent if self.is_right(__magic_name__ ): # If it is the right children UpperCAmelCase_ : Optional[Any] = new_children else: UpperCAmelCase_ : Optional[int] = new_children else: UpperCAmelCase_ : List[str] = new_children def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Node ) -> bool: """simple docstring""" if node.parent and node.parent.right: return node == node.parent.right return False def UpperCAmelCase__ ( self : Union[str, Any] ) -> bool: """simple docstring""" return self.root is None def UpperCAmelCase__ ( self : Any , __magic_name__ : str ) -> None: """simple docstring""" UpperCAmelCase_ : Tuple = Node(__magic_name__ ) # create a new Node if self.empty(): # if Tree is empty UpperCAmelCase_ : List[Any] = new_node # set its root else: # Tree is not empty UpperCAmelCase_ : str = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: UpperCAmelCase_ : Union[str, Any] = new_node # We insert the new node in a leaf break else: UpperCAmelCase_ : List[Any] = parent_node.left else: if parent_node.right is None: UpperCAmelCase_ : List[Any] = new_node break else: UpperCAmelCase_ : Union[str, Any] = parent_node.right UpperCAmelCase_ : Union[str, Any] = parent_node def UpperCAmelCase__ ( self : Optional[Any] , *__magic_name__ : List[str] ) -> None: """simple docstring""" for value in values: self.__insert(__magic_name__ ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : int ) -> Node | None: """simple docstring""" if self.empty(): raise IndexError('''Warning: Tree is empty! please use another.''' ) else: UpperCAmelCase_ : str = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: UpperCAmelCase_ : List[str] = node.left if value < node.value else node.right return node def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Node | None = None ) -> Node | None: """simple docstring""" if node is None: if self.root is None: return None UpperCAmelCase_ : Dict = self.root if not self.empty(): while node.right is not None: UpperCAmelCase_ : Any = node.right return node def UpperCAmelCase__ ( self : Dict , __magic_name__ : Node | None = None ) -> Node | None: """simple docstring""" if node is None: UpperCAmelCase_ : Optional[int] = self.root if self.root is None: return None if not self.empty(): UpperCAmelCase_ : Union[str, Any] = self.root while node.left is not None: UpperCAmelCase_ : Dict = node.left return node def UpperCAmelCase__ ( self : Tuple , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : List[str] = self.search(__magic_name__ ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(__magic_name__ , __magic_name__ ) elif node.left is None: # Has only right children self.__reassign_nodes(__magic_name__ , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(__magic_name__ , node.left ) else: UpperCAmelCase_ : List[str] = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore UpperCAmelCase_ : Optional[int] = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Node | None ) -> Iterable: """simple docstring""" if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : List[Any]=None ) -> Any: """simple docstring""" if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : list , __magic_name__ : Node | None ) -> None: """simple docstring""" if node: self.inorder(__magic_name__ , node.left ) arr.append(node.value ) self.inorder(__magic_name__ , node.right ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : int , __magic_name__ : Node ) -> int: """simple docstring""" UpperCAmelCase_ : list[int] = [] self.inorder(__magic_name__ , __magic_name__ ) # append all values to list using inorder traversal return arr[k - 1] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Node | None ) -> list[Node]: UpperCAmelCase_ : Any = [] if curr_node is not None: UpperCAmelCase_ : Any = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def lowerCamelCase_ ( ) -> None: UpperCAmelCase_ : str = (8, 3, 6, 1, 10, 14, 13, 4, 7) UpperCAmelCase_ : Tuple = BinarySearchTree() for i in testlist: t.insert(SCREAMING_SNAKE_CASE__ ) # Prints all the elements of the list in order traversal print(SCREAMING_SNAKE_CASE__ ) if t.search(6 ) is not None: print('''The value 6 exists''' ) else: print('''The value 6 doesn\'t exist''' ) if t.search(-1 ) is not None: print('''The value -1 exists''' ) else: print('''The value -1 doesn\'t exist''' ) if not t.empty(): print('''Max Value: ''', t.get_max().value ) # type: ignore print('''Min Value: ''', t.get_min().value ) # type: ignore for i in testlist: t.remove(SCREAMING_SNAKE_CASE__ ) print(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
644
0
import requests def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : str ) -> None: UpperCAmelCase_ : List[str] = {'''Content-Type''': '''application/json'''} UpperCAmelCase_ : Optional[Any] = requests.post(SCREAMING_SNAKE_CASE__, json={'''text''': message_body}, headers=SCREAMING_SNAKE_CASE__ ) if response.status_code != 200: UpperCAmelCase_ : str = ( '''Request to slack returned an error ''' F"""{response.status_code}, the response is:\n{response.text}""" ) raise ValueError(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("<YOUR MESSAGE BODY>", "<SLACK CHANNEL URL>")
713
'''simple docstring''' import sys import turtle def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float] ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : int, ) -> None: my_pen.up() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) if depth == 0: return triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( "Correct format for using this script: " "python fractals.py <int:depth_for_fractal>" ) snake_case_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor("red") snake_case_ : Tuple = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
644
0
import unittest from transformers import CamembertTokenizer, CamembertTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import is_torch_available from ...test_tokenization_common import TokenizerTesterMixin snake_case_ : Tuple = get_tests_dir("fixtures/test_sentencepiece.model") snake_case_ : List[str] = get_tests_dir("fixtures/test_sentencepiece_bpe.model") snake_case_ : List[str] = "pt" if is_torch_available() else "tf" @require_sentencepiece @require_tokenizers class __a (lowerCamelCase , unittest.TestCase ): __a : str = CamembertTokenizer __a : Optional[int] = CamembertTokenizerFast __a : List[Any] = True __a : Union[str, Any] = True def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase_ : Optional[Any] = CamembertTokenizer(__magic_name__ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : Any ) -> Tuple: """simple docstring""" UpperCAmelCase_ : int = '''<pad>''' UpperCAmelCase_ : Union[str, Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__magic_name__ ) , __magic_name__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__magic_name__ ) , __magic_name__ ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : List[str] = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>NOTUSED''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-1] , '''<mask>''' ) self.assertEqual(len(__magic_name__ ) , 10_04 ) def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 10_05 ) def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[Any] = CamembertTokenizer(__magic_name__ ) tokenizer.save_pretrained(self.tmpdirname ) UpperCAmelCase_ : Optional[Any] = CamembertTokenizerFast.from_pretrained(self.tmpdirname ) UpperCAmelCase_ : Optional[int] = '''I was born in 92000, and this is falsé.''' UpperCAmelCase_ : Any = tokenizer.encode(__magic_name__ ) UpperCAmelCase_ : Optional[Any] = rust_tokenizer.encode(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) UpperCAmelCase_ : Tuple = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) UpperCAmelCase_ : List[str] = rust_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) # <unk> tokens are not the same for `rust` than for `slow`. # Because spm gives back raw token instead of `unk` in EncodeAsPieces # tokens = tokenizer.tokenize(sequence) UpperCAmelCase_ : List[Any] = tokenizer.convert_ids_to_tokens(__magic_name__ ) UpperCAmelCase_ : Any = rust_tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" if not self.test_rust_tokenizer: return UpperCAmelCase_ : List[str] = self.get_tokenizer() UpperCAmelCase_ : Union[str, Any] = self.get_rust_tokenizer() UpperCAmelCase_ : List[Any] = '''I was born in 92000, and this is falsé.''' UpperCAmelCase_ : int = tokenizer.tokenize(__magic_name__ ) UpperCAmelCase_ : List[Any] = rust_tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) UpperCAmelCase_ : int = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) UpperCAmelCase_ : Any = rust_tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) UpperCAmelCase_ : Tuple = self.get_rust_tokenizer() UpperCAmelCase_ : int = tokenizer.encode(__magic_name__ ) UpperCAmelCase_ : List[Any] = rust_tokenizer.encode(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) @slow def UpperCAmelCase__ ( self : Any ) -> str: """simple docstring""" UpperCAmelCase_ : str = {'''input_ids''': [[5, 54, 71_96, 2_97, 30, 23, 7_76, 18, 11, 32_15, 37_05, 82_52, 22, 31_64, 11_81, 21_16, 29, 16, 8_13, 25, 7_91, 33_14, 20, 34_46, 38, 2_75_75, 1_20, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 4_68, 17, 11, 90_88, 20, 15_17, 8, 2_28_04, 1_88_18, 10, 38, 6_29, 6_07, 6_07, 1_42, 19, 71_96, 8_67, 56, 1_03_26, 24, 22_67, 20, 4_16, 50_72, 1_56_12, 2_33, 7_34, 7, 23_99, 27, 16, 30_15, 16_49, 7, 24, 20, 43_38, 23_99, 27, 13, 34_00, 14, 13, 61_89, 8, 9_30, 9, 6]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # camembert is a french model. So we also use french texts. UpperCAmelCase_ : List[Any] = [ '''Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ''' '''utilisé principalement dans le domaine du traitement automatique des langues (TAL).''', '''À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ''' '''pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ''' '''telles que la traduction et la synthèse de texte.''', ] self.tokenizer_integration_test_util( expected_encoding=__magic_name__ , model_name='''camembert-base''' , revision='''3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf''' , sequences=__magic_name__ , )
714
'''simple docstring''' import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device snake_case_ : List[str] = False class __a (unittest.TestCase ): pass @nightly @require_torch_gpu class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCAmelCase_ : Optional[int] = torch.manual_seed(0 ) UpperCAmelCase_ : Union[str, Any] = pipe.dual_guided( prompt='''first prompt''' , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__magic_name__ ) UpperCAmelCase_ : Optional[int] = VersatileDiffusionPipeline.from_pretrained(__magic_name__ , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Any = generator.manual_seed(0 ) UpperCAmelCase_ : Dict = pipe.dual_guided( prompt='''first prompt''' , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : str = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = '''cyberpunk 2077''' UpperCAmelCase_ : Union[str, Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCAmelCase_ : Tuple = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = pipe.dual_guided( prompt=__magic_name__ , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images UpperCAmelCase_ : List[str] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Union[str, Any] = np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 UpperCAmelCase_ : Tuple = '''A painting of a squirrel eating a burger ''' UpperCAmelCase_ : Optional[int] = torch.manual_seed(0 ) UpperCAmelCase_ : List[Any] = pipe.text_to_image( prompt=__magic_name__ , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images UpperCAmelCase_ : Tuple = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Any = np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 UpperCAmelCase_ : Tuple = pipe.image_variation(__magic_name__ , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Optional[Any] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : List[str] = np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
644
0
'''simple docstring''' from __future__ import annotations class __a : def __init__( self : Optional[int] , __magic_name__ : str=None ) -> Any: """simple docstring""" UpperCAmelCase_ : List[Any] = data UpperCAmelCase_ : Optional[int] = None def __repr__( self : List[str] ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Any = [] UpperCAmelCase_ : Any = self while temp: string_rep.append(F"""{temp.data}""" ) UpperCAmelCase_ : List[str] = temp.next return "->".join(__magic_name__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : list ) -> Optional[int]: if not elements_list: raise Exception('''The Elements List is empty''' ) UpperCAmelCase_ : Tuple = Node(elements_list[0] ) for i in range(1, len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ : Tuple = Node(elements_list[i] ) UpperCAmelCase_ : str = current.next return head def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Node ) -> None: if head_node is not None and isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): print_reverse(head_node.next ) print(head_node.data ) def lowerCamelCase_ ( ) -> Optional[Any]: from doctest import testmod testmod() UpperCAmelCase_ : Optional[Any] = make_linked_list([14, 52, 14, 12, 43] ) print('''Linked List:''' ) print(SCREAMING_SNAKE_CASE__ ) print('''Elements in Reverse:''' ) print_reverse(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
715
'''simple docstring''' snake_case_ : int = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
644
0
'''simple docstring''' import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class __a (lowerCamelCase ): def __init__( self : int , __magic_name__ : UNetaDModel , __magic_name__ : UNetaDModel , __magic_name__ : DDPMScheduler , __magic_name__ : Union[str, Any] , ) -> Dict: """simple docstring""" super().__init__() UpperCAmelCase_ : Optional[int] = value_function UpperCAmelCase_ : Tuple = unet UpperCAmelCase_ : List[Any] = scheduler UpperCAmelCase_ : List[str] = env UpperCAmelCase_ : Any = env.get_dataset() UpperCAmelCase_ : str = {} for key in self.data.keys(): try: UpperCAmelCase_ : Optional[int] = self.data[key].mean() except: # noqa: E722 pass UpperCAmelCase_ : Dict = {} for key in self.data.keys(): try: UpperCAmelCase_ : Tuple = self.data[key].std() except: # noqa: E722 pass UpperCAmelCase_ : List[str] = env.observation_space.shape[0] UpperCAmelCase_ : Union[str, Any] = env.action_space.shape[0] def UpperCAmelCase__ ( self : int , __magic_name__ : str , __magic_name__ : Optional[int] ) -> Tuple: """simple docstring""" return (x_in - self.means[key]) / self.stds[key] def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Dict , __magic_name__ : Any ) -> Optional[int]: """simple docstring""" return x_in * self.stds[key] + self.means[key] def UpperCAmelCase__ ( self : str , __magic_name__ : str ) -> Dict: """simple docstring""" if type(__magic_name__ ) is dict: return {k: self.to_torch(__magic_name__ ) for k, v in x_in.items()} elif torch.is_tensor(__magic_name__ ): return x_in.to(self.unet.device ) return torch.tensor(__magic_name__ , device=self.unet.device ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : str , __magic_name__ : List[str] , __magic_name__ : Tuple ) -> Tuple: """simple docstring""" for key, val in cond.items(): UpperCAmelCase_ : Union[str, Any] = val.clone() return x_in def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Tuple , __magic_name__ : Tuple , __magic_name__ : str , __magic_name__ : List[Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = x.shape[0] UpperCAmelCase_ : int = None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model UpperCAmelCase_ : Union[str, Any] = torch.full((batch_size,) , __magic_name__ , device=self.unet.device , dtype=torch.long ) for _ in range(__magic_name__ ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models UpperCAmelCase_ : List[str] = self.value_function(x.permute(0 , 2 , 1 ) , __magic_name__ ).sample UpperCAmelCase_ : str = torch.autograd.grad([y.sum()] , [x] )[0] UpperCAmelCase_ : Union[str, Any] = self.scheduler._get_variance(__magic_name__ ) UpperCAmelCase_ : str = torch.exp(0.5 * posterior_variance ) UpperCAmelCase_ : Union[str, Any] = model_std * grad UpperCAmelCase_ : int = 0 UpperCAmelCase_ : List[str] = x.detach() UpperCAmelCase_ : str = x + scale * grad UpperCAmelCase_ : int = self.reset_xa(__magic_name__ , __magic_name__ , self.action_dim ) UpperCAmelCase_ : Optional[int] = self.unet(x.permute(0 , 2 , 1 ) , __magic_name__ ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg UpperCAmelCase_ : Dict = self.scheduler.step(__magic_name__ , __magic_name__ , __magic_name__ , predict_epsilon=__magic_name__ )['''prev_sample'''] # apply conditions to the trajectory (set the initial state) UpperCAmelCase_ : Any = self.reset_xa(__magic_name__ , __magic_name__ , self.action_dim ) UpperCAmelCase_ : Union[str, Any] = self.to_torch(__magic_name__ ) return x, y def __call__( self : Optional[Any] , __magic_name__ : List[str] , __magic_name__ : str=64 , __magic_name__ : Optional[Any]=32 , __magic_name__ : List[str]=2 , __magic_name__ : List[str]=0.1 ) -> int: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.normalize(__magic_name__ , '''observations''' ) UpperCAmelCase_ : Dict = obs[None].repeat(__magic_name__ , axis=0 ) UpperCAmelCase_ : List[str] = {0: self.to_torch(__magic_name__ )} UpperCAmelCase_ : Optional[int] = (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) UpperCAmelCase_ : Optional[int] = randn_tensor(__magic_name__ , device=self.unet.device ) UpperCAmelCase_ : Union[str, Any] = self.reset_xa(__magic_name__ , __magic_name__ , self.action_dim ) UpperCAmelCase_ : Tuple = self.to_torch(__magic_name__ ) # run the diffusion process UpperCAmelCase_ : Dict = self.run_diffusion(__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ ) # sort output trajectories by value UpperCAmelCase_ : List[str] = y.argsort(0 , descending=__magic_name__ ).squeeze() UpperCAmelCase_ : Optional[Any] = x[sorted_idx] UpperCAmelCase_ : List[Any] = sorted_values[:, :, : self.action_dim] UpperCAmelCase_ : Optional[Any] = actions.detach().cpu().numpy() UpperCAmelCase_ : Union[str, Any] = self.de_normalize(__magic_name__ , key='''actions''' ) # select the action with the highest value if y is not None: UpperCAmelCase_ : List[str] = 0 else: # if we didn't run value guiding, select a random action UpperCAmelCase_ : List[Any] = np.random.randint(0 , __magic_name__ ) UpperCAmelCase_ : Tuple = denorm_actions[selected_index, 0] return denorm_actions
716
'''simple docstring''' import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __a (unittest.TestCase ): @property def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def UpperCAmelCase__ ( self : Dict ) -> Tuple: """simple docstring""" UpperCAmelCase_ : List[Any] = self.dummy_uncond_unet UpperCAmelCase_ : Dict = KarrasVeScheduler() UpperCAmelCase_ : Union[str, Any] = KarrasVePipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Dict = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[int] = pipe(num_inference_steps=2 , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Tuple = torch.manual_seed(0 ) UpperCAmelCase_ : str = pipe(num_inference_steps=2 , generator=__magic_name__ , output_type='''numpy''' , return_dict=__magic_name__ )[0] UpperCAmelCase_ : Union[str, Any] = image[0, -3:, -3:, -1] UpperCAmelCase_ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase_ : Dict = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : List[str] = '''google/ncsnpp-celebahq-256''' UpperCAmelCase_ : List[str] = UNetaDModel.from_pretrained(__magic_name__ ) UpperCAmelCase_ : List[Any] = KarrasVeScheduler() UpperCAmelCase_ : Any = KarrasVePipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Dict = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = pipe(num_inference_steps=20 , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) UpperCAmelCase_ : Optional[Any] = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
644
0
'''simple docstring''' from __future__ import annotations from typing import Any class __a : def __init__( self : List[Any] , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : List[Any] = num_of_nodes UpperCAmelCase_ : list[list[int]] = [] UpperCAmelCase_ : dict[int, int] = {} def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : int ) -> None: """simple docstring""" self.m_edges.append([u_node, v_node, weight] ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : int ) -> int: """simple docstring""" if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : int ) -> None: """simple docstring""" if self.m_component[u_node] != u_node: for k in self.m_component: UpperCAmelCase_ : int = self.find_component(__magic_name__ ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : list[int] , __magic_name__ : int , __magic_name__ : int ) -> None: """simple docstring""" if component_size[u_node] <= component_size[v_node]: UpperCAmelCase_ : Dict = v_node component_size[v_node] += component_size[u_node] self.set_component(__magic_name__ ) elif component_size[u_node] >= component_size[v_node]: UpperCAmelCase_ : str = self.find_component(__magic_name__ ) component_size[u_node] += component_size[v_node] self.set_component(__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> None: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = [] UpperCAmelCase_ : List[str] = 0 UpperCAmelCase_ : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) UpperCAmelCase_ : Optional[int] = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: UpperCAmelCase_ : Tuple = edge UpperCAmelCase_ : List[Any] = self.m_component[u] UpperCAmelCase_ : List[Any] = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): UpperCAmelCase_ : Dict = [u, v, w] for edge in minimum_weight_edge: if isinstance(__magic_name__ , __magic_name__ ): UpperCAmelCase_ : Dict = edge UpperCAmelCase_ : int = self.m_component[u] UpperCAmelCase_ : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(__magic_name__ , __magic_name__ , __magic_name__ ) print(F"""Added edge [{u} - {v}]\nAdded weight: {w}\n""" ) num_of_components -= 1 UpperCAmelCase_ : Optional[Any] = [-1] * self.m_num_of_nodes print(F"""The total weight of the minimal spanning tree is: {mst_weight}""" ) def lowerCamelCase_ ( ) -> None: '''simple docstring''' pass if __name__ == "__main__": import doctest doctest.testmod()
717
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class __a (lowerCamelCase ): __a : List[Any] = "openai/whisper-base" __a : Optional[Any] = ( "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the " "transcribed text." ) __a : Any = "transcriber" __a : str = WhisperProcessor __a : List[Any] = WhisperForConditionalGeneration __a : int = ["audio"] __a : Optional[Any] = ["text"] def UpperCAmelCase__ ( self : Dict , __magic_name__ : List[str] ) -> Optional[int]: """simple docstring""" return self.pre_processor(__magic_name__ , return_tensors='''pt''' ).input_features def UpperCAmelCase__ ( self : Dict , __magic_name__ : Dict ) -> Tuple: """simple docstring""" return self.model.generate(inputs=__magic_name__ ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Dict ) -> str: """simple docstring""" return self.pre_processor.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ )[0]
644
0
'''simple docstring''' import json import os import unittest from transformers import MgpstrTokenizer from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __a (lowerCamelCase , unittest.TestCase ): __a : Optional[Any] = MgpstrTokenizer __a : str = False __a : Union[str, Any] = {} __a : Any = False def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" super().setUp() # fmt: off UpperCAmelCase_ : Union[str, Any] = ['''[GO]''', '''[s]''', '''0''', '''1''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''a''', '''b''', '''c''', '''d''', '''e''', '''f''', '''g''', '''h''', '''i''', '''j''', '''k''', '''l''', '''m''', '''n''', '''o''', '''p''', '''q''', '''r''', '''s''', '''t''', '''u''', '''v''', '''w''', '''x''', '''y''', '''z'''] # fmt: on UpperCAmelCase_ : Dict = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) UpperCAmelCase_ : Optional[int] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__magic_name__ ) + '''\n''' ) def UpperCAmelCase__ ( self : List[Any] , **__magic_name__ : str ) -> int: """simple docstring""" return MgpstrTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : str = '''tester''' UpperCAmelCase_ : Any = '''tester''' return input_text, output_text @unittest.skip('''MGP-STR always lower cases letters.''' ) def UpperCAmelCase__ ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" pass def UpperCAmelCase__ ( self : Tuple ) -> Dict: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.get_tokenizers(do_lower_case=__magic_name__ ) for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): UpperCAmelCase_ : int = '''[SPECIAL_TOKEN]''' tokenizer.add_special_tokens({'''cls_token''': special_token} ) UpperCAmelCase_ : List[Any] = tokenizer.encode([special_token] , add_special_tokens=__magic_name__ ) self.assertEqual(len(__magic_name__ ) , 1 ) UpperCAmelCase_ : int = tokenizer.decode(__magic_name__ , skip_special_tokens=__magic_name__ ) self.assertTrue(special_token not in decoded ) def UpperCAmelCase__ ( self : Dict ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[int] = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(F"""{tokenizer.__class__.__name__}""" ): UpperCAmelCase_ : Any = self.get_input_output_texts(__magic_name__ ) UpperCAmelCase_ : int = tokenizer.tokenize(__magic_name__ ) UpperCAmelCase_ : Optional[Any] = tokenizer.convert_tokens_to_ids(__magic_name__ ) UpperCAmelCase_ : Any = tokenizer.encode(__magic_name__ , add_special_tokens=__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) UpperCAmelCase_ : int = tokenizer.convert_ids_to_tokens(__magic_name__ ) self.assertNotEqual(len(__magic_name__ ) , 0 ) UpperCAmelCase_ : Dict = tokenizer.decode(__magic_name__ ) self.assertIsInstance(__magic_name__ , __magic_name__ ) self.assertEqual(text_a.replace(''' ''' , '''''' ) , __magic_name__ ) @unittest.skip('''MGP-STR tokenizer only handles one sequence.''' ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" pass @unittest.skip('''inputs cannot be pretokenized in MgpstrTokenizer''' ) def UpperCAmelCase__ ( self : int ) -> List[Any]: """simple docstring""" pass
718
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> int: return abs(SCREAMING_SNAKE_CASE__ ) if a == 0 else greatest_common_divisor(b % a, SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = y, x % y return abs(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( ) -> Optional[int]: try: UpperCAmelCase_ : Optional[Any] = input('''Enter two integers separated by comma (,): ''' ).split(''',''' ) UpperCAmelCase_ : Optional[int] = int(nums[0] ) UpperCAmelCase_ : List[Any] = int(nums[1] ) print( F"""greatest_common_divisor({num_a}, {num_a}) = """ F"""{greatest_common_divisor(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )}""" ) print(F"""By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )}""" ) except (IndexError, UnboundLocalError, ValueError): print('''Wrong input''' ) if __name__ == "__main__": main()
644
0
'''simple docstring''' import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device snake_case_ : List[str] = False class __a (unittest.TestCase ): pass @nightly @require_torch_gpu class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCAmelCase_ : Optional[int] = torch.manual_seed(0 ) UpperCAmelCase_ : Union[str, Any] = pipe.dual_guided( prompt='''first prompt''' , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__magic_name__ ) UpperCAmelCase_ : Optional[int] = VersatileDiffusionPipeline.from_pretrained(__magic_name__ , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Any = generator.manual_seed(0 ) UpperCAmelCase_ : Dict = pipe.dual_guided( prompt='''first prompt''' , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : str = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = '''cyberpunk 2077''' UpperCAmelCase_ : Union[str, Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCAmelCase_ : Tuple = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = pipe.dual_guided( prompt=__magic_name__ , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images UpperCAmelCase_ : List[str] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Union[str, Any] = np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 UpperCAmelCase_ : Tuple = '''A painting of a squirrel eating a burger ''' UpperCAmelCase_ : Optional[int] = torch.manual_seed(0 ) UpperCAmelCase_ : List[Any] = pipe.text_to_image( prompt=__magic_name__ , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images UpperCAmelCase_ : Tuple = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Any = np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 UpperCAmelCase_ : Tuple = pipe.image_variation(__magic_name__ , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Optional[Any] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : List[str] = np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
719
'''simple docstring''' import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __a : def __init__( self : int , __magic_name__ : Optional[Any] , __magic_name__ : Any=13 , __magic_name__ : Any=7 , __magic_name__ : Union[str, Any]=True , __magic_name__ : Union[str, Any]=True , __magic_name__ : str=True , __magic_name__ : Optional[int]=True , __magic_name__ : List[Any]=99 , __magic_name__ : int=24 , __magic_name__ : Optional[int]=2 , __magic_name__ : Tuple=6 , __magic_name__ : Union[str, Any]=37 , __magic_name__ : Optional[Any]="gelu" , __magic_name__ : Any=0.1 , __magic_name__ : str=0.1 , __magic_name__ : Tuple=5_12 , __magic_name__ : Union[str, Any]=16 , __magic_name__ : Tuple=2 , __magic_name__ : Tuple=0.0_2 , __magic_name__ : Optional[Any]=3 , __magic_name__ : Optional[int]=None , __magic_name__ : Any=10_00 , ) -> str: """simple docstring""" UpperCAmelCase_ : Tuple = parent UpperCAmelCase_ : Optional[int] = batch_size UpperCAmelCase_ : List[str] = seq_length UpperCAmelCase_ : Dict = is_training UpperCAmelCase_ : List[str] = use_input_mask UpperCAmelCase_ : Any = use_token_type_ids UpperCAmelCase_ : Any = use_labels UpperCAmelCase_ : Any = vocab_size UpperCAmelCase_ : Dict = hidden_size UpperCAmelCase_ : Tuple = num_hidden_layers UpperCAmelCase_ : Tuple = num_attention_heads UpperCAmelCase_ : int = intermediate_size UpperCAmelCase_ : Union[str, Any] = hidden_act UpperCAmelCase_ : Optional[int] = hidden_dropout_prob UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase_ : Union[str, Any] = max_position_embeddings UpperCAmelCase_ : int = type_vocab_size UpperCAmelCase_ : List[Any] = type_sequence_label_size UpperCAmelCase_ : int = initializer_range UpperCAmelCase_ : Dict = num_labels UpperCAmelCase_ : List[str] = scope UpperCAmelCase_ : List[str] = range_bbox def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCAmelCase_ : List[str] = bbox[i, j, 3] UpperCAmelCase_ : Dict = bbox[i, j, 1] UpperCAmelCase_ : Optional[Any] = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCAmelCase_ : List[str] = bbox[i, j, 2] UpperCAmelCase_ : Tuple = bbox[i, j, 0] UpperCAmelCase_ : Union[str, Any] = t UpperCAmelCase_ : int = None if self.use_input_mask: UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCAmelCase_ : Optional[int] = None if self.use_token_type_ids: UpperCAmelCase_ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Dict = None UpperCAmelCase_ : Tuple = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : int = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : int , ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = LiltModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Optional[Any] = model(__magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : List[Any] = model(__magic_name__ , bbox=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : Optional[int] = model(__magic_name__ , bbox=__magic_name__ ) 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 : int , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[int] , __magic_name__ : List[Any] , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Any = self.num_labels UpperCAmelCase_ : List[Any] = LiltForTokenClassification(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : List[Any] = model( __magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : int , __magic_name__ : Tuple , __magic_name__ : Any , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : str = LiltForQuestionAnswering(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Optional[Any] = model( __magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , start_positions=__magic_name__ , end_positions=__magic_name__ , ) 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 : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : Optional[int] = config_and_inputs UpperCAmelCase_ : Tuple = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class __a (lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : Tuple = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __a : Any = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __a : Union[str, Any] = False __a : int = False def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : int ) -> str: """simple docstring""" return True def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = LiltModelTester(self ) UpperCAmelCase_ : List[Any] = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ : Tuple = type self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @slow def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Optional[int] = LiltModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) @require_torch @slow class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" UpperCAmelCase_ : str = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''' ).to(__magic_name__ ) UpperCAmelCase_ : Any = torch.tensor([[1, 2]] , device=__magic_name__ ) UpperCAmelCase_ : int = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=__magic_name__ ) # forward pass with torch.no_grad(): UpperCAmelCase_ : Optional[int] = model(input_ids=__magic_name__ , bbox=__magic_name__ ) UpperCAmelCase_ : int = torch.Size([1, 2, 7_68] ) UpperCAmelCase_ : List[str] = torch.tensor( [[-0.0_6_5_3, 0.0_9_5_0, -0.0_0_6_1], [-0.0_5_4_5, 0.0_9_2_6, -0.0_3_2_4]] , device=__magic_name__ , ) self.assertTrue(outputs.last_hidden_state.shape , __magic_name__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , __magic_name__ , atol=1E-3 ) )
644
0
from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : Union[str, Any]=1E-12 ) -> Optional[Any]: UpperCAmelCase_ : Any = jnp.divide(emb_a.T, jnp.clip(jnp.linalg.norm(SCREAMING_SNAKE_CASE__, axis=1 ), a_min=SCREAMING_SNAKE_CASE__ ) ).T UpperCAmelCase_ : Optional[int] = jnp.divide(emb_a.T, jnp.clip(jnp.linalg.norm(SCREAMING_SNAKE_CASE__, axis=1 ), a_min=SCREAMING_SNAKE_CASE__ ) ).T return jnp.matmul(SCREAMING_SNAKE_CASE__, norm_emb_a.T ) class __a (nn.Module ): __a : CLIPConfig __a : jnp.dtype = jnp.floataa def UpperCAmelCase__ ( self : Union[str, Any] ) -> Any: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = FlaxCLIPVisionModule(self.config.vision_config ) UpperCAmelCase_ : Tuple = nn.Dense(self.config.projection_dim , use_bias=__magic_name__ , dtype=self.dtype ) UpperCAmelCase_ : Optional[Any] = self.param('''concept_embeds''' , jax.nn.initializers.ones , (17, self.config.projection_dim) ) UpperCAmelCase_ : Union[str, Any] = self.param( '''special_care_embeds''' , jax.nn.initializers.ones , (3, self.config.projection_dim) ) UpperCAmelCase_ : Tuple = self.param('''concept_embeds_weights''' , jax.nn.initializers.ones , (17,) ) UpperCAmelCase_ : Tuple = self.param('''special_care_embeds_weights''' , jax.nn.initializers.ones , (3,) ) def __call__( self : Any , __magic_name__ : Tuple ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Dict = self.vision_model(__magic_name__ )[1] UpperCAmelCase_ : Optional[Any] = self.visual_projection(__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = jax_cosine_distance(__magic_name__ , self.special_care_embeds ) UpperCAmelCase_ : Optional[int] = jax_cosine_distance(__magic_name__ , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs UpperCAmelCase_ : Any = 0.0 UpperCAmelCase_ : Any = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment UpperCAmelCase_ : List[Any] = jnp.round(__magic_name__ , 3 ) UpperCAmelCase_ : Optional[Any] = jnp.any(special_scores > 0 , axis=1 , keepdims=__magic_name__ ) # Use a lower threshold if an image has any special care concept UpperCAmelCase_ : Union[str, Any] = is_special_care * 0.0_1 UpperCAmelCase_ : str = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment UpperCAmelCase_ : Optional[Any] = jnp.round(__magic_name__ , 3 ) UpperCAmelCase_ : Optional[Any] = jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class __a (lowerCamelCase ): __a : str = CLIPConfig __a : Optional[Any] = "clip_input" __a : List[str] = FlaxStableDiffusionSafetyCheckerModule def __init__( self : Optional[Any] , __magic_name__ : CLIPConfig , __magic_name__ : Optional[Tuple] = None , __magic_name__ : int = 0 , __magic_name__ : jnp.dtype = jnp.floataa , __magic_name__ : bool = True , **__magic_name__ : int , ) -> Any: """simple docstring""" if input_shape is None: UpperCAmelCase_ : List[str] = (1, 2_24, 2_24, 3) UpperCAmelCase_ : Dict = self.module_class(config=__magic_name__ , dtype=__magic_name__ , **__magic_name__ ) super().__init__(__magic_name__ , __magic_name__ , input_shape=__magic_name__ , seed=__magic_name__ , dtype=__magic_name__ , _do_init=_do_init ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : jax.random.KeyArray , __magic_name__ : Tuple , __magic_name__ : FrozenDict = None ) -> FrozenDict: """simple docstring""" UpperCAmelCase_ : Dict = jax.random.normal(__magic_name__ , __magic_name__ ) UpperCAmelCase_ : str = jax.random.split(__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = {'''params''': params_rng, '''dropout''': dropout_rng} UpperCAmelCase_ : Optional[Any] = self.module.init(__magic_name__ , __magic_name__ )['''params'''] return random_params def __call__( self : Optional[Any] , __magic_name__ : Any , __magic_name__ : dict = None , ) -> int: """simple docstring""" UpperCAmelCase_ : Optional[Any] = jnp.transpose(__magic_name__ , (0, 2, 3, 1) ) return self.module.apply( {'''params''': params or self.params} , jnp.array(__magic_name__ , dtype=jnp.floataa ) , rngs={} , )
720
'''simple docstring''' import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging snake_case_ : str = logging.get_logger(__name__) snake_case_ : int = "▁" snake_case_ : str = {"vocab_file": "vocab.txt", "sentencepiece_model_ckpt": "sentencepiece.bpe.model"} snake_case_ : int = { "sentencepiece_model_file": "sentencepiece.bpe.model", "vocab_file": "vocab.txt", } snake_case_ : Optional[Any] = { "vocab_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", }, "sentencepiece_model_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", }, } snake_case_ : Dict = { "ernie-m-base": 5_14, "ernie-m-large": 5_14, } snake_case_ : Any = { "ernie-m-base": {"do_lower_case": False}, "ernie-m-large": {"do_lower_case": False}, } class __a (lowerCamelCase ): __a : List[str] = ["input_ids"] __a : Union[str, Any] = VOCAB_FILES_NAMES __a : Tuple = PRETRAINED_INIT_CONFIGURATION __a : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a : Optional[int] = PRETRAINED_VOCAB_FILES_MAP __a : Union[str, Any] = RESOURCE_FILES_NAMES def __init__( self : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : int=None , __magic_name__ : str=False , __magic_name__ : int="utf8" , __magic_name__ : Optional[int]="[UNK]" , __magic_name__ : Dict="[SEP]" , __magic_name__ : List[Any]="[PAD]" , __magic_name__ : str="[CLS]" , __magic_name__ : Optional[int]="[MASK]" , __magic_name__ : Optional[Dict[str, Any]] = None , **__magic_name__ : Union[str, Any] , ) -> None: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. UpperCAmelCase_ : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , pad_token=__magic_name__ , cls_token=__magic_name__ , mask_token=__magic_name__ , vocab_file=__magic_name__ , encoding=__magic_name__ , sp_model_kwargs=self.sp_model_kwargs , **__magic_name__ , ) UpperCAmelCase_ : Optional[Any] = do_lower_case UpperCAmelCase_ : List[str] = sentencepiece_model_ckpt UpperCAmelCase_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__magic_name__ ) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: UpperCAmelCase_ : List[Any] = self.load_vocab(filepath=__magic_name__ ) else: UpperCAmelCase_ : str = {self.sp_model.id_to_piece(__magic_name__ ): id for id in range(self.sp_model.get_piece_size() )} UpperCAmelCase_ : int = {v: k for k, v in self.vocab.items()} def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Any ) -> Any: """simple docstring""" if text is None: return None UpperCAmelCase_ : str = self.tokenize(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ : str = '''''', [] for i, ch in enumerate(__magic_name__ ): if ch in self.SP_CHAR_MAPPING: UpperCAmelCase_ : Optional[int] = self.SP_CHAR_MAPPING.get(__magic_name__ ) else: UpperCAmelCase_ : Union[str, Any] = unicodedata.normalize('''NFKC''' , __magic_name__ ) if self.is_whitespace(__magic_name__ ): continue normalized_text += ch char_mapping.extend([i] * len(__magic_name__ ) ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = normalized_text, [], 0 if self.do_lower_case: UpperCAmelCase_ : Optional[int] = text.lower() for token in split_tokens: if token[:1] == "▁": UpperCAmelCase_ : Tuple = token[1:] UpperCAmelCase_ : int = text[offset:].index(__magic_name__ ) + offset UpperCAmelCase_ : Optional[int] = start + len(__magic_name__ ) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) ) UpperCAmelCase_ : int = end return token_mapping @property def UpperCAmelCase__ ( self : Any ) -> Any: """simple docstring""" return len(self.vocab ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def __getstate__( self : str ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.__dict__.copy() UpperCAmelCase_ : Optional[Any] = None return state def __setstate__( self : str , __magic_name__ : Any ) -> Dict: """simple docstring""" UpperCAmelCase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): UpperCAmelCase_ : int = {} UpperCAmelCase_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.sentencepiece_model_ckpt ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Any ) -> List[str]: """simple docstring""" return "".join((self.SP_CHAR_MAPPING.get(__magic_name__ , __magic_name__ ) for c in text) ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Tuple , __magic_name__ : Any=False , __magic_name__ : List[str]=64 , __magic_name__ : List[str]=0.1 ) -> List[str]: """simple docstring""" if self.sp_model_kwargs.get('''enable_sampling''' ) is True: UpperCAmelCase_ : Dict = True if self.sp_model_kwargs.get('''alpha''' ) is not None: UpperCAmelCase_ : Union[str, Any] = self.sp_model_kwargs.get('''alpha''' ) if self.sp_model_kwargs.get('''nbest_size''' ) is not None: UpperCAmelCase_ : Any = self.sp_model_kwargs.get('''nbest_size''' ) if not enable_sampling: UpperCAmelCase_ : Dict = self.sp_model.EncodeAsPieces(__magic_name__ ) else: UpperCAmelCase_ : Dict = self.sp_model.SampleEncodeAsPieces(__magic_name__ , __magic_name__ , __magic_name__ ) UpperCAmelCase_ : List[Any] = [] for pi, piece in enumerate(__magic_name__ ): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(__magic_name__ ) and pi != 0: new_pieces.append(__magic_name__ ) continue else: continue UpperCAmelCase_ : List[str] = 0 for i, chunk in enumerate(__magic_name__ ): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(__magic_name__ ) or self.is_punct(__magic_name__ ): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) new_pieces.append(__magic_name__ ) UpperCAmelCase_ : List[Any] = i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) UpperCAmelCase_ : List[str] = i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) UpperCAmelCase_ : str = i if len(__magic_name__ ) > lst_i: new_pieces.append(piece[lst_i:] ) return new_pieces def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Optional[int] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = ''''''.join(__magic_name__ ).replace(__magic_name__ , ''' ''' ).strip() return out_string def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, Any] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : str = self.convert_ids_to_tokens(__magic_name__ ) UpperCAmelCase_ : Optional[Any] = ''''''.join(__magic_name__ ).replace(__magic_name__ , ''' ''' ).strip() return out_string def UpperCAmelCase__ ( self : str , __magic_name__ : Optional[Any] ) -> List[Any]: """simple docstring""" return self.vocab.get(__magic_name__ , self.vocab.get(self.unk_token ) ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.reverse_vocab.get(__magic_name__ , self.unk_token ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Any , __magic_name__ : Union[str, Any]=None ) -> Any: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase_ : Union[str, Any] = [self.cls_token_id] UpperCAmelCase_ : List[Any] = [self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def UpperCAmelCase__ ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : List[str]=None ) -> int: """simple docstring""" if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def UpperCAmelCase__ ( self : Dict , __magic_name__ : Optional[Any] , __magic_name__ : List[str]=None , __magic_name__ : Optional[Any]=False ) -> Optional[int]: """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__magic_name__ )) + [1, 1] + ([0] * len(__magic_name__ )) + [1] return [1] + ([0] * len(__magic_name__ )) + [1] def UpperCAmelCase__ ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method if token_ids_a is None: # [CLS] X [SEP] return (len(__magic_name__ ) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(__magic_name__ ) + 1) + [1] * (len(__magic_name__ ) + 3) def UpperCAmelCase__ ( self : Dict , __magic_name__ : str ) -> Tuple: """simple docstring""" if "\u4e00" <= char <= "\u9fff": return True return False def UpperCAmelCase__ ( self : int , __magic_name__ : Optional[int] ) -> str: """simple docstring""" if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def UpperCAmelCase__ ( self : int , __magic_name__ : Optional[Any] ) -> Dict: """simple docstring""" if char in ",;:.?!~,;:。?!《》【】": return True return False def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Any ) -> Union[str, Any]: """simple docstring""" if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(__magic_name__ ) == 1: UpperCAmelCase_ : Optional[Any] = unicodedata.category(__magic_name__ ) if cat == "Zs": return True return False def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : Tuple ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[Any] = {} with io.open(__magic_name__ , '''r''' , encoding='''utf-8''' ) as f: for index, line in enumerate(__magic_name__ ): UpperCAmelCase_ : List[Any] = line.rstrip('''\n''' ) UpperCAmelCase_ : Dict = int(__magic_name__ ) return token_to_idx def UpperCAmelCase__ ( self : Dict , __magic_name__ : str , __magic_name__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = 0 if os.path.isdir(__magic_name__ ): UpperCAmelCase_ : Any = os.path.join( __magic_name__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) else: UpperCAmelCase_ : List[str] = (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory with open(__magic_name__ , '''w''' , encoding='''utf-8''' ) as writer: for token, token_index in sorted(self.vocab.items() , key=lambda __magic_name__ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ''' Please check that the vocabulary is not corrupted!''' ) UpperCAmelCase_ : Dict = token_index writer.write(token + '''\n''' ) index += 1 UpperCAmelCase_ : Union[str, Any] = os.path.join(__magic_name__ , '''sentencepiece.bpe.model''' ) with open(__magic_name__ , '''wb''' ) as fi: UpperCAmelCase_ : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (vocab_file,)
644
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING snake_case_ : int = logging.get_logger(__name__) snake_case_ : str = { "SenseTime/deformable-detr": "https://huggingface.co/sensetime/deformable-detr/resolve/main/config.json", # See all Deformable DETR models at https://huggingface.co/models?filter=deformable-detr } class __a (lowerCamelCase ): __a : Optional[Any] = "deformable_detr" __a : Optional[Any] = { "hidden_size": "d_model", "num_attention_heads": "encoder_attention_heads", } def __init__( self : List[Any] , __magic_name__ : str=True , __magic_name__ : Tuple=None , __magic_name__ : Optional[Any]=3 , __magic_name__ : int=3_00 , __magic_name__ : str=10_24 , __magic_name__ : List[Any]=6 , __magic_name__ : Dict=10_24 , __magic_name__ : Optional[int]=8 , __magic_name__ : List[Any]=6 , __magic_name__ : Dict=10_24 , __magic_name__ : int=8 , __magic_name__ : Tuple=0.0 , __magic_name__ : Tuple=True , __magic_name__ : Tuple="relu" , __magic_name__ : Union[str, Any]=2_56 , __magic_name__ : Dict=0.1 , __magic_name__ : Optional[int]=0.0 , __magic_name__ : Optional[int]=0.0 , __magic_name__ : int=0.0_2 , __magic_name__ : Dict=1.0 , __magic_name__ : Dict=True , __magic_name__ : str=False , __magic_name__ : str="sine" , __magic_name__ : List[Any]="resnet50" , __magic_name__ : List[str]=True , __magic_name__ : Optional[int]=False , __magic_name__ : List[str]=4 , __magic_name__ : List[Any]=4 , __magic_name__ : Optional[Any]=4 , __magic_name__ : List[str]=False , __magic_name__ : Tuple=3_00 , __magic_name__ : List[str]=False , __magic_name__ : Optional[int]=1 , __magic_name__ : int=5 , __magic_name__ : Union[str, Any]=2 , __magic_name__ : Optional[int]=1 , __magic_name__ : Tuple=1 , __magic_name__ : Optional[Any]=5 , __magic_name__ : Optional[int]=2 , __magic_name__ : Optional[Any]=0.1 , __magic_name__ : Dict=0.2_5 , __magic_name__ : Tuple=False , **__magic_name__ : List[Any] , ) -> Tuple: """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.''' ) UpperCAmelCase_ : Tuple = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(__magic_name__ , __magic_name__ ): UpperCAmelCase_ : Tuple = backbone_config.get('''model_type''' ) UpperCAmelCase_ : Optional[int] = CONFIG_MAPPING[backbone_model_type] UpperCAmelCase_ : Any = config_class.from_dict(__magic_name__ ) UpperCAmelCase_ : Dict = use_timm_backbone UpperCAmelCase_ : List[str] = backbone_config UpperCAmelCase_ : Union[str, Any] = num_channels UpperCAmelCase_ : int = num_queries UpperCAmelCase_ : Optional[Any] = max_position_embeddings UpperCAmelCase_ : Dict = d_model UpperCAmelCase_ : Tuple = encoder_ffn_dim UpperCAmelCase_ : List[Any] = encoder_layers UpperCAmelCase_ : Any = encoder_attention_heads UpperCAmelCase_ : List[Any] = decoder_ffn_dim UpperCAmelCase_ : Optional[Any] = decoder_layers UpperCAmelCase_ : Any = decoder_attention_heads UpperCAmelCase_ : Optional[int] = dropout UpperCAmelCase_ : Union[str, Any] = attention_dropout UpperCAmelCase_ : Tuple = activation_dropout UpperCAmelCase_ : Optional[int] = activation_function UpperCAmelCase_ : Dict = init_std UpperCAmelCase_ : int = init_xavier_std UpperCAmelCase_ : List[str] = encoder_layerdrop UpperCAmelCase_ : List[Any] = auxiliary_loss UpperCAmelCase_ : Optional[int] = position_embedding_type UpperCAmelCase_ : Union[str, Any] = backbone UpperCAmelCase_ : Optional[Any] = use_pretrained_backbone UpperCAmelCase_ : Dict = dilation # deformable attributes UpperCAmelCase_ : Optional[int] = num_feature_levels UpperCAmelCase_ : str = encoder_n_points UpperCAmelCase_ : Tuple = decoder_n_points UpperCAmelCase_ : Dict = two_stage UpperCAmelCase_ : Optional[int] = two_stage_num_proposals UpperCAmelCase_ : Dict = with_box_refine if two_stage is True and with_box_refine is False: raise ValueError('''If two_stage is True, with_box_refine must be True.''' ) # Hungarian matcher UpperCAmelCase_ : Union[str, Any] = class_cost UpperCAmelCase_ : List[str] = bbox_cost UpperCAmelCase_ : Dict = giou_cost # Loss coefficients UpperCAmelCase_ : Tuple = mask_loss_coefficient UpperCAmelCase_ : int = dice_loss_coefficient UpperCAmelCase_ : Optional[Any] = bbox_loss_coefficient UpperCAmelCase_ : Any = giou_loss_coefficient UpperCAmelCase_ : List[Any] = eos_coefficient UpperCAmelCase_ : Dict = focal_alpha UpperCAmelCase_ : int = disable_custom_kernels super().__init__(is_encoder_decoder=__magic_name__ , **__magic_name__ ) @property def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" return self.encoder_attention_heads @property def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" return self.d_model def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" UpperCAmelCase_ : int = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: UpperCAmelCase_ : str = self.backbone_config.to_dict() UpperCAmelCase_ : List[Any] = self.__class__.model_type return output
721
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) UpperCAmelCase_ : Union[str, Any] = len(bin(SCREAMING_SNAKE_CASE__ )[3:] ) UpperCAmelCase_ : Union[str, Any] = bin(abs(SCREAMING_SNAKE_CASE__ ) - (1 << binary_number_length) )[3:] UpperCAmelCase_ : Optional[Any] = ( ( '''1''' + '''0''' * (binary_number_length - len(SCREAMING_SNAKE_CASE__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
644
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case_ : Dict = { "configuration_swinv2": ["SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Swinv2Config"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : str = [ "SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST", "Swinv2ForImageClassification", "Swinv2ForMaskedImageModeling", "Swinv2Model", "Swinv2PreTrainedModel", ] if TYPE_CHECKING: from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swinva import ( SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST, SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel, SwinvaPreTrainedModel, ) else: import sys snake_case_ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
700
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. UpperCAmelCase_ : List[str] = [[1, 2, 4], [1, 2, 3, 4]] UpperCAmelCase_ : List[str] = DisjunctiveConstraint(__magic_name__ ) self.assertTrue(isinstance(dc.token_ids , __magic_name__ ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). UpperCAmelCase_ : Tuple = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(__magic_name__ ) # fails here def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] UpperCAmelCase_ : List[str] = DisjunctiveConstraint(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) UpperCAmelCase_ : Dict = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : str = dc.update(2 ) UpperCAmelCase_ : Optional[Any] = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(3 ) UpperCAmelCase_ : Dict = stepped is True and completed is True and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase__ ( self : int ) -> Dict: """simple docstring""" UpperCAmelCase_ : Any = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] UpperCAmelCase_ : Tuple = DisjunctiveConstraint(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
644
0
'''simple docstring''' from random import shuffle import tensorflow as tf from numpy import array def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[Any], SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: UpperCAmelCase_ : List[str] = int(SCREAMING_SNAKE_CASE__ ) assert noofclusters < len(SCREAMING_SNAKE_CASE__ ) # Find out the dimensionality UpperCAmelCase_ : Tuple = len(vectors[0] ) # Will help select random centroids from among the available vectors UpperCAmelCase_ : Optional[Any] = list(range(len(SCREAMING_SNAKE_CASE__ ) ) ) shuffle(SCREAMING_SNAKE_CASE__ ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. UpperCAmelCase_ : Union[str, Any] = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION UpperCAmelCase_ : Union[str, Any] = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points UpperCAmelCase_ : List[str] = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(SCREAMING_SNAKE_CASE__ ) ] ##These nodes will assign the centroid Variables the appropriate ##values UpperCAmelCase_ : Any = tf.placeholder('''float64''', [dim] ) UpperCAmelCase_ : List[Any] = [] for centroid in centroids: cent_assigns.append(tf.assign(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) UpperCAmelCase_ : Union[str, Any] = [tf.Variable(0 ) for i in range(len(SCREAMING_SNAKE_CASE__ ) )] ##These nodes will assign an assignment Variable the appropriate ##value UpperCAmelCase_ : Any = tf.placeholder('''int32''' ) UpperCAmelCase_ : Optional[Any] = [] for assignment in assignments: cluster_assigns.append(tf.assign(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input UpperCAmelCase_ : Tuple = tf.placeholder('''float''', [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors UpperCAmelCase_ : Dict = tf.reduce_mean(SCREAMING_SNAKE_CASE__, 0 ) ##Node for computing Euclidean distances # Placeholders for input UpperCAmelCase_ : int = tf.placeholder('''float''', [dim] ) UpperCAmelCase_ : Optional[Any] = tf.placeholder('''float''', [dim] ) UpperCAmelCase_ : Optional[int] = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input UpperCAmelCase_ : Dict = tf.placeholder('''float''', [noofclusters] ) UpperCAmelCase_ : Dict = tf.argmin(SCREAMING_SNAKE_CASE__, 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. UpperCAmelCase_ : str = tf.initialize_all_variables() # Initialize all variables sess.run(SCREAMING_SNAKE_CASE__ ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. UpperCAmelCase_ : Optional[Any] = 100 for _ in range(SCREAMING_SNAKE_CASE__ ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ : Dict = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. UpperCAmelCase_ : List[Any] = [ sess.run(SCREAMING_SNAKE_CASE__, feed_dict={va: vect, va: sess.run(SCREAMING_SNAKE_CASE__ )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input UpperCAmelCase_ : List[Any] = sess.run( SCREAMING_SNAKE_CASE__, feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n], feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(SCREAMING_SNAKE_CASE__ ): # Collect all the vectors assigned to this cluster UpperCAmelCase_ : Dict = [ vectors[i] for i in range(len(SCREAMING_SNAKE_CASE__ ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location UpperCAmelCase_ : Dict = sess.run( SCREAMING_SNAKE_CASE__, feed_dict={mean_input: array(SCREAMING_SNAKE_CASE__ )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n], feed_dict={centroid_value: new_location} ) # Return centroids and assignments UpperCAmelCase_ : Union[str, Any] = sess.run(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[int] = sess.run(SCREAMING_SNAKE_CASE__ ) return centroids, assignments
701
'''simple docstring''' import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": snake_case_ : List[Any] = pd.read_csv("sample_data.csv", header=None) snake_case_ : Optional[Any] = df.shape[:1][0] # If you're using some other dataset input the target column snake_case_ : Any = df.iloc[:, 1:2] snake_case_ : str = actual_data.values.reshape(len_data, 1) snake_case_ : Optional[Any] = MinMaxScaler().fit_transform(actual_data) snake_case_ : List[str] = 10 snake_case_ : Any = 5 snake_case_ : Any = 20 snake_case_ : Tuple = len_data - periods * look_back snake_case_ : str = actual_data[:division] snake_case_ : Optional[int] = actual_data[division - look_back :] snake_case_ ,snake_case_ : Any = [], [] snake_case_ ,snake_case_ : Union[str, Any] = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) snake_case_ : Any = np.array(train_x) snake_case_ : Optional[Any] = np.array(test_x) snake_case_ : Optional[Any] = np.array([list(i.ravel()) for i in train_y]) snake_case_ : List[str] = np.array([list(i.ravel()) for i in test_y]) snake_case_ : List[Any] = Sequential() model.add(LSTM(1_28, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(1_28, 1))) model.add(Dense(forward_days)) model.compile(loss="mean_squared_error", optimizer="adam") snake_case_ : Dict = model.fit( x_train, y_train, epochs=1_50, verbose=1, shuffle=True, batch_size=4 ) snake_case_ : Optional[Any] = model.predict(x_test)
644
0
'''simple docstring''' import re from ..models.auto import AutoProcessor from ..models.vision_encoder_decoder import VisionEncoderDecoderModel from ..utils import is_vision_available from .base import PipelineTool if is_vision_available(): from PIL import Image class __a (lowerCamelCase ): __a : Dict = "naver-clova-ix/donut-base-finetuned-docvqa" __a : Optional[int] = ( "This is a tool that answers a question about an document (pdf). It takes an input named `document` which " "should be the document containing the information, as well as a `question` that is the question about the " "document. It returns a text that contains the answer to the question." ) __a : int = "document_qa" __a : Optional[Any] = AutoProcessor __a : Optional[Any] = VisionEncoderDecoderModel __a : Any = ["image", "text"] __a : Union[str, Any] = ["text"] def __init__( self : int , *__magic_name__ : Union[str, Any] , **__magic_name__ : List[Any] ) -> List[Any]: """simple docstring""" if not is_vision_available(): raise ValueError('''Pillow must be installed to use the DocumentQuestionAnsweringTool.''' ) super().__init__(*__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : "Image" , __magic_name__ : str ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = '''<s_docvqa><s_question>{user_input}</s_question><s_answer>''' UpperCAmelCase_ : Any = task_prompt.replace('''{user_input}''' , __magic_name__ ) UpperCAmelCase_ : int = self.pre_processor.tokenizer( __magic_name__ , add_special_tokens=__magic_name__ , return_tensors='''pt''' ).input_ids UpperCAmelCase_ : int = self.pre_processor(__magic_name__ , return_tensors='''pt''' ).pixel_values return {"decoder_input_ids": decoder_input_ids, "pixel_values": pixel_values} def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Optional[Any] ) -> List[str]: """simple docstring""" return self.model.generate( inputs['''pixel_values'''].to(self.device ) , decoder_input_ids=inputs['''decoder_input_ids'''].to(self.device ) , max_length=self.model.decoder.config.max_position_embeddings , early_stopping=__magic_name__ , pad_token_id=self.pre_processor.tokenizer.pad_token_id , eos_token_id=self.pre_processor.tokenizer.eos_token_id , use_cache=__magic_name__ , num_beams=1 , bad_words_ids=[[self.pre_processor.tokenizer.unk_token_id]] , return_dict_in_generate=__magic_name__ , ).sequences def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Tuple ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.pre_processor.batch_decode(__magic_name__ )[0] UpperCAmelCase_ : Dict = sequence.replace(self.pre_processor.tokenizer.eos_token , '''''' ) UpperCAmelCase_ : Optional[int] = sequence.replace(self.pre_processor.tokenizer.pad_token , '''''' ) UpperCAmelCase_ : Dict = re.sub(R'''<.*?>''' , '''''' , __magic_name__ , count=1 ).strip() # remove first task start token UpperCAmelCase_ : List[str] = self.pre_processor.tokenajson(__magic_name__ ) return sequence["answer"]
702
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker snake_case_ : Union[str, Any] = "CompVis/stable-diffusion-v1-1" snake_case_ : Dict = "CompVis/stable-diffusion-v1-2" snake_case_ : Any = "CompVis/stable-diffusion-v1-3" snake_case_ : str = "CompVis/stable-diffusion-v1-4" class __a (lowerCamelCase ): def __init__( self : Any , __magic_name__ : AutoencoderKL , __magic_name__ : CLIPTextModel , __magic_name__ : CLIPTokenizer , __magic_name__ : UNetaDConditionModel , __magic_name__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __magic_name__ : StableDiffusionSafetyChecker , __magic_name__ : CLIPImageProcessor , __magic_name__ : bool = True , ) -> str: """simple docstring""" super()._init_() UpperCAmelCase_ : Any = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Dict = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : List[Any] = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Tuple = StableDiffusionPipeline( vae=__magic_name__ , text_encoder=__magic_name__ , tokenizer=__magic_name__ , unet=__magic_name__ , scheduler=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , requires_safety_checker=__magic_name__ , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def UpperCAmelCase__ ( self : Tuple ) -> Dict[str, Any]: """simple docstring""" return {k: getattr(self , __magic_name__ ) for k in self.config.keys() if not k.startswith('''_''' )} def UpperCAmelCase__ ( self : Dict , __magic_name__ : Optional[Union[str, int]] = "auto" ) -> int: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ : List[str] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" self.enable_attention_slicing(__magic_name__ ) @torch.no_grad() def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Tuple , ) -> Optional[int]: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Any , ) -> Any: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Dict , ) -> List[str]: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : int , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Optional[int] , ) -> str: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Optional[int] , ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : int = '''cuda''' if torch.cuda.is_available() else '''cpu''' self.to(__magic_name__ ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` must be divisible by 8 but are {height} and {width}.""" ) # Get first result from Stable Diffusion Checkpoint v1.1 UpperCAmelCase_ : Optional[int] = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCAmelCase_ : int = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCAmelCase_ : str = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCAmelCase_ : str = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
644
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case_ : List[Any] = {"configuration_opt": ["OPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "OPTConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : str = [ "OPT_PRETRAINED_MODEL_ARCHIVE_LIST", "OPTForCausalLM", "OPTModel", "OPTPreTrainedModel", "OPTForSequenceClassification", "OPTForQuestionAnswering", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Optional[Any] = ["TFOPTForCausalLM", "TFOPTModel", "TFOPTPreTrainedModel"] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Dict = [ "FlaxOPTForCausalLM", "FlaxOPTModel", "FlaxOPTPreTrainedModel", ] if TYPE_CHECKING: from .configuration_opt import OPT_PRETRAINED_CONFIG_ARCHIVE_MAP, OPTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_opt import ( OPT_PRETRAINED_MODEL_ARCHIVE_LIST, OPTForCausalLM, OPTForQuestionAnswering, OPTForSequenceClassification, OPTModel, OPTPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_opt import TFOPTForCausalLM, TFOPTModel, TFOPTPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_opt import FlaxOPTForCausalLM, FlaxOPTModel, FlaxOPTPreTrainedModel else: import sys snake_case_ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
703
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler snake_case_ : Optional[int] = 16 snake_case_ : Tuple = 32 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Accelerator, SCREAMING_SNAKE_CASE__ : int = 16, SCREAMING_SNAKE_CASE__ : str = "bert-base-cased" ) -> Dict: UpperCAmelCase_ : Dict = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = load_dataset('''glue''', '''mrpc''' ) def tokenize_function(SCREAMING_SNAKE_CASE__ : Optional[int] ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase_ : Union[str, Any] = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=SCREAMING_SNAKE_CASE__, max_length=SCREAMING_SNAKE_CASE__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase_ : Tuple = datasets.map( SCREAMING_SNAKE_CASE__, batched=SCREAMING_SNAKE_CASE__, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], load_from_cache_file=SCREAMING_SNAKE_CASE__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase_ : Optional[Any] = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(SCREAMING_SNAKE_CASE__ : str ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(SCREAMING_SNAKE_CASE__, padding='''max_length''', max_length=128, return_tensors='''pt''' ) return tokenizer.pad(SCREAMING_SNAKE_CASE__, padding='''longest''', return_tensors='''pt''' ) # Instantiate dataloaders. UpperCAmelCase_ : str = DataLoader( tokenized_datasets['''train'''], shuffle=SCREAMING_SNAKE_CASE__, collate_fn=SCREAMING_SNAKE_CASE__, batch_size=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = DataLoader( tokenized_datasets['''validation'''], shuffle=SCREAMING_SNAKE_CASE__, collate_fn=SCREAMING_SNAKE_CASE__, batch_size=SCREAMING_SNAKE_CASE__ ) return train_dataloader, eval_dataloader def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Optional[int], SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Any ) -> Any: model.eval() UpperCAmelCase_ : List[str] = 0 for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase_ : Dict = model(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : str = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCAmelCase_ , UpperCAmelCase_ : List[str] = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(SCREAMING_SNAKE_CASE__ ) - 1: UpperCAmelCase_ : Tuple = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCAmelCase_ : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=SCREAMING_SNAKE_CASE__, references=SCREAMING_SNAKE_CASE__, ) UpperCAmelCase_ : List[str] = metric.compute() return eval_metric["accuracy"] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : int ) -> Tuple: # Initialize accelerator UpperCAmelCase_ : Union[str, Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase_ : int = config['''lr'''] UpperCAmelCase_ : Optional[int] = int(config['''num_epochs'''] ) UpperCAmelCase_ : Optional[int] = int(config['''seed'''] ) UpperCAmelCase_ : List[str] = int(config['''batch_size'''] ) UpperCAmelCase_ : Optional[int] = args.model_name_or_path set_seed(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = get_dataloaders(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase_ : List[Any] = AutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__, return_dict=SCREAMING_SNAKE_CASE__ ) # Instantiate optimizer UpperCAmelCase_ : str = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCAmelCase_ : List[str] = optimizer_cls(params=model.parameters(), lr=SCREAMING_SNAKE_CASE__ ) if accelerator.state.deepspeed_plugin is not None: UpperCAmelCase_ : List[Any] = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: UpperCAmelCase_ : Tuple = 1 UpperCAmelCase_ : int = (len(SCREAMING_SNAKE_CASE__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCAmelCase_ : Tuple = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE__, num_warmup_steps=0, num_training_steps=SCREAMING_SNAKE_CASE__, ) else: UpperCAmelCase_ : Any = DummyScheduler(SCREAMING_SNAKE_CASE__, total_num_steps=SCREAMING_SNAKE_CASE__, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = accelerator.prepare( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase_ : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly UpperCAmelCase_ : Dict = 0 UpperCAmelCase_ : int = evaluate.load('''glue''', '''mrpc''' ) UpperCAmelCase_ : Optional[Any] = num_epochs if args.partial_train_epoch is not None: UpperCAmelCase_ : List[Any] = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) UpperCAmelCase_ : Tuple = args.resume_from_checkpoint.split('''epoch_''' )[1] UpperCAmelCase_ : int = '''''' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break UpperCAmelCase_ : Union[str, Any] = int(SCREAMING_SNAKE_CASE__ ) + 1 UpperCAmelCase_ : Dict = evaluation_loop(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) accelerator.print('''resumed checkpoint performance:''', SCREAMING_SNAKE_CASE__ ) accelerator.print('''resumed checkpoint\'s scheduler\'s lr:''', lr_scheduler.get_lr()[0] ) accelerator.print('''resumed optimizers\'s lr:''', optimizer.param_groups[0]['''lr'''] ) with open(os.path.join(args.output_dir, F"""state_{starting_epoch-1}.json""" ), '''r''' ) as f: UpperCAmelCase_ : Optional[int] = json.load(SCREAMING_SNAKE_CASE__ ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model UpperCAmelCase_ : int = {} for epoch in range(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Optional[int] = model(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Any = outputs.loss UpperCAmelCase_ : Tuple = loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 UpperCAmelCase_ : Tuple = F"""epoch_{epoch}""" UpperCAmelCase_ : Optional[int] = os.path.join(args.output_dir, SCREAMING_SNAKE_CASE__ ) accelerator.save_state(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = evaluation_loop(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[Any] = accuracy UpperCAmelCase_ : Any = lr_scheduler.get_lr()[0] UpperCAmelCase_ : List[str] = optimizer.param_groups[0]['''lr'''] UpperCAmelCase_ : Tuple = epoch UpperCAmelCase_ : Dict = overall_step accelerator.print(F"""epoch {epoch}:""", SCREAMING_SNAKE_CASE__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F"""state_{epoch}.json""" ), '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( ) -> List[str]: UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''', type=SCREAMING_SNAKE_CASE__, default='''bert-base-cased''', help='''Path to pretrained model or model identifier from huggingface.co/models.''', required=SCREAMING_SNAKE_CASE__, ) parser.add_argument( '''--output_dir''', type=SCREAMING_SNAKE_CASE__, default='''.''', help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''', ) parser.add_argument( '''--resume_from_checkpoint''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''If the training should continue from a checkpoint folder.''', ) parser.add_argument( '''--partial_train_epoch''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''If passed, the training will stop after this number of epochs.''', ) parser.add_argument( '''--num_epochs''', type=SCREAMING_SNAKE_CASE__, default=2, help='''Number of train epochs.''', ) UpperCAmelCase_ : Optional[int] = parser.parse_args() UpperCAmelCase_ : List[Any] = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
644
0
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 __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def UpperCAmelCase__ ( self : Optional[int] ) -> int: """simple docstring""" UpperCAmelCase_ : int = 1 UpperCAmelCase_ : Union[str, Any] = 3 UpperCAmelCase_ : Union[str, Any] = (32, 32) UpperCAmelCase_ : List[str] = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(__magic_name__ ) return image @property def UpperCAmelCase__ ( self : Tuple ) -> List[Any]: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase_ : List[Any] = 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 : Optional[Any] ) -> str: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase_ : List[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 : List[str] ) -> Dict: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase_ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) return CLIPTextModel(__magic_name__ ) @property def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" def extract(*__magic_name__ : int , **__magic_name__ : Optional[Any] ): class __a : def __init__( self : Any ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[Any] = torch.ones([0] ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Tuple ) -> Dict: """simple docstring""" self.pixel_values.to(__magic_name__ ) return self return Out() return extract def UpperCAmelCase__ ( self : str ) -> int: """simple docstring""" UpperCAmelCase_ : List[Any] = '''cpu''' # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ : Any = self.dummy_cond_unet UpperCAmelCase_ : Any = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=__magic_name__ , set_alpha_to_one=__magic_name__ , ) UpperCAmelCase_ : List[str] = self.dummy_vae UpperCAmelCase_ : Any = self.dummy_text_encoder UpperCAmelCase_ : str = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) # make sure here that pndm scheduler skips prk UpperCAmelCase_ : Dict = StableDiffusionPipeline( unet=__magic_name__ , scheduler=__magic_name__ , vae=__magic_name__ , text_encoder=__magic_name__ , tokenizer=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=self.dummy_extractor , ) UpperCAmelCase_ : str = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = '''A painting of a squirrel eating a burger''' UpperCAmelCase_ : List[str] = torch.Generator(device=__magic_name__ ).manual_seed(0 ) UpperCAmelCase_ : Tuple = sd_pipe([prompt] , generator=__magic_name__ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' ) UpperCAmelCase_ : List[Any] = output.images UpperCAmelCase_ : List[str] = torch.Generator(device=__magic_name__ ).manual_seed(0 ) UpperCAmelCase_ : List[Any] = sd_pipe( [prompt] , generator=__magic_name__ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , return_dict=__magic_name__ , )[0] UpperCAmelCase_ : Optional[Any] = image[0, -3:, -3:, -1] UpperCAmelCase_ : Optional[int] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase_ : Union[str, Any] = np.array([0.5_7_5_6, 0.6_1_1_8, 0.5_0_0_5, 0.5_0_4_1, 0.5_4_7_1, 0.4_7_2_6, 0.4_9_7_6, 0.4_8_6_5, 0.4_8_6_4] ) 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 : Optional[Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Any = '''cpu''' # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ : Union[str, Any] = self.dummy_cond_unet UpperCAmelCase_ : Union[str, Any] = PNDMScheduler(skip_prk_steps=__magic_name__ ) UpperCAmelCase_ : Tuple = self.dummy_vae UpperCAmelCase_ : List[Any] = self.dummy_text_encoder UpperCAmelCase_ : List[Any] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) # make sure here that pndm scheduler skips prk UpperCAmelCase_ : int = StableDiffusionPipeline( unet=__magic_name__ , scheduler=__magic_name__ , vae=__magic_name__ , text_encoder=__magic_name__ , tokenizer=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=self.dummy_extractor , ) UpperCAmelCase_ : Union[str, Any] = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : str = '''A painting of a squirrel eating a burger''' UpperCAmelCase_ : str = torch.Generator(device=__magic_name__ ).manual_seed(0 ) UpperCAmelCase_ : List[str] = sd_pipe([prompt] , generator=__magic_name__ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' ) UpperCAmelCase_ : int = output.images UpperCAmelCase_ : str = torch.Generator(device=__magic_name__ ).manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = sd_pipe( [prompt] , generator=__magic_name__ , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , return_dict=__magic_name__ , )[0] UpperCAmelCase_ : Optional[int] = image[0, -3:, -3:, -1] UpperCAmelCase_ : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase_ : str = np.array([0.5_1_2_5, 0.5_7_1_6, 0.4_8_2_8, 0.5_0_6_0, 0.5_6_5_0, 0.4_7_6_8, 0.5_1_8_5, 0.4_8_9_5, 0.4_9_9_3] ) 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 : Dict ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = StableDiffusionPipeline.from_pretrained( '''hf-internal-testing/tiny-stable-diffusion-lms-pipe''' , safety_checker=__magic_name__ ) assert isinstance(__magic_name__ , __magic_name__ ) assert isinstance(pipe.scheduler , __magic_name__ ) assert pipe.safety_checker is None UpperCAmelCase_ : Tuple = 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(__magic_name__ ) UpperCAmelCase_ : Dict = StableDiffusionPipeline.from_pretrained(__magic_name__ ) # sanity check that the pipeline still works assert pipe.safety_checker is None UpperCAmelCase_ : int = 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 : List[Any] ) -> int: """simple docstring""" UpperCAmelCase_ : str = self.dummy_cond_unet UpperCAmelCase_ : Optional[int] = PNDMScheduler(skip_prk_steps=__magic_name__ ) UpperCAmelCase_ : Optional[int] = self.dummy_vae UpperCAmelCase_ : List[str] = self.dummy_text_encoder UpperCAmelCase_ : Optional[Any] = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) # put models in fp16 UpperCAmelCase_ : Tuple = unet.half() UpperCAmelCase_ : List[str] = vae.half() UpperCAmelCase_ : Union[str, Any] = bert.half() # make sure here that pndm scheduler skips prk UpperCAmelCase_ : Union[str, Any] = StableDiffusionPipeline( unet=__magic_name__ , scheduler=__magic_name__ , vae=__magic_name__ , text_encoder=__magic_name__ , tokenizer=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=self.dummy_extractor , ) UpperCAmelCase_ : Optional[Any] = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = '''A painting of a squirrel eating a burger''' UpperCAmelCase_ : Any = sd_pipe([prompt] , num_inference_steps=2 , output_type='''np''' ).images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''' , safety_checker=__magic_name__ ) UpperCAmelCase_ : Any = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) UpperCAmelCase_ : Optional[int] = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Tuple = ( '''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 ''' ) UpperCAmelCase_ : Dict = 40_03_66_03_46 UpperCAmelCase_ : Optional[int] = 7 # without safety guidance (sld_guidance_scale = 0) UpperCAmelCase_ : Union[str, Any] = torch.manual_seed(__magic_name__ ) UpperCAmelCase_ : Dict = sd_pipe( [prompt] , generator=__magic_name__ , guidance_scale=__magic_name__ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) UpperCAmelCase_ : Optional[int] = output.images UpperCAmelCase_ : Union[str, Any] = image[0, -3:, -3:, -1] UpperCAmelCase_ : Dict = [0.2_2_7_8, 0.2_2_3_1, 0.2_2_4_9, 0.2_3_3_3, 0.2_3_0_3, 0.1_8_8_5, 0.2_2_7_3, 0.2_1_4_4, 0.2_1_7_6] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 # without safety guidance (strong configuration) UpperCAmelCase_ : Union[str, Any] = torch.manual_seed(__magic_name__ ) UpperCAmelCase_ : Any = sd_pipe( [prompt] , generator=__magic_name__ , guidance_scale=__magic_name__ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) UpperCAmelCase_ : str = output.images UpperCAmelCase_ : Optional[int] = image[0, -3:, -3:, -1] UpperCAmelCase_ : List[Any] = [0.2_3_8_3, 0.2_2_7_6, 0.2_3_6, 0.2_1_9_2, 0.2_1_8_6, 0.2_0_5_3, 0.1_9_7_1, 0.1_9_0_1, 0.1_7_1_9] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''' , safety_checker=__magic_name__ ) UpperCAmelCase_ : Tuple = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config ) UpperCAmelCase_ : List[Any] = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Any = '''padme amidala taking a bath artwork, safe for work, no nudity''' UpperCAmelCase_ : Union[str, Any] = 27_34_97_17_55 UpperCAmelCase_ : str = 7 UpperCAmelCase_ : List[str] = torch.manual_seed(__magic_name__ ) UpperCAmelCase_ : Tuple = sd_pipe( [prompt] , generator=__magic_name__ , guidance_scale=__magic_name__ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) UpperCAmelCase_ : str = output.images UpperCAmelCase_ : int = image[0, -3:, -3:, -1] UpperCAmelCase_ : Dict = [0.3_5_0_2, 0.3_6_2_2, 0.3_3_9_6, 0.3_6_4_2, 0.3_4_7_8, 0.3_3_1_8, 0.3_5, 0.3_3_4_8, 0.3_2_9_7] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 UpperCAmelCase_ : Optional[Any] = torch.manual_seed(__magic_name__ ) UpperCAmelCase_ : int = sd_pipe( [prompt] , generator=__magic_name__ , guidance_scale=__magic_name__ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) UpperCAmelCase_ : Optional[int] = output.images UpperCAmelCase_ : Union[str, Any] = image[0, -3:, -3:, -1] UpperCAmelCase_ : Optional[Any] = [0.5_5_3_1, 0.5_2_0_6, 0.4_8_9_5, 0.5_1_5_6, 0.5_1_8_2, 0.4_7_5_1, 0.4_8_0_2, 0.4_8_0_3, 0.4_4_4_3] assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5''' ) UpperCAmelCase_ : Optional[Any] = sd_pipe.to(__magic_name__ ) sd_pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : str = ( '''the four horsewomen of the apocalypse, painting by tom of finland, gaston bussiere, craig mullins, j. c.''' ''' leyendecker''' ) UpperCAmelCase_ : Any = 10_44_35_52_34 UpperCAmelCase_ : Dict = 12 UpperCAmelCase_ : List[str] = torch.manual_seed(__magic_name__ ) UpperCAmelCase_ : int = sd_pipe( [prompt] , generator=__magic_name__ , guidance_scale=__magic_name__ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=0 , ) UpperCAmelCase_ : Union[str, Any] = output.images UpperCAmelCase_ : Optional[int] = image[0, -3:, -3:, -1] UpperCAmelCase_ : List[Any] = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ) assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-7 UpperCAmelCase_ : Union[str, Any] = torch.manual_seed(__magic_name__ ) UpperCAmelCase_ : Any = sd_pipe( [prompt] , generator=__magic_name__ , guidance_scale=__magic_name__ , num_inference_steps=50 , output_type='''np''' , width=5_12 , height=5_12 , sld_guidance_scale=20_00 , sld_warmup_steps=7 , sld_threshold=0.0_2_5 , sld_momentum_scale=0.5 , sld_mom_beta=0.7 , ) UpperCAmelCase_ : Tuple = output.images UpperCAmelCase_ : Any = image[0, -3:, -3:, -1] UpperCAmelCase_ : Optional[int] = np.array([0.5_8_1_8, 0.6_2_8_5, 0.6_8_3_5, 0.6_0_1_9, 0.6_2_5, 0.6_7_5_4, 0.6_0_9_6, 0.6_3_3_4, 0.6_5_6_1] ) assert image.shape == (1, 5_12, 5_12, 3) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
704
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : list[int] ) -> list[list[int]]: UpperCAmelCase_ : int = [] if len(SCREAMING_SNAKE_CASE__ ) == 1: return [nums.copy()] for _ in range(len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ : List[Any] = nums.pop(0 ) UpperCAmelCase_ : Optional[Any] = permute(SCREAMING_SNAKE_CASE__ ) for perm in permutations: perm.append(SCREAMING_SNAKE_CASE__ ) result.extend(SCREAMING_SNAKE_CASE__ ) nums.append(SCREAMING_SNAKE_CASE__ ) return result def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: def backtrack(SCREAMING_SNAKE_CASE__ : Union[str, Any] ): if start == len(SCREAMING_SNAKE_CASE__ ) - 1: output.append(nums[:] ) else: for i in range(SCREAMING_SNAKE_CASE__, len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ , UpperCAmelCase_ : Tuple = nums[i], nums[start] backtrack(start + 1 ) UpperCAmelCase_ , UpperCAmelCase_ : int = nums[i], nums[start] # backtrack UpperCAmelCase_ : Optional[int] = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function snake_case_ : Tuple = permutea([1, 2, 3]) print(res) doctest.testmod()
644
0
'''simple docstring''' from __future__ import annotations from typing import Any class __a : def __init__( self : List[str] , __magic_name__ : int = 6 ) -> None: """simple docstring""" UpperCAmelCase_ : Node | None = None UpperCAmelCase_ : Node | None = None self.create_linked_list(__magic_name__ ) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : Tuple = Node() UpperCAmelCase_ : Optional[int] = current_node UpperCAmelCase_ : int = current_node UpperCAmelCase_ : Optional[int] = current_node for _ in range(1 , __magic_name__ ): UpperCAmelCase_ : str = Node() UpperCAmelCase_ : Dict = current_node UpperCAmelCase_ : Union[str, Any] = previous_node UpperCAmelCase_ : List[str] = current_node UpperCAmelCase_ : List[Any] = self.front UpperCAmelCase_ : Union[str, Any] = previous_node def UpperCAmelCase__ ( self : str ) -> bool: """simple docstring""" return ( self.front == self.rear and self.front is not None and self.front.data is None ) def UpperCAmelCase__ ( self : List[str] ) -> Any | None: """simple docstring""" self.check_can_perform_operation() return self.front.data if self.front else None def UpperCAmelCase__ ( self : Any , __magic_name__ : Any ) -> None: """simple docstring""" if self.rear is None: return self.check_is_full() if not self.is_empty(): UpperCAmelCase_ : Any = self.rear.next if self.rear: UpperCAmelCase_ : List[str] = data def UpperCAmelCase__ ( self : Union[str, 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: UpperCAmelCase_ : Any = self.front.data UpperCAmelCase_ : Optional[Any] = None return data UpperCAmelCase_ : Dict = self.front UpperCAmelCase_ : Dict = old_front.next UpperCAmelCase_ : Optional[Any] = old_front.data UpperCAmelCase_ : List[str] = None return data def UpperCAmelCase__ ( self : Tuple ) -> None: """simple docstring""" if self.is_empty(): raise Exception('''Empty Queue''' ) def UpperCAmelCase__ ( self : str ) -> None: """simple docstring""" if self.rear and self.rear.next == self.front: raise Exception('''Full Queue''' ) class __a : def __init__( self : Optional[int] ) -> None: """simple docstring""" UpperCAmelCase_ : Any | None = None UpperCAmelCase_ : Node | None = None UpperCAmelCase_ : Node | None = None if __name__ == "__main__": import doctest doctest.testmod()
705
'''simple docstring''' class __a : def __init__( self : List[Any] , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : Optional[Any] = size UpperCAmelCase_ : Tuple = [0] * size UpperCAmelCase_ : Optional[Any] = [0] * size @staticmethod def UpperCAmelCase__ ( __magic_name__ : int ) -> int: """simple docstring""" return index | (index + 1) @staticmethod def UpperCAmelCase__ ( __magic_name__ : int ) -> int: """simple docstring""" return (index & (index + 1)) - 1 def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : int , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : int = value while index < self.size: UpperCAmelCase_ : str = self.get_prev(__magic_name__ ) + 1 if current_left_border == index: UpperCAmelCase_ : List[str] = value else: UpperCAmelCase_ : Optional[int] = max(__magic_name__ , __magic_name__ , __magic_name__ ) UpperCAmelCase_ : Tuple = self.get_next(__magic_name__ ) def UpperCAmelCase__ ( self : Any , __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" right -= 1 # Because of right is exclusive UpperCAmelCase_ : List[str] = 0 while left <= right: UpperCAmelCase_ : Optional[Any] = self.get_prev(__magic_name__ ) if left <= current_left: UpperCAmelCase_ : Dict = max(__magic_name__ , self.tree[right] ) UpperCAmelCase_ : Optional[Any] = current_left else: UpperCAmelCase_ : str = max(__magic_name__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
644
0
'''simple docstring''' from __future__ import annotations from random import random from typing import Generic, TypeVar snake_case_ : List[str] = TypeVar("KT") snake_case_ : int = TypeVar("VT") class __a (Generic[KT, VT] ): def __init__( self : Union[str, Any] , __magic_name__ : KT | str = "root" , __magic_name__ : VT | None = None ) -> str: """simple docstring""" UpperCAmelCase_ : str = key UpperCAmelCase_ : Dict = value UpperCAmelCase_ : list[Node[KT, VT]] = [] def __repr__( self : Optional[Any] ) -> str: """simple docstring""" return F"""Node({self.key}: {self.value})""" @property def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return len(self.forward ) class __a (Generic[KT, VT] ): def __init__( self : str , __magic_name__ : float = 0.5 , __magic_name__ : int = 16 ) -> Any: """simple docstring""" UpperCAmelCase_ : Node[KT, VT] = Node[KT, VT]() UpperCAmelCase_ : Dict = 0 UpperCAmelCase_ : Tuple = p UpperCAmelCase_ : Tuple = max_level def __str__( self : Optional[Any] ) -> str: """simple docstring""" UpperCAmelCase_ : Optional[Any] = list(self ) if len(__magic_name__ ) == 0: return F"""SkipList(level={self.level})""" UpperCAmelCase_ : Tuple = max((len(str(__magic_name__ ) ) for item in items) , default=4 ) UpperCAmelCase_ : Tuple = max(__magic_name__ , 4 ) + 4 UpperCAmelCase_ : Dict = self.head UpperCAmelCase_ : str = [] UpperCAmelCase_ : int = node.forward.copy() lines.append(F"""[{node.key}]""".ljust(__magic_name__ , '''-''' ) + '''* ''' * len(__magic_name__ ) ) lines.append(''' ''' * label_size + '''| ''' * len(__magic_name__ ) ) while len(node.forward ) != 0: UpperCAmelCase_ : str = node.forward[0] lines.append( F"""[{node.key}]""".ljust(__magic_name__ , '''-''' ) + ''' '''.join(str(n.key ) if n.key == node.key else '''|''' for n in forwards ) ) lines.append(''' ''' * label_size + '''| ''' * len(__magic_name__ ) ) UpperCAmelCase_ : List[Any] = node.forward lines.append('''None'''.ljust(__magic_name__ ) + '''* ''' * len(__magic_name__ ) ) return F"""SkipList(level={self.level})\n""" + "\n".join(__magic_name__ ) def __iter__( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.head while len(node.forward ) != 0: yield node.forward[0].key UpperCAmelCase_ : Any = node.forward[0] def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" UpperCAmelCase_ : Optional[Any] = 1 while random() < self.p and level < self.max_level: level += 1 return level def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : str ) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: """simple docstring""" UpperCAmelCase_ : List[str] = [] UpperCAmelCase_ : str = self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: UpperCAmelCase_ : int = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(__magic_name__ ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def UpperCAmelCase__ ( self : int , __magic_name__ : KT ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Any = self._locate_node(__magic_name__ ) if node is not None: for i, update_node in enumerate(__magic_name__ ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: UpperCAmelCase_ : Optional[int] = node.forward[i] else: UpperCAmelCase_ : List[Any] = update_node.forward[:i] def UpperCAmelCase__ ( self : str , __magic_name__ : KT , __magic_name__ : VT ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Dict = self._locate_node(__magic_name__ ) if node is not None: UpperCAmelCase_ : str = value else: UpperCAmelCase_ : Optional[Any] = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , __magic_name__ ): update_vector.append(self.head ) UpperCAmelCase_ : int = level UpperCAmelCase_ : Optional[int] = Node(__magic_name__ , __magic_name__ ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(__magic_name__ ) else: UpperCAmelCase_ : Tuple = new_node def UpperCAmelCase__ ( self : Any , __magic_name__ : VT ) -> VT | None: """simple docstring""" UpperCAmelCase_ : Tuple = self._locate_node(__magic_name__ ) if node is not None: return node.value return None def lowerCamelCase_ ( ) -> List[Any]: UpperCAmelCase_ : List[Any] = SkipList() skip_list.insert('''Key1''', 3 ) skip_list.insert('''Key2''', 12 ) skip_list.insert('''Key3''', 41 ) skip_list.insert('''Key4''', -19 ) UpperCAmelCase_ : Dict = skip_list.head UpperCAmelCase_ : Any = {} while node.level != 0: UpperCAmelCase_ : List[str] = node.forward[0] UpperCAmelCase_ : Any = node.value assert len(SCREAMING_SNAKE_CASE__ ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def lowerCamelCase_ ( ) -> Any: UpperCAmelCase_ : List[str] = SkipList() skip_list.insert('''Key1''', 10 ) skip_list.insert('''Key1''', 12 ) skip_list.insert('''Key5''', 7 ) skip_list.insert('''Key7''', 10 ) skip_list.insert('''Key10''', 5 ) skip_list.insert('''Key7''', 7 ) skip_list.insert('''Key5''', 5 ) skip_list.insert('''Key10''', 10 ) UpperCAmelCase_ : Optional[Any] = skip_list.head UpperCAmelCase_ : Dict = {} while node.level != 0: UpperCAmelCase_ : List[Any] = node.forward[0] UpperCAmelCase_ : Dict = node.value if len(SCREAMING_SNAKE_CASE__ ) != 4: print() assert len(SCREAMING_SNAKE_CASE__ ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def lowerCamelCase_ ( ) -> Union[str, Any]: UpperCAmelCase_ : Any = SkipList() assert skip_list.find('''Some key''' ) is None def lowerCamelCase_ ( ) -> Optional[Any]: UpperCAmelCase_ : Optional[Any] = SkipList() skip_list.insert('''Key2''', 20 ) assert skip_list.find('''Key2''' ) == 20 skip_list.insert('''Some Key''', 10 ) skip_list.insert('''Key2''', 8 ) skip_list.insert('''V''', 13 ) assert skip_list.find('''Y''' ) is None assert skip_list.find('''Key2''' ) == 8 assert skip_list.find('''Some Key''' ) == 10 assert skip_list.find('''V''' ) == 13 def lowerCamelCase_ ( ) -> Optional[int]: UpperCAmelCase_ : int = SkipList() skip_list.delete('''Some key''' ) assert len(skip_list.head.forward ) == 0 def lowerCamelCase_ ( ) -> List[str]: UpperCAmelCase_ : Optional[Any] = SkipList() skip_list.insert('''Key1''', 12 ) skip_list.insert('''V''', 13 ) skip_list.insert('''X''', 14 ) skip_list.insert('''Key2''', 15 ) skip_list.delete('''V''' ) skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''Key2''' ) is None def lowerCamelCase_ ( ) -> Optional[Any]: UpperCAmelCase_ : int = SkipList() skip_list.insert('''Key1''', 12 ) skip_list.insert('''V''', 13 ) skip_list.insert('''X''', 14 ) skip_list.insert('''Key2''', 15 ) skip_list.delete('''V''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) == 14 assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''X''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) == 12 assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key1''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) == 15 skip_list.delete('''Key2''' ) assert skip_list.find('''V''' ) is None assert skip_list.find('''X''' ) is None assert skip_list.find('''Key1''' ) is None assert skip_list.find('''Key2''' ) is None def lowerCamelCase_ ( ) -> Tuple: UpperCAmelCase_ : Tuple = SkipList() skip_list.insert('''Key1''', 12 ) skip_list.insert('''V''', 13 ) skip_list.insert('''X''', 142 ) skip_list.insert('''Key2''', 15 ) skip_list.delete('''X''' ) def traverse_keys(SCREAMING_SNAKE_CASE__ : Optional[Any] ): yield node.key for forward_node in node.forward: yield from traverse_keys(SCREAMING_SNAKE_CASE__ ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def lowerCamelCase_ ( ) -> Union[str, Any]: def is_sorted(SCREAMING_SNAKE_CASE__ : Tuple ): return all(next_item >= item for item, next_item in zip(SCREAMING_SNAKE_CASE__, lst[1:] ) ) UpperCAmelCase_ : Union[str, Any] = SkipList() for i in range(10 ): skip_list.insert(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) assert is_sorted(list(SCREAMING_SNAKE_CASE__ ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(SCREAMING_SNAKE_CASE__ ) ) skip_list.insert(-12, -12 ) skip_list.insert(77, 77 ) assert is_sorted(list(SCREAMING_SNAKE_CASE__ ) ) def lowerCamelCase_ ( ) -> Any: for _ in range(100 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def lowerCamelCase_ ( ) -> Any: UpperCAmelCase_ : Dict = SkipList() skip_list.insert(2, '''2''' ) skip_list.insert(4, '''4''' ) skip_list.insert(6, '''4''' ) skip_list.insert(4, '''5''' ) skip_list.insert(8, '''4''' ) skip_list.insert(9, '''4''' ) skip_list.delete(4 ) print(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
706
'''simple docstring''' import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __a : def __init__( self : List[str] , __magic_name__ : List[str] , __magic_name__ : str=13 , __magic_name__ : Union[str, Any]=7 , __magic_name__ : Union[str, Any]=True , __magic_name__ : Any=True , __magic_name__ : List[str]=False , __magic_name__ : Optional[int]=True , __magic_name__ : Dict=99 , __magic_name__ : Tuple=32 , __magic_name__ : int=5 , __magic_name__ : Dict=4 , __magic_name__ : Tuple=37 , __magic_name__ : Optional[int]="gelu" , __magic_name__ : List[str]=0.1 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : str=5_12 , __magic_name__ : Union[str, Any]=16 , __magic_name__ : int=2 , __magic_name__ : List[Any]=0.0_2 , __magic_name__ : Tuple=3 , __magic_name__ : Union[str, Any]=4 , __magic_name__ : Optional[int]=None , ) -> str: """simple docstring""" UpperCAmelCase_ : Any = parent UpperCAmelCase_ : Union[str, Any] = batch_size UpperCAmelCase_ : List[Any] = seq_length UpperCAmelCase_ : str = is_training UpperCAmelCase_ : Any = use_input_mask UpperCAmelCase_ : List[str] = use_token_type_ids UpperCAmelCase_ : Union[str, Any] = use_labels UpperCAmelCase_ : Dict = vocab_size UpperCAmelCase_ : Optional[Any] = hidden_size UpperCAmelCase_ : Dict = num_hidden_layers UpperCAmelCase_ : List[Any] = num_attention_heads UpperCAmelCase_ : Optional[int] = intermediate_size UpperCAmelCase_ : Union[str, Any] = hidden_act UpperCAmelCase_ : str = hidden_dropout_prob UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase_ : Any = max_position_embeddings UpperCAmelCase_ : str = type_vocab_size UpperCAmelCase_ : Optional[Any] = type_sequence_label_size UpperCAmelCase_ : List[Any] = initializer_range UpperCAmelCase_ : int = num_labels UpperCAmelCase_ : Optional[int] = num_choices UpperCAmelCase_ : Tuple = scope def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : Union[str, Any] = None if self.use_input_mask: UpperCAmelCase_ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ : str = None if self.use_token_type_ids: UpperCAmelCase_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Tuple = None UpperCAmelCase_ : List[str] = None UpperCAmelCase_ : Union[str, Any] = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase_ : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" return BioGptConfig( 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=__magic_name__ , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : Tuple , __magic_name__ : str , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = BioGptModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Dict = model(__magic_name__ , attention_mask=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Tuple , __magic_name__ : List[str] , __magic_name__ : Optional[int] , ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptForCausalLM(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : List[Any] = model(__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase__ ( self : str , __magic_name__ : Optional[int] , __magic_name__ : Tuple , __magic_name__ : List[str] , __magic_name__ : int , __magic_name__ : str , *__magic_name__ : Any ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() # create attention mask UpperCAmelCase_ : Optional[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=__magic_name__ ) UpperCAmelCase_ : Any = self.seq_length // 2 UpperCAmelCase_ : Tuple = 0 # first forward pass UpperCAmelCase_ , UpperCAmelCase_ : Dict = model(__magic_name__ , attention_mask=__magic_name__ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase_ : Tuple = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCAmelCase_ : List[str] = ids_tensor((1,) , __magic_name__ ).item() + 1 UpperCAmelCase_ : Tuple = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCAmelCase_ : str = random_other_next_tokens # append to next input_ids and attn_mask UpperCAmelCase_ : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase_ : int = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=__magic_name__ )] , dim=1 , ) # get two different outputs UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] UpperCAmelCase_ : int = model(__magic_name__ , past_key_values=__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] # select random slice UpperCAmelCase_ : Optional[int] = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase_ : Union[str, Any] = output_from_no_past[:, -1, random_slice_idx].detach() UpperCAmelCase_ : Dict = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Dict , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , *__magic_name__ : str ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptModel(config=__magic_name__ ).to(__magic_name__ ).eval() UpperCAmelCase_ : Optional[int] = torch.ones(input_ids.shape , dtype=torch.long , device=__magic_name__ ) # first forward pass UpperCAmelCase_ : Union[str, Any] = model(__magic_name__ , attention_mask=__magic_name__ , use_cache=__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ : int = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCAmelCase_ : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase_ : Any = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCAmelCase_ : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase_ : List[str] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] UpperCAmelCase_ : Optional[Any] = model(__magic_name__ , attention_mask=__magic_name__ , past_key_values=__magic_name__ )[ '''last_hidden_state''' ] # select random slice UpperCAmelCase_ : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase_ : str = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCAmelCase_ : Optional[int] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-3 ) ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : str , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , *__magic_name__ : Any , __magic_name__ : List[Any]=False ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = BioGptForCausalLM(__magic_name__ ) model.to(__magic_name__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCAmelCase_ : List[str] = model(__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Optional[int] , *__magic_name__ : List[str] ) -> str: """simple docstring""" UpperCAmelCase_ : int = BioGptModel(__magic_name__ ) UpperCAmelCase_ : Dict = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.0_0_1 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.0_1 ) def UpperCAmelCase__ ( self : int , __magic_name__ : Tuple , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , *__magic_name__ : Any ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : str = self.num_labels UpperCAmelCase_ : Any = BioGptForTokenClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" UpperCAmelCase_ : List[Any] = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : int = config_and_inputs UpperCAmelCase_ : Any = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __a (lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : str = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) __a : List[Any] = (BioGptForCausalLM,) if is_torch_available() else () __a : Union[str, Any] = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) __a : List[str] = False def UpperCAmelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" UpperCAmelCase_ : List[str] = BioGptModelTester(self ) UpperCAmelCase_ : Optional[Any] = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ : str = type self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*__magic_name__ , gradient_checkpointing=__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*__magic_name__ ) def UpperCAmelCase__ ( self : Dict ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*__magic_name__ ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*__magic_name__ ) @slow def UpperCAmelCase__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) model.to(__magic_name__ ) UpperCAmelCase_ : List[str] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : Tuple = '''left''' # Define PAD Token = EOS Token = 50256 UpperCAmelCase_ : List[Any] = tokenizer.eos_token UpperCAmelCase_ : List[Any] = model.config.eos_token_id # use different length sentences to test batching UpperCAmelCase_ : Tuple = [ '''Hello, my dog is a little''', '''Today, I''', ] UpperCAmelCase_ : Optional[Any] = tokenizer(__magic_name__ , return_tensors='''pt''' , padding=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = inputs['''input_ids'''].to(__magic_name__ ) UpperCAmelCase_ : Any = model.generate( input_ids=__magic_name__ , attention_mask=inputs['''attention_mask'''].to(__magic_name__ ) , ) UpperCAmelCase_ : Union[str, Any] = tokenizer(sentences[0] , return_tensors='''pt''' ).input_ids.to(__magic_name__ ) UpperCAmelCase_ : Tuple = model.generate(input_ids=__magic_name__ ) UpperCAmelCase_ : List[str] = inputs_non_padded.shape[-1] - inputs['''attention_mask'''][-1].long().sum().cpu().item() UpperCAmelCase_ : List[Any] = tokenizer(sentences[1] , return_tensors='''pt''' ).input_ids.to(__magic_name__ ) UpperCAmelCase_ : Tuple = model.generate(input_ids=__magic_name__ , max_length=model.config.max_length - num_paddings ) UpperCAmelCase_ : int = tokenizer.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Dict = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = [ '''Hello, my dog is a little bit bigger than a little bit.''', '''Today, I have a good idea of how to use the information''', ] self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertListEqual(__magic_name__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : List[Any] = BioGptModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : str = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : List[str] = 3 UpperCAmelCase_ : Tuple = input_dict['''input_ids'''] UpperCAmelCase_ : Dict = input_ids.ne(1 ).to(__magic_name__ ) UpperCAmelCase_ : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCAmelCase_ : Dict = BioGptForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : int = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : List[Any] = 3 UpperCAmelCase_ : Optional[int] = '''multi_label_classification''' UpperCAmelCase_ : int = input_dict['''input_ids'''] UpperCAmelCase_ : str = input_ids.ne(1 ).to(__magic_name__ ) UpperCAmelCase_ : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCAmelCase_ : Union[str, Any] = BioGptForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : str = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __a (unittest.TestCase ): @slow def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" UpperCAmelCase_ : str = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : List[str] = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCAmelCase_ : str = model(__magic_name__ )[0] UpperCAmelCase_ : Optional[int] = 4_23_84 UpperCAmelCase_ : Tuple = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , __magic_name__ ) UpperCAmelCase_ : List[Any] = torch.tensor( [[[-9.5_2_3_6, -9.8_9_1_8, 1_0.4_5_5_7], [-1_1.0_4_6_9, -9.6_4_2_3, 8.1_0_2_2], [-8.8_6_6_4, -7.8_8_2_6, 5.5_3_2_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __magic_name__ , atol=1E-4 ) ) @slow def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Any = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : str = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) model.to(__magic_name__ ) torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = tokenizer('''COVID-19 is''' , return_tensors='''pt''' ).to(__magic_name__ ) UpperCAmelCase_ : Optional[int] = model.generate( **__magic_name__ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=__magic_name__ , ) UpperCAmelCase_ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = ( '''COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the''' ''' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and''' ''' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),''' ''' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and''' ''' more than 800,000 deaths.''' ) self.assertEqual(__magic_name__ , __magic_name__ )
644
0
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str ) -> str: return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
707
'''simple docstring''' import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class __a (lowerCamelCase , unittest.TestCase ): __a : List[str] = BlenderbotSmallTokenizer __a : List[Any] = False def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" super().setUp() UpperCAmelCase_ : Tuple = ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__'''] UpperCAmelCase_ : Optional[Any] = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) UpperCAmelCase_ : int = ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', ''''''] UpperCAmelCase_ : Optional[Any] = {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''} UpperCAmelCase_ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__magic_name__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__magic_name__ ) ) def UpperCAmelCase__ ( self : List[Any] , **__magic_name__ : Dict ) -> Tuple: """simple docstring""" kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : List[str] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : str = '''adapt act apte''' UpperCAmelCase_ : Tuple = '''adapt act apte''' return input_text, output_text def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" UpperCAmelCase_ : str = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCAmelCase_ : List[Any] = '''adapt act apte''' UpperCAmelCase_ : Dict = ['''adapt''', '''act''', '''ap@@''', '''te'''] UpperCAmelCase_ : Dict = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) UpperCAmelCase_ : Tuple = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" UpperCAmelCase_ : List[Any] = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) assert tok('''sam''' ).input_ids == [13_84] UpperCAmelCase_ : Optional[int] = '''I am a small frog.''' UpperCAmelCase_ : List[str] = tok([src_text] , padding=__magic_name__ , truncation=__magic_name__ )['''input_ids'''] UpperCAmelCase_ : Dict = tok.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ , clean_up_tokenization_spaces=__magic_name__ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) UpperCAmelCase_ : List[Any] = '''I am a small frog .''' UpperCAmelCase_ : Any = '''.''' UpperCAmelCase_ : List[Any] = tok(__magic_name__ )['''input_ids'''] UpperCAmelCase_ : Optional[int] = tok(__magic_name__ )['''input_ids'''] assert encoded[-1] == encoded_dot[0]
644
0
'''simple docstring''' from math import factorial def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int = 100 ) -> int: return sum(int(SCREAMING_SNAKE_CASE__ ) for x in str(factorial(SCREAMING_SNAKE_CASE__ ) ) ) if __name__ == "__main__": print(solution(int(input("Enter the Number: ").strip())))
708
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" UpperCAmelCase_ : Dict = get_activation('''swish''' ) self.assertIsInstance(__magic_name__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , 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 : Tuple ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = get_activation('''silu''' ) self.assertIsInstance(__magic_name__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , 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 : Tuple ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Optional[int] = get_activation('''mish''' ) self.assertIsInstance(__magic_name__ , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , 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 : str ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = get_activation('''gelu''' ) self.assertIsInstance(__magic_name__ , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , 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 )
644
0
'''simple docstring''' from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer snake_case_ : Any = logging.get_logger(__name__) snake_case_ : Optional[int] = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"} snake_case_ : Dict = { "vocab_file": { "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json" }, "merges_file": { "allegro/herbert-base-cased": "https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt" }, } snake_case_ : Optional[Any] = {"allegro/herbert-base-cased": 5_14} snake_case_ : Union[str, Any] = {} class __a (lowerCamelCase ): __a : Optional[Any] = VOCAB_FILES_NAMES __a : Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP __a : Dict = PRETRAINED_INIT_CONFIGURATION __a : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a : Optional[int] = HerbertTokenizer def __init__( self : Optional[int] , __magic_name__ : List[Any]=None , __magic_name__ : Optional[int]=None , __magic_name__ : List[str]=None , __magic_name__ : int="<s>" , __magic_name__ : str="<unk>" , __magic_name__ : int="<pad>" , __magic_name__ : Any="<mask>" , __magic_name__ : Optional[Any]="</s>" , **__magic_name__ : Any , ) -> Union[str, Any]: """simple docstring""" super().__init__( __magic_name__ , __magic_name__ , tokenizer_file=__magic_name__ , cls_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , sep_token=__magic_name__ , **__magic_name__ , ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCAmelCase_ : List[Any] = [self.cls_token_id] UpperCAmelCase_ : List[Any] = [self.sep_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None , __magic_name__ : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) if token_ids_a is None: return [1] + ([0] * len(__magic_name__ )) + [1] return [1] + ([0] * len(__magic_name__ )) + [1] + ([0] * len(__magic_name__ )) + [1] def UpperCAmelCase__ ( self : str , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCAmelCase_ : Dict = [self.sep_token_id] UpperCAmelCase_ : 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 : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" UpperCAmelCase_ : int = self._tokenizer.model.save(__magic_name__ , name=__magic_name__ ) return tuple(__magic_name__ )
709
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging snake_case_ : Union[str, Any] = logging.get_logger(__name__) class __a (lowerCamelCase ): __a : Tuple = ["pixel_values"] def __init__( self : List[Any] , __magic_name__ : bool = True , __magic_name__ : int = 32 , __magic_name__ : Union[str, Any]=PILImageResampling.BILINEAR , __magic_name__ : bool = True , **__magic_name__ : List[str] , ) -> None: """simple docstring""" UpperCAmelCase_ : int = do_resize UpperCAmelCase_ : Tuple = do_rescale UpperCAmelCase_ : List[Any] = size_divisor UpperCAmelCase_ : Any = resample super().__init__(**__magic_name__ ) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : np.ndarray , __magic_name__ : int , __magic_name__ : str , __magic_name__ : Optional[ChannelDimension] = None , **__magic_name__ : Tuple ) -> np.ndarray: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : List[str] = get_image_size(__magic_name__ ) # Rounds the height and width down to the closest multiple of size_divisor UpperCAmelCase_ : Dict = height // size_divisor * size_divisor UpperCAmelCase_ : Dict = width // size_divisor * size_divisor UpperCAmelCase_ : Any = resize(__magic_name__ , (new_h, new_w) , resample=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) return image def UpperCAmelCase__ ( self : int , __magic_name__ : np.ndarray , __magic_name__ : float , __magic_name__ : Optional[ChannelDimension] = None , **__magic_name__ : Optional[Any] ) -> np.ndarray: """simple docstring""" return rescale(image=__magic_name__ , scale=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : str , __magic_name__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[int] = None , __magic_name__ : Any=None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[Union[TensorType, str]] = None , __magic_name__ : ChannelDimension = ChannelDimension.FIRST , **__magic_name__ : Tuple , ) -> BatchFeature: """simple docstring""" UpperCAmelCase_ : Dict = do_resize if do_resize is not None else self.do_resize UpperCAmelCase_ : str = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ : Any = size_divisor if size_divisor is not None else self.size_divisor UpperCAmelCase_ : Dict = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('''size_divisor is required for resizing''' ) UpperCAmelCase_ : Optional[int] = make_list_of_images(__magic_name__ ) if not valid_images(__magic_name__ ): raise ValueError('''Invalid image(s)''' ) # All transformations expect numpy arrays. UpperCAmelCase_ : List[str] = [to_numpy_array(__magic_name__ ) for img in images] if do_resize: UpperCAmelCase_ : str = [self.resize(__magic_name__ , size_divisor=__magic_name__ , resample=__magic_name__ ) for image in images] if do_rescale: UpperCAmelCase_ : Tuple = [self.rescale(__magic_name__ , scale=1 / 2_55 ) for image in images] UpperCAmelCase_ : Union[str, Any] = [to_channel_dimension_format(__magic_name__ , __magic_name__ ) for image in images] UpperCAmelCase_ : int = {'''pixel_values''': images} return BatchFeature(data=__magic_name__ , tensor_type=__magic_name__ )
644
0
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : dict ) -> set: UpperCAmelCase_ : Union[str, Any] = set() # edges = list of graph's edges UpperCAmelCase_ : Optional[int] = get_edges(SCREAMING_SNAKE_CASE__ ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: UpperCAmelCase_ : Optional[int] = edges.pop() chosen_vertices.add(SCREAMING_SNAKE_CASE__ ) chosen_vertices.add(SCREAMING_SNAKE_CASE__ ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(SCREAMING_SNAKE_CASE__ ) return chosen_vertices def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : dict ) -> set: UpperCAmelCase_ : int = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
710
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int = 10, SCREAMING_SNAKE_CASE__ : int = 22 ) -> int: UpperCAmelCase_ : Optional[int] = range(1, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = range(1, SCREAMING_SNAKE_CASE__ ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(f'''{solution(10, 22) = }''')
644
0
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: assert x is not None assert y is not None UpperCAmelCase_ : str = len(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[int] = len(SCREAMING_SNAKE_CASE__ ) # declaring the array for storing the dp values UpperCAmelCase_ : Optional[int] = [[0] * (n + 1) for _ in range(m + 1 )] # noqa: E741 for i in range(1, m + 1 ): for j in range(1, n + 1 ): UpperCAmelCase_ : Union[str, Any] = 1 if x[i - 1] == y[j - 1] else 0 UpperCAmelCase_ : Any = max(l[i - 1][j], l[i][j - 1], l[i - 1][j - 1] + match ) UpperCAmelCase_ : Tuple = '''''' UpperCAmelCase_ : List[str] = m, n while i > 0 and j > 0: UpperCAmelCase_ : List[str] = 1 if x[i - 1] == y[j - 1] else 0 if l[i][j] == l[i - 1][j - 1] + match: if match == 1: UpperCAmelCase_ : Dict = x[i - 1] + seq i -= 1 j -= 1 elif l[i][j] == l[i - 1][j]: i -= 1 else: j -= 1 return l[m][n], seq if __name__ == "__main__": snake_case_ : Optional[int] = "AGGTAB" snake_case_ : str = "GXTXAYB" snake_case_ : Optional[Any] = 4 snake_case_ : Optional[int] = "GTAB" snake_case_ : List[Any] = longest_common_subsequence(a, b) print("len =", ln, ", sub-sequence =", subseq) import doctest doctest.testmod()
711
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __a (lowerCamelCase ): __a : int = "dandelin/vilt-b32-finetuned-vqa" __a : Any = ( "This is a tool that answers a question about an image. It takes an input named `image` which should be the " "image containing the information, as well as a `question` which should be the question in English. It " "returns a text that is the answer to the question." ) __a : Any = "image_qa" __a : str = AutoProcessor __a : Any = AutoModelForVisualQuestionAnswering __a : List[Any] = ["image", "text"] __a : int = ["text"] def __init__( self : Tuple , *__magic_name__ : Any , **__magic_name__ : Any ) -> Tuple: """simple docstring""" requires_backends(self , ['''vision'''] ) super().__init__(*__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : "Image" , __magic_name__ : str ) -> Tuple: """simple docstring""" return self.pre_processor(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) def UpperCAmelCase__ ( self : Any , __magic_name__ : List[str] ) -> Optional[Any]: """simple docstring""" with torch.no_grad(): return self.model(**__magic_name__ ).logits def UpperCAmelCase__ ( self : int , __magic_name__ : int ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Dict = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
644
0
'''simple docstring''' import os def lowerCamelCase_ ( ) -> str: with open(os.path.dirname(SCREAMING_SNAKE_CASE__ ) + '''/grid.txt''' ) as f: UpperCAmelCase_ : Tuple = [] # noqa: E741 for _ in range(20 ): l.append([int(SCREAMING_SNAKE_CASE__ ) for x in f.readline().split()] ) UpperCAmelCase_ : Optional[Any] = 0 # right for i in range(20 ): for j in range(17 ): UpperCAmelCase_ : str = l[i][j] * l[i][j + 1] * l[i][j + 2] * l[i][j + 3] if temp > maximum: UpperCAmelCase_ : Optional[Any] = temp # down for i in range(17 ): for j in range(20 ): UpperCAmelCase_ : Optional[int] = l[i][j] * l[i + 1][j] * l[i + 2][j] * l[i + 3][j] if temp > maximum: UpperCAmelCase_ : Dict = temp # diagonal 1 for i in range(17 ): for j in range(17 ): UpperCAmelCase_ : int = l[i][j] * l[i + 1][j + 1] * l[i + 2][j + 2] * l[i + 3][j + 3] if temp > maximum: UpperCAmelCase_ : Tuple = temp # diagonal 2 for i in range(17 ): for j in range(3, 20 ): UpperCAmelCase_ : Tuple = l[i][j] * l[i + 1][j - 1] * l[i + 2][j - 2] * l[i + 3][j - 3] if temp > maximum: UpperCAmelCase_ : Optional[int] = temp return maximum if __name__ == "__main__": print(solution())
712
'''simple docstring''' from collections.abc import Iterable from typing import Any class __a : def __init__( self : Optional[Any] , __magic_name__ : int | None = None ) -> Tuple: """simple docstring""" UpperCAmelCase_ : List[str] = value UpperCAmelCase_ : Node | None = None # Added in order to delete a node easier UpperCAmelCase_ : Node | None = None UpperCAmelCase_ : Node | None = None def __repr__( self : List[str] ) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({F"""{self.value}""": (self.left, self.right)} , indent=1 ) class __a : def __init__( self : int , __magic_name__ : Node | None = None ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : str = root def __str__( self : Any ) -> str: """simple docstring""" return str(self.root ) def UpperCAmelCase__ ( self : Any , __magic_name__ : Node , __magic_name__ : Node | None ) -> None: """simple docstring""" if new_children is not None: # reset its kids UpperCAmelCase_ : Dict = node.parent if node.parent is not None: # reset its parent if self.is_right(__magic_name__ ): # If it is the right children UpperCAmelCase_ : Optional[Any] = new_children else: UpperCAmelCase_ : Optional[int] = new_children else: UpperCAmelCase_ : List[str] = new_children def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Node ) -> bool: """simple docstring""" if node.parent and node.parent.right: return node == node.parent.right return False def UpperCAmelCase__ ( self : Union[str, Any] ) -> bool: """simple docstring""" return self.root is None def UpperCAmelCase__ ( self : Any , __magic_name__ : str ) -> None: """simple docstring""" UpperCAmelCase_ : Tuple = Node(__magic_name__ ) # create a new Node if self.empty(): # if Tree is empty UpperCAmelCase_ : List[Any] = new_node # set its root else: # Tree is not empty UpperCAmelCase_ : str = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: UpperCAmelCase_ : Union[str, Any] = new_node # We insert the new node in a leaf break else: UpperCAmelCase_ : List[Any] = parent_node.left else: if parent_node.right is None: UpperCAmelCase_ : List[Any] = new_node break else: UpperCAmelCase_ : Union[str, Any] = parent_node.right UpperCAmelCase_ : Union[str, Any] = parent_node def UpperCAmelCase__ ( self : Optional[Any] , *__magic_name__ : List[str] ) -> None: """simple docstring""" for value in values: self.__insert(__magic_name__ ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : int ) -> Node | None: """simple docstring""" if self.empty(): raise IndexError('''Warning: Tree is empty! please use another.''' ) else: UpperCAmelCase_ : str = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: UpperCAmelCase_ : List[str] = node.left if value < node.value else node.right return node def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Node | None = None ) -> Node | None: """simple docstring""" if node is None: if self.root is None: return None UpperCAmelCase_ : Dict = self.root if not self.empty(): while node.right is not None: UpperCAmelCase_ : Any = node.right return node def UpperCAmelCase__ ( self : Dict , __magic_name__ : Node | None = None ) -> Node | None: """simple docstring""" if node is None: UpperCAmelCase_ : Optional[int] = self.root if self.root is None: return None if not self.empty(): UpperCAmelCase_ : Union[str, Any] = self.root while node.left is not None: UpperCAmelCase_ : Dict = node.left return node def UpperCAmelCase__ ( self : Tuple , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : List[str] = self.search(__magic_name__ ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(__magic_name__ , __magic_name__ ) elif node.left is None: # Has only right children self.__reassign_nodes(__magic_name__ , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(__magic_name__ , node.left ) else: UpperCAmelCase_ : List[str] = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore UpperCAmelCase_ : Optional[int] = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Node | None ) -> Iterable: """simple docstring""" if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : List[Any]=None ) -> Any: """simple docstring""" if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : list , __magic_name__ : Node | None ) -> None: """simple docstring""" if node: self.inorder(__magic_name__ , node.left ) arr.append(node.value ) self.inorder(__magic_name__ , node.right ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : int , __magic_name__ : Node ) -> int: """simple docstring""" UpperCAmelCase_ : list[int] = [] self.inorder(__magic_name__ , __magic_name__ ) # append all values to list using inorder traversal return arr[k - 1] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Node | None ) -> list[Node]: UpperCAmelCase_ : Any = [] if curr_node is not None: UpperCAmelCase_ : Any = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def lowerCamelCase_ ( ) -> None: UpperCAmelCase_ : str = (8, 3, 6, 1, 10, 14, 13, 4, 7) UpperCAmelCase_ : Tuple = BinarySearchTree() for i in testlist: t.insert(SCREAMING_SNAKE_CASE__ ) # Prints all the elements of the list in order traversal print(SCREAMING_SNAKE_CASE__ ) if t.search(6 ) is not None: print('''The value 6 exists''' ) else: print('''The value 6 doesn\'t exist''' ) if t.search(-1 ) is not None: print('''The value -1 exists''' ) else: print('''The value -1 doesn\'t exist''' ) if not t.empty(): print('''Max Value: ''', t.get_max().value ) # type: ignore print('''Min Value: ''', t.get_min().value ) # type: ignore for i in testlist: t.remove(SCREAMING_SNAKE_CASE__ ) print(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
644
0
def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> str: if a < 0 or b < 0: raise ValueError('''the value of both inputs must be positive''' ) UpperCAmelCase_ : int = str(bin(SCREAMING_SNAKE_CASE__ ) )[2:] # remove the leading "0b" UpperCAmelCase_ : Optional[Any] = str(bin(SCREAMING_SNAKE_CASE__ ) )[2:] # remove the leading "0b" UpperCAmelCase_ : int = max(len(SCREAMING_SNAKE_CASE__ ), len(SCREAMING_SNAKE_CASE__ ) ) return "0b" + "".join( str(int(char_a == '''1''' and char_b == '''1''' ) ) for char_a, char_b in zip(a_binary.zfill(SCREAMING_SNAKE_CASE__ ), b_binary.zfill(SCREAMING_SNAKE_CASE__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
713
'''simple docstring''' import sys import turtle def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float] ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : int, ) -> None: my_pen.up() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) if depth == 0: return triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( "Correct format for using this script: " "python fractals.py <int:depth_for_fractal>" ) snake_case_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor("red") snake_case_ : Tuple = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
644
0
import argparse import logging import os import sys import numpy as np import onnxruntime import torch from bart_onnx.generation_onnx import BARTBeamSearchGenerator from bart_onnx.reduce_onnx_size import remove_dup_initializers import transformers from transformers import BartForConditionalGeneration, BartTokenizer logging.basicConfig( format="%(asctime)s | %(levelname)s | %(name)s | [%(filename)s:%(lineno)d] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", level=os.environ.get("LOGLEVEL", "INFO").upper(), stream=sys.stdout, ) snake_case_ : Any = logging.getLogger(__name__) snake_case_ : Dict = {"facebook/bart-base": BartForConditionalGeneration} snake_case_ : Optional[Any] = {"facebook/bart-base": BartTokenizer} def lowerCamelCase_ ( ) -> Optional[int]: UpperCAmelCase_ : List[str] = argparse.ArgumentParser(description='''Export Bart model + Beam Search to ONNX graph.''' ) parser.add_argument( '''--validation_file''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''A csv or a json file containing the validation data.''' ) parser.add_argument( '''--max_length''', type=SCREAMING_SNAKE_CASE__, default=5, help='''The maximum total input sequence length after tokenization.''', ) parser.add_argument( '''--num_beams''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help=( '''Number of beams to use for evaluation. This argument will be ''' '''passed to ``model.generate``, which is used during ``evaluate`` and ``predict``.''' ), ) parser.add_argument( '''--model_name_or_path''', type=SCREAMING_SNAKE_CASE__, help='''Path to pretrained model or model identifier from huggingface.co/models.''', required=SCREAMING_SNAKE_CASE__, ) parser.add_argument( '''--config_name''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''Pretrained config name or path if not the same as model_name''', ) parser.add_argument( '''--device''', type=SCREAMING_SNAKE_CASE__, default='''cpu''', help='''Device where the model will be run''', ) parser.add_argument('''--output_file_path''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''Where to store the final ONNX file.''' ) UpperCAmelCase_ : Optional[int] = parser.parse_args() return args def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[Any], SCREAMING_SNAKE_CASE__ : Union[str, Any]="cpu" ) -> Tuple: UpperCAmelCase_ : Tuple = model_dict[model_name].from_pretrained(SCREAMING_SNAKE_CASE__ ).to(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[str] = tokenizer_dict[model_name].from_pretrained(SCREAMING_SNAKE_CASE__ ) if model_name in ["facebook/bart-base"]: UpperCAmelCase_ : Optional[Any] = 0 UpperCAmelCase_ : Any = None UpperCAmelCase_ : List[Any] = 0 return huggingface_model, tokenizer def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : Optional[int], SCREAMING_SNAKE_CASE__ : List[Any] ) -> Any: model.eval() UpperCAmelCase_ : Optional[Any] = None UpperCAmelCase_ : Union[str, Any] = torch.jit.script(BARTBeamSearchGenerator(SCREAMING_SNAKE_CASE__ ) ) with torch.no_grad(): UpperCAmelCase_ : Optional[Any] = '''My friends are cool but they eat too many carbs.''' UpperCAmelCase_ : List[str] = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors='''pt''' ).to(model.device ) UpperCAmelCase_ : Optional[int] = model.generate( inputs['''input_ids'''], attention_mask=inputs['''attention_mask'''], num_beams=SCREAMING_SNAKE_CASE__, max_length=SCREAMING_SNAKE_CASE__, early_stopping=SCREAMING_SNAKE_CASE__, decoder_start_token_id=model.config.decoder_start_token_id, ) torch.onnx.export( SCREAMING_SNAKE_CASE__, ( inputs['''input_ids'''], inputs['''attention_mask'''], num_beams, max_length, model.config.decoder_start_token_id, ), SCREAMING_SNAKE_CASE__, opset_version=14, input_names=['''input_ids''', '''attention_mask''', '''num_beams''', '''max_length''', '''decoder_start_token_id'''], output_names=['''output_ids'''], dynamic_axes={ '''input_ids''': {0: '''batch''', 1: '''seq'''}, '''output_ids''': {0: '''batch''', 1: '''seq_out'''}, }, example_outputs=SCREAMING_SNAKE_CASE__, ) logger.info('''Model exported to {}'''.format(SCREAMING_SNAKE_CASE__ ) ) UpperCAmelCase_ : Union[str, Any] = remove_dup_initializers(os.path.abspath(SCREAMING_SNAKE_CASE__ ) ) logger.info('''Deduplicated and optimized model written to {}'''.format(SCREAMING_SNAKE_CASE__ ) ) UpperCAmelCase_ : Dict = onnxruntime.InferenceSession(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[int] = ort_sess.run( SCREAMING_SNAKE_CASE__, { '''input_ids''': inputs['''input_ids'''].cpu().numpy(), '''attention_mask''': inputs['''attention_mask'''].cpu().numpy(), '''num_beams''': np.array(SCREAMING_SNAKE_CASE__ ), '''max_length''': np.array(SCREAMING_SNAKE_CASE__ ), '''decoder_start_token_id''': np.array(model.config.decoder_start_token_id ), }, ) np.testing.assert_allclose(summary_ids.cpu().numpy(), ort_out[0], rtol=1E-3, atol=1E-3 ) logger.info('''Model outputs from torch and ONNX Runtime are similar.''' ) logger.info('''Success.''' ) def lowerCamelCase_ ( ) -> Optional[Any]: UpperCAmelCase_ : List[Any] = parse_args() UpperCAmelCase_ : List[str] = 5 UpperCAmelCase_ : Optional[Any] = 4 # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) logger.setLevel(logging.INFO ) transformers.utils.logging.set_verbosity_error() UpperCAmelCase_ : Dict = torch.device(args.device ) UpperCAmelCase_ : Dict = load_model_tokenizer(args.model_name_or_path, SCREAMING_SNAKE_CASE__ ) if model.config.decoder_start_token_id is None: raise ValueError('''Make sure that `config.decoder_start_token_id` is correctly defined''' ) model.to(SCREAMING_SNAKE_CASE__ ) if args.max_length: UpperCAmelCase_ : Tuple = args.max_length if args.num_beams: UpperCAmelCase_ : Optional[int] = args.num_beams if args.output_file_path: UpperCAmelCase_ : Optional[int] = args.output_file_path else: UpperCAmelCase_ : Dict = '''BART.onnx''' logger.info('''Exporting model to ONNX''' ) export_and_validate_model(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
714
'''simple docstring''' import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device snake_case_ : List[str] = False class __a (unittest.TestCase ): pass @nightly @require_torch_gpu class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCAmelCase_ : Optional[int] = torch.manual_seed(0 ) UpperCAmelCase_ : Union[str, Any] = pipe.dual_guided( prompt='''first prompt''' , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__magic_name__ ) UpperCAmelCase_ : Optional[int] = VersatileDiffusionPipeline.from_pretrained(__magic_name__ , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Any = generator.manual_seed(0 ) UpperCAmelCase_ : Dict = pipe.dual_guided( prompt='''first prompt''' , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : str = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = '''cyberpunk 2077''' UpperCAmelCase_ : Union[str, Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCAmelCase_ : Tuple = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = pipe.dual_guided( prompt=__magic_name__ , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images UpperCAmelCase_ : List[str] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Union[str, Any] = np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 UpperCAmelCase_ : Tuple = '''A painting of a squirrel eating a burger ''' UpperCAmelCase_ : Optional[int] = torch.manual_seed(0 ) UpperCAmelCase_ : List[Any] = pipe.text_to_image( prompt=__magic_name__ , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images UpperCAmelCase_ : Tuple = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Any = np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 UpperCAmelCase_ : Tuple = pipe.image_variation(__magic_name__ , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Optional[Any] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : List[str] = np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
644
0
'''simple docstring''' from __future__ import annotations from scipy.special import comb # type: ignore class __a : def __init__( self : Tuple , __magic_name__ : list[tuple[float, float]] ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Dict = list_of_points # Degree determines the flexibility of the curve. # Degree = 1 will produce a straight line. UpperCAmelCase_ : List[str] = len(__magic_name__ ) - 1 def UpperCAmelCase__ ( self : Tuple , __magic_name__ : float ) -> list[float]: """simple docstring""" assert 0 <= t <= 1, "Time t must be between 0 and 1." UpperCAmelCase_ : list[float] = [] for i in range(len(self.list_of_points ) ): # basis function for each i output_values.append( comb(self.degree , __magic_name__ ) * ((1 - t) ** (self.degree - i)) * (t**i) ) # the basis must sum up to 1 for it to produce a valid Bezier curve. assert round(sum(__magic_name__ ) , 5 ) == 1 return output_values def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : float ) -> tuple[float, float]: """simple docstring""" assert 0 <= t <= 1, "Time t must be between 0 and 1." UpperCAmelCase_ : Any = self.basis_function(__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = 0.0 UpperCAmelCase_ : Tuple = 0.0 for i in range(len(self.list_of_points ) ): # For all points, sum up the product of i-th basis function and i-th point. x += basis_function[i] * self.list_of_points[i][0] y += basis_function[i] * self.list_of_points[i][1] return (x, y) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : float = 0.0_1 ) -> List[str]: """simple docstring""" from matplotlib import pyplot as plt # type: ignore UpperCAmelCase_ : list[float] = [] # x coordinates of points to plot UpperCAmelCase_ : list[float] = [] # y coordinates of points to plot UpperCAmelCase_ : int = 0.0 while t <= 1: UpperCAmelCase_ : str = self.bezier_curve_function(__magic_name__ ) to_plot_x.append(value[0] ) to_plot_y.append(value[1] ) t += step_size UpperCAmelCase_ : Any = [i[0] for i in self.list_of_points] UpperCAmelCase_ : Union[str, Any] = [i[1] for i in self.list_of_points] plt.plot( __magic_name__ , __magic_name__ , color='''blue''' , label='''Curve of Degree ''' + str(self.degree ) , ) plt.scatter(__magic_name__ , __magic_name__ , color='''red''' , label='''Control Points''' ) plt.legend() plt.show() if __name__ == "__main__": import doctest doctest.testmod() BezierCurve([(1, 2), (3, 5)]).plot_curve() # degree 1 BezierCurve([(0, 0), (5, 5), (5, 0)]).plot_curve() # degree 2 BezierCurve([(0, 0), (5, 5), (5, 0), (2.5, -2.5)]).plot_curve() # degree 3
715
'''simple docstring''' snake_case_ : int = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
644
0
'''simple docstring''' import math def lowerCamelCase_ ( ) -> None: UpperCAmelCase_ : Union[str, Any] = input('''Enter message: ''' ) UpperCAmelCase_ : List[str] = int(input(F"""Enter key [2-{len(SCREAMING_SNAKE_CASE__ ) - 1}]: """ ) ) UpperCAmelCase_ : Any = input('''Encryption/Decryption [e/d]: ''' ) if mode.lower().startswith('''e''' ): UpperCAmelCase_ : Optional[int] = encrypt_message(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) elif mode.lower().startswith('''d''' ): UpperCAmelCase_ : int = decrypt_message(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(F"""Output:\n{text + "|"}""" ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : str ) -> str: UpperCAmelCase_ : Optional[int] = [''''''] * key for col in range(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Optional[Any] = col while pointer < len(SCREAMING_SNAKE_CASE__ ): cipher_text[col] += message[pointer] pointer += key return "".join(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : str ) -> str: UpperCAmelCase_ : Union[str, Any] = math.ceil(len(SCREAMING_SNAKE_CASE__ ) / key ) UpperCAmelCase_ : int = key UpperCAmelCase_ : Optional[int] = (num_cols * num_rows) - len(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Any = [''''''] * num_cols UpperCAmelCase_ : str = 0 UpperCAmelCase_ : Optional[int] = 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) ): UpperCAmelCase_ : Any = 0 row += 1 return "".join(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod() main()
716
'''simple docstring''' import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __a (unittest.TestCase ): @property def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def UpperCAmelCase__ ( self : Dict ) -> Tuple: """simple docstring""" UpperCAmelCase_ : List[Any] = self.dummy_uncond_unet UpperCAmelCase_ : Dict = KarrasVeScheduler() UpperCAmelCase_ : Union[str, Any] = KarrasVePipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Dict = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[int] = pipe(num_inference_steps=2 , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Tuple = torch.manual_seed(0 ) UpperCAmelCase_ : str = pipe(num_inference_steps=2 , generator=__magic_name__ , output_type='''numpy''' , return_dict=__magic_name__ )[0] UpperCAmelCase_ : Union[str, Any] = image[0, -3:, -3:, -1] UpperCAmelCase_ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase_ : Dict = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : List[str] = '''google/ncsnpp-celebahq-256''' UpperCAmelCase_ : List[str] = UNetaDModel.from_pretrained(__magic_name__ ) UpperCAmelCase_ : List[Any] = KarrasVeScheduler() UpperCAmelCase_ : Any = KarrasVePipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Dict = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = pipe(num_inference_steps=20 , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) UpperCAmelCase_ : Optional[Any] = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
644
0
'''simple docstring''' from __future__ import annotations from collections import deque class __a : def __init__( self : List[Any] , __magic_name__ : list[str] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : list[dict] = [] self.adlist.append( {'''value''': '''''', '''next_states''': [], '''fail_state''': 0, '''output''': []} ) for keyword in keywords: self.add_keyword(__magic_name__ ) self.set_fail_transitions() def UpperCAmelCase__ ( self : str , __magic_name__ : int , __magic_name__ : 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 : Optional[int] , __magic_name__ : str ) -> None: """simple docstring""" UpperCAmelCase_ : Tuple = 0 for character in keyword: UpperCAmelCase_ : List[Any] = self.find_next_state(__magic_name__ , __magic_name__ ) 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 ) UpperCAmelCase_ : Optional[Any] = len(self.adlist ) - 1 else: UpperCAmelCase_ : Optional[Any] = next_state self.adlist[current_state]["output"].append(__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> None: """simple docstring""" UpperCAmelCase_ : deque = deque() for node in self.adlist[0]["next_states"]: q.append(__magic_name__ ) UpperCAmelCase_ : Any = 0 while q: UpperCAmelCase_ : str = q.popleft() for child in self.adlist[r]["next_states"]: q.append(__magic_name__ ) UpperCAmelCase_ : str = self.adlist[r]['''fail_state'''] while ( self.find_next_state(__magic_name__ , self.adlist[child]['''value'''] ) is None and state != 0 ): UpperCAmelCase_ : Tuple = self.adlist[state]['''fail_state'''] UpperCAmelCase_ : Union[str, Any] = self.find_next_state( __magic_name__ , self.adlist[child]['''value'''] ) if self.adlist[child]["fail_state"] is None: UpperCAmelCase_ : List[Any] = 0 UpperCAmelCase_ : Optional[Any] = ( self.adlist[child]['''output'''] + self.adlist[self.adlist[child]['''fail_state''']]['''output'''] ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : str ) -> dict[str, list[int]]: """simple docstring""" UpperCAmelCase_ : dict = {} # returns a dict with keywords and list of its occurrences UpperCAmelCase_ : Optional[Any] = 0 for i in range(len(__magic_name__ ) ): while ( self.find_next_state(__magic_name__ , string[i] ) is None and current_state != 0 ): UpperCAmelCase_ : Tuple = self.adlist[current_state]['''fail_state'''] UpperCAmelCase_ : List[Any] = self.find_next_state(__magic_name__ , string[i] ) if next_state is None: UpperCAmelCase_ : List[Any] = 0 else: UpperCAmelCase_ : Optional[int] = next_state for key in self.adlist[current_state]["output"]: if key not in result: UpperCAmelCase_ : Any = [] result[key].append(i - len(__magic_name__ ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
717
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class __a (lowerCamelCase ): __a : List[Any] = "openai/whisper-base" __a : Optional[Any] = ( "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the " "transcribed text." ) __a : Any = "transcriber" __a : str = WhisperProcessor __a : List[Any] = WhisperForConditionalGeneration __a : int = ["audio"] __a : Optional[Any] = ["text"] def UpperCAmelCase__ ( self : Dict , __magic_name__ : List[str] ) -> Optional[int]: """simple docstring""" return self.pre_processor(__magic_name__ , return_tensors='''pt''' ).input_features def UpperCAmelCase__ ( self : Dict , __magic_name__ : Dict ) -> Tuple: """simple docstring""" return self.model.generate(inputs=__magic_name__ ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Dict ) -> str: """simple docstring""" return self.pre_processor.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ )[0]
644
0
'''simple docstring''' import math import random from typing import Any from .hill_climbing import SearchProblem def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[Any], SCREAMING_SNAKE_CASE__ : bool = True, SCREAMING_SNAKE_CASE__ : float = math.inf, SCREAMING_SNAKE_CASE__ : float = -math.inf, SCREAMING_SNAKE_CASE__ : float = math.inf, SCREAMING_SNAKE_CASE__ : float = -math.inf, SCREAMING_SNAKE_CASE__ : bool = False, SCREAMING_SNAKE_CASE__ : float = 100, SCREAMING_SNAKE_CASE__ : float = 0.01, SCREAMING_SNAKE_CASE__ : float = 1, ) -> Any: UpperCAmelCase_ : Tuple = False UpperCAmelCase_ : Union[str, Any] = search_prob UpperCAmelCase_ : int = start_temperate UpperCAmelCase_ : Optional[Any] = [] UpperCAmelCase_ : Tuple = 0 UpperCAmelCase_ : int = None while not search_end: UpperCAmelCase_ : Optional[Any] = current_state.score() if best_state is None or current_score > best_state.score(): UpperCAmelCase_ : Union[str, Any] = current_state scores.append(SCREAMING_SNAKE_CASE__ ) iterations += 1 UpperCAmelCase_ : Optional[int] = None UpperCAmelCase_ : List[Any] = current_state.get_neighbors() while ( next_state is None and neighbors ): # till we do not find a neighbor that we can move to UpperCAmelCase_ : Optional[Any] = random.randint(0, len(SCREAMING_SNAKE_CASE__ ) - 1 ) # picking a random neighbor UpperCAmelCase_ : Optional[int] = neighbors.pop(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = picked_neighbor.score() - current_score if ( picked_neighbor.x > max_x or picked_neighbor.x < min_x or picked_neighbor.y > max_y or picked_neighbor.y < min_y ): continue # neighbor outside our bounds if not find_max: UpperCAmelCase_ : List[Any] = change * -1 # in case we are finding minimum if change > 0: # improves the solution UpperCAmelCase_ : Tuple = picked_neighbor else: UpperCAmelCase_ : List[Any] = (math.e) ** ( change / current_temp ) # probability generation function if random.random() < probability: # random number within probability UpperCAmelCase_ : str = picked_neighbor UpperCAmelCase_ : Union[str, Any] = current_temp - (current_temp * rate_of_decrease) if current_temp < threshold_temp or next_state is None: # temperature below threshold, or could not find a suitable neighbor UpperCAmelCase_ : Union[str, Any] = True else: UpperCAmelCase_ : Tuple = next_state if visualization: from matplotlib import pyplot as plt plt.plot(range(SCREAMING_SNAKE_CASE__ ), SCREAMING_SNAKE_CASE__ ) plt.xlabel('''Iterations''' ) plt.ylabel('''Function values''' ) plt.show() return best_state if __name__ == "__main__": def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : List[str] ) -> Tuple: return (x**2) + (y**2) # starting the problem with initial coordinates (12, 47) snake_case_ : Tuple = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) snake_case_ : List[Any] = simulated_annealing( prob, find_max=False, max_x=1_00, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The minimum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f'''and 50 > y > - 5 found via hill climbing: {local_min.score()}''' ) # starting the problem with initial coordinates (12, 47) snake_case_ : List[str] = SearchProblem(x=12, y=47, step_size=1, function_to_optimize=test_fa) snake_case_ : Tuple = simulated_annealing( prob, find_max=True, max_x=1_00, min_x=5, max_y=50, min_y=-5, visualization=True ) print( "The maximum score for f(x, y) = x^2 + y^2 with the domain 100 > x > 5 " f'''and 50 > y > - 5 found via hill climbing: {local_min.score()}''' ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[str]: return (3 * x**2) - (6 * y) snake_case_ : Dict = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) snake_case_ : str = simulated_annealing(prob, find_max=False, visualization=True) print( "The minimum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f'''{local_min.score()}''' ) snake_case_ : List[Any] = SearchProblem(x=3, y=4, step_size=1, function_to_optimize=test_fa) snake_case_ : Optional[int] = simulated_annealing(prob, find_max=True, visualization=True) print( "The maximum score for f(x, y) = 3*x^2 - 6*y found via hill climbing: " f'''{local_min.score()}''' )
718
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> int: return abs(SCREAMING_SNAKE_CASE__ ) if a == 0 else greatest_common_divisor(b % a, SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = y, x % y return abs(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( ) -> Optional[int]: try: UpperCAmelCase_ : Optional[Any] = input('''Enter two integers separated by comma (,): ''' ).split(''',''' ) UpperCAmelCase_ : Optional[int] = int(nums[0] ) UpperCAmelCase_ : List[Any] = int(nums[1] ) print( F"""greatest_common_divisor({num_a}, {num_a}) = """ F"""{greatest_common_divisor(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )}""" ) print(F"""By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )}""" ) except (IndexError, UnboundLocalError, ValueError): print('''Wrong input''' ) if __name__ == "__main__": main()
644
0
'''simple docstring''' import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": snake_case_ : List[Any] = pd.read_csv("sample_data.csv", header=None) snake_case_ : Optional[Any] = df.shape[:1][0] # If you're using some other dataset input the target column snake_case_ : Any = df.iloc[:, 1:2] snake_case_ : str = actual_data.values.reshape(len_data, 1) snake_case_ : Optional[Any] = MinMaxScaler().fit_transform(actual_data) snake_case_ : List[str] = 10 snake_case_ : Any = 5 snake_case_ : Any = 20 snake_case_ : Tuple = len_data - periods * look_back snake_case_ : str = actual_data[:division] snake_case_ : Optional[int] = actual_data[division - look_back :] snake_case_ : Any = [], [] snake_case_ : Union[str, Any] = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) snake_case_ : Any = np.array(train_x) snake_case_ : Optional[Any] = np.array(test_x) snake_case_ : Optional[Any] = np.array([list(i.ravel()) for i in train_y]) snake_case_ : List[str] = np.array([list(i.ravel()) for i in test_y]) snake_case_ : List[Any] = Sequential() model.add(LSTM(1_28, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(1_28, 1))) model.add(Dense(forward_days)) model.compile(loss="mean_squared_error", optimizer="adam") snake_case_ : Dict = model.fit( x_train, y_train, epochs=1_50, verbose=1, shuffle=True, batch_size=4 ) snake_case_ : Optional[Any] = model.predict(x_test)
719
'''simple docstring''' import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __a : def __init__( self : int , __magic_name__ : Optional[Any] , __magic_name__ : Any=13 , __magic_name__ : Any=7 , __magic_name__ : Union[str, Any]=True , __magic_name__ : Union[str, Any]=True , __magic_name__ : str=True , __magic_name__ : Optional[int]=True , __magic_name__ : List[Any]=99 , __magic_name__ : int=24 , __magic_name__ : Optional[int]=2 , __magic_name__ : Tuple=6 , __magic_name__ : Union[str, Any]=37 , __magic_name__ : Optional[Any]="gelu" , __magic_name__ : Any=0.1 , __magic_name__ : str=0.1 , __magic_name__ : Tuple=5_12 , __magic_name__ : Union[str, Any]=16 , __magic_name__ : Tuple=2 , __magic_name__ : Tuple=0.0_2 , __magic_name__ : Optional[Any]=3 , __magic_name__ : Optional[int]=None , __magic_name__ : Any=10_00 , ) -> str: """simple docstring""" UpperCAmelCase_ : Tuple = parent UpperCAmelCase_ : Optional[int] = batch_size UpperCAmelCase_ : List[str] = seq_length UpperCAmelCase_ : Dict = is_training UpperCAmelCase_ : List[str] = use_input_mask UpperCAmelCase_ : Any = use_token_type_ids UpperCAmelCase_ : Any = use_labels UpperCAmelCase_ : Any = vocab_size UpperCAmelCase_ : Dict = hidden_size UpperCAmelCase_ : Tuple = num_hidden_layers UpperCAmelCase_ : Tuple = num_attention_heads UpperCAmelCase_ : int = intermediate_size UpperCAmelCase_ : Union[str, Any] = hidden_act UpperCAmelCase_ : Optional[int] = hidden_dropout_prob UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase_ : Union[str, Any] = max_position_embeddings UpperCAmelCase_ : int = type_vocab_size UpperCAmelCase_ : List[Any] = type_sequence_label_size UpperCAmelCase_ : int = initializer_range UpperCAmelCase_ : Dict = num_labels UpperCAmelCase_ : List[str] = scope UpperCAmelCase_ : List[str] = range_bbox def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCAmelCase_ : List[str] = bbox[i, j, 3] UpperCAmelCase_ : Dict = bbox[i, j, 1] UpperCAmelCase_ : Optional[Any] = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCAmelCase_ : List[str] = bbox[i, j, 2] UpperCAmelCase_ : Tuple = bbox[i, j, 0] UpperCAmelCase_ : Union[str, Any] = t UpperCAmelCase_ : int = None if self.use_input_mask: UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCAmelCase_ : Optional[int] = None if self.use_token_type_ids: UpperCAmelCase_ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Dict = None UpperCAmelCase_ : Tuple = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : int = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : int , ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = LiltModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Optional[Any] = model(__magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : List[Any] = model(__magic_name__ , bbox=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : Optional[int] = model(__magic_name__ , bbox=__magic_name__ ) 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 : int , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[int] , __magic_name__ : List[Any] , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Any = self.num_labels UpperCAmelCase_ : List[Any] = LiltForTokenClassification(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : List[Any] = model( __magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : int , __magic_name__ : Tuple , __magic_name__ : Any , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : str = LiltForQuestionAnswering(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Optional[Any] = model( __magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , start_positions=__magic_name__ , end_positions=__magic_name__ , ) 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 : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : Optional[int] = config_and_inputs UpperCAmelCase_ : Tuple = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class __a (lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : Tuple = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __a : Any = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __a : Union[str, Any] = False __a : int = False def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : int ) -> str: """simple docstring""" return True def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = LiltModelTester(self ) UpperCAmelCase_ : List[Any] = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ : Tuple = type self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @slow def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Optional[int] = LiltModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) @require_torch @slow class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" UpperCAmelCase_ : str = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''' ).to(__magic_name__ ) UpperCAmelCase_ : Any = torch.tensor([[1, 2]] , device=__magic_name__ ) UpperCAmelCase_ : int = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=__magic_name__ ) # forward pass with torch.no_grad(): UpperCAmelCase_ : Optional[int] = model(input_ids=__magic_name__ , bbox=__magic_name__ ) UpperCAmelCase_ : int = torch.Size([1, 2, 7_68] ) UpperCAmelCase_ : List[str] = torch.tensor( [[-0.0_6_5_3, 0.0_9_5_0, -0.0_0_6_1], [-0.0_5_4_5, 0.0_9_2_6, -0.0_3_2_4]] , device=__magic_name__ , ) self.assertTrue(outputs.last_hidden_state.shape , __magic_name__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , __magic_name__ , atol=1E-3 ) )
644
0
import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() snake_case_ : List[str] = logging.get_logger(__name__) snake_case_ : List[Any] = { "b0": efficientnet.EfficientNetBa, "b1": efficientnet.EfficientNetBa, "b2": efficientnet.EfficientNetBa, "b3": efficientnet.EfficientNetBa, "b4": efficientnet.EfficientNetBa, "b5": efficientnet.EfficientNetBa, "b6": efficientnet.EfficientNetBa, "b7": efficientnet.EfficientNetBa, } snake_case_ : Optional[Any] = { "b0": { "hidden_dim": 12_80, "width_coef": 1.0, "depth_coef": 1.0, "image_size": 2_24, "dropout_rate": 0.2, "dw_padding": [], }, "b1": { "hidden_dim": 12_80, "width_coef": 1.0, "depth_coef": 1.1, "image_size": 2_40, "dropout_rate": 0.2, "dw_padding": [16], }, "b2": { "hidden_dim": 14_08, "width_coef": 1.1, "depth_coef": 1.2, "image_size": 2_60, "dropout_rate": 0.3, "dw_padding": [5, 8, 16], }, "b3": { "hidden_dim": 15_36, "width_coef": 1.2, "depth_coef": 1.4, "image_size": 3_00, "dropout_rate": 0.3, "dw_padding": [5, 18], }, "b4": { "hidden_dim": 17_92, "width_coef": 1.4, "depth_coef": 1.8, "image_size": 3_80, "dropout_rate": 0.4, "dw_padding": [6], }, "b5": { "hidden_dim": 20_48, "width_coef": 1.6, "depth_coef": 2.2, "image_size": 4_56, "dropout_rate": 0.4, "dw_padding": [13, 27], }, "b6": { "hidden_dim": 23_04, "width_coef": 1.8, "depth_coef": 2.6, "image_size": 5_28, "dropout_rate": 0.5, "dw_padding": [31], }, "b7": { "hidden_dim": 25_60, "width_coef": 2.0, "depth_coef": 3.1, "image_size": 6_00, "dropout_rate": 0.5, "dw_padding": [18], }, } def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str ) -> Dict: UpperCAmelCase_ : int = EfficientNetConfig() UpperCAmelCase_ : str = CONFIG_MAP[model_name]['''hidden_dim'''] UpperCAmelCase_ : Any = CONFIG_MAP[model_name]['''width_coef'''] UpperCAmelCase_ : Tuple = CONFIG_MAP[model_name]['''depth_coef'''] UpperCAmelCase_ : List[Any] = CONFIG_MAP[model_name]['''image_size'''] UpperCAmelCase_ : int = CONFIG_MAP[model_name]['''dropout_rate'''] UpperCAmelCase_ : Optional[int] = CONFIG_MAP[model_name]['''dw_padding'''] UpperCAmelCase_ : int = '''huggingface/label-files''' UpperCAmelCase_ : Dict = '''imagenet-1k-id2label.json''' UpperCAmelCase_ : Union[str, Any] = 1000 UpperCAmelCase_ : Tuple = json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, repo_type='''dataset''' ), '''r''' ) ) UpperCAmelCase_ : str = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} UpperCAmelCase_ : Any = idalabel UpperCAmelCase_ : List[str] = {v: k for k, v in idalabel.items()} return config def lowerCamelCase_ ( ) -> Optional[Any]: UpperCAmelCase_ : Optional[int] = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCAmelCase_ : List[Any] = Image.open(requests.get(SCREAMING_SNAKE_CASE__, stream=SCREAMING_SNAKE_CASE__ ).raw ) return im def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[int] ) -> List[str]: UpperCAmelCase_ : Optional[Any] = CONFIG_MAP[model_name]['''image_size'''] UpperCAmelCase_ : str = EfficientNetImageProcessor( size={'''height''': size, '''width''': size}, image_mean=[0.4_85, 0.4_56, 0.4_06], image_std=[0.47_85_39_44, 0.4_73_28_64, 0.47_43_41_63], do_center_crop=SCREAMING_SNAKE_CASE__, ) return preprocessor def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int ) -> Tuple: UpperCAmelCase_ : Dict = [v.split('''_''' )[0].split('''block''' )[1] for v in original_param_names if v.startswith('''block''' )] UpperCAmelCase_ : Optional[int] = sorted(set(SCREAMING_SNAKE_CASE__ ) ) UpperCAmelCase_ : Union[str, Any] = len(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : str = {b: str(SCREAMING_SNAKE_CASE__ ) for b, i in zip(SCREAMING_SNAKE_CASE__, range(SCREAMING_SNAKE_CASE__ ) )} UpperCAmelCase_ : Optional[int] = [] rename_keys.append(('''stem_conv/kernel:0''', '''embeddings.convolution.weight''') ) rename_keys.append(('''stem_bn/gamma:0''', '''embeddings.batchnorm.weight''') ) rename_keys.append(('''stem_bn/beta:0''', '''embeddings.batchnorm.bias''') ) rename_keys.append(('''stem_bn/moving_mean:0''', '''embeddings.batchnorm.running_mean''') ) rename_keys.append(('''stem_bn/moving_variance:0''', '''embeddings.batchnorm.running_var''') ) for b in block_names: UpperCAmelCase_ : Union[str, Any] = block_name_mapping[b] rename_keys.append((F"""block{b}_expand_conv/kernel:0""", F"""encoder.blocks.{hf_b}.expansion.expand_conv.weight""") ) rename_keys.append((F"""block{b}_expand_bn/gamma:0""", F"""encoder.blocks.{hf_b}.expansion.expand_bn.weight""") ) rename_keys.append((F"""block{b}_expand_bn/beta:0""", F"""encoder.blocks.{hf_b}.expansion.expand_bn.bias""") ) rename_keys.append( (F"""block{b}_expand_bn/moving_mean:0""", F"""encoder.blocks.{hf_b}.expansion.expand_bn.running_mean""") ) rename_keys.append( (F"""block{b}_expand_bn/moving_variance:0""", F"""encoder.blocks.{hf_b}.expansion.expand_bn.running_var""") ) rename_keys.append( (F"""block{b}_dwconv/depthwise_kernel:0""", F"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight""") ) rename_keys.append((F"""block{b}_bn/gamma:0""", F"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight""") ) rename_keys.append((F"""block{b}_bn/beta:0""", F"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias""") ) rename_keys.append( (F"""block{b}_bn/moving_mean:0""", F"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean""") ) rename_keys.append( (F"""block{b}_bn/moving_variance:0""", F"""encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var""") ) rename_keys.append((F"""block{b}_se_reduce/kernel:0""", F"""encoder.blocks.{hf_b}.squeeze_excite.reduce.weight""") ) rename_keys.append((F"""block{b}_se_reduce/bias:0""", F"""encoder.blocks.{hf_b}.squeeze_excite.reduce.bias""") ) rename_keys.append((F"""block{b}_se_expand/kernel:0""", F"""encoder.blocks.{hf_b}.squeeze_excite.expand.weight""") ) rename_keys.append((F"""block{b}_se_expand/bias:0""", F"""encoder.blocks.{hf_b}.squeeze_excite.expand.bias""") ) rename_keys.append( (F"""block{b}_project_conv/kernel:0""", F"""encoder.blocks.{hf_b}.projection.project_conv.weight""") ) rename_keys.append((F"""block{b}_project_bn/gamma:0""", F"""encoder.blocks.{hf_b}.projection.project_bn.weight""") ) rename_keys.append((F"""block{b}_project_bn/beta:0""", F"""encoder.blocks.{hf_b}.projection.project_bn.bias""") ) rename_keys.append( (F"""block{b}_project_bn/moving_mean:0""", F"""encoder.blocks.{hf_b}.projection.project_bn.running_mean""") ) rename_keys.append( (F"""block{b}_project_bn/moving_variance:0""", F"""encoder.blocks.{hf_b}.projection.project_bn.running_var""") ) rename_keys.append(('''top_conv/kernel:0''', '''encoder.top_conv.weight''') ) rename_keys.append(('''top_bn/gamma:0''', '''encoder.top_bn.weight''') ) rename_keys.append(('''top_bn/beta:0''', '''encoder.top_bn.bias''') ) rename_keys.append(('''top_bn/moving_mean:0''', '''encoder.top_bn.running_mean''') ) rename_keys.append(('''top_bn/moving_variance:0''', '''encoder.top_bn.running_var''') ) UpperCAmelCase_ : Optional[int] = {} for item in rename_keys: if item[0] in original_param_names: UpperCAmelCase_ : Optional[int] = '''efficientnet.''' + item[1] UpperCAmelCase_ : Any = '''classifier.weight''' UpperCAmelCase_ : Dict = '''classifier.bias''' return key_mapping def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]: for key, value in tf_params.items(): if "normalization" in key: continue UpperCAmelCase_ : List[str] = key_mapping[key] if "_conv" in key and "kernel" in key: UpperCAmelCase_ : Union[str, Any] = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).permute(3, 2, 0, 1 ) elif "depthwise_kernel" in key: UpperCAmelCase_ : Tuple = torch.from_numpy(SCREAMING_SNAKE_CASE__ ).permute(2, 3, 0, 1 ) elif "kernel" in key: UpperCAmelCase_ : str = torch.from_numpy(np.transpose(SCREAMING_SNAKE_CASE__ ) ) else: UpperCAmelCase_ : Tuple = torch.from_numpy(SCREAMING_SNAKE_CASE__ ) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(SCREAMING_SNAKE_CASE__ ) @torch.no_grad() def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[Any], SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: UpperCAmelCase_ : Optional[Any] = model_classes[model_name]( include_top=SCREAMING_SNAKE_CASE__, weights='''imagenet''', input_tensor=SCREAMING_SNAKE_CASE__, input_shape=SCREAMING_SNAKE_CASE__, pooling=SCREAMING_SNAKE_CASE__, classes=1000, classifier_activation='''softmax''', ) UpperCAmelCase_ : int = original_model.trainable_variables UpperCAmelCase_ : List[Any] = original_model.non_trainable_variables UpperCAmelCase_ : Tuple = {param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: UpperCAmelCase_ : Dict = param.numpy() UpperCAmelCase_ : Dict = list(tf_params.keys() ) # Load HuggingFace model UpperCAmelCase_ : str = get_efficientnet_config(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[int] = EfficientNetForImageClassification(SCREAMING_SNAKE_CASE__ ).eval() UpperCAmelCase_ : Optional[int] = hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print('''Converting parameters...''' ) UpperCAmelCase_ : List[Any] = rename_keys(SCREAMING_SNAKE_CASE__ ) replace_params(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # Initialize preprocessor and preprocess input image UpperCAmelCase_ : Optional[Any] = convert_image_processor(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Union[str, Any] = preprocessor(images=prepare_img(), return_tensors='''pt''' ) # HF model inference hf_model.eval() with torch.no_grad(): UpperCAmelCase_ : str = hf_model(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Dict = outputs.logits.detach().numpy() # Original model inference UpperCAmelCase_ : List[str] = False UpperCAmelCase_ : Union[str, Any] = CONFIG_MAP[model_name]['''image_size'''] UpperCAmelCase_ : str = prepare_img().resize((image_size, image_size), resample=PIL.Image.NEAREST ) UpperCAmelCase_ : Union[str, Any] = image.img_to_array(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[Any] = np.expand_dims(SCREAMING_SNAKE_CASE__, axis=0 ) UpperCAmelCase_ : Optional[int] = original_model.predict(SCREAMING_SNAKE_CASE__ ) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, atol=1E-3 ), "The predicted logits are not the same." print('''Model outputs match!''' ) if save_model: # Create folder to save model if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): os.mkdir(SCREAMING_SNAKE_CASE__ ) # Save converted model and image processor hf_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) preprocessor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if push_to_hub: # Push model and image processor to hub print(F"""Pushing converted {model_name} to the hub...""" ) UpperCAmelCase_ : List[str] = F"""efficientnet-{model_name}""" preprocessor.push_to_hub(SCREAMING_SNAKE_CASE__ ) hf_model.push_to_hub(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": snake_case_ : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="b0", type=str, help="Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].", ) parser.add_argument( "--pytorch_dump_folder_path", default="hf_model", type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument("--save_model", action="store_true", help="Save model to local") parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub") snake_case_ : List[Any] = parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
720
'''simple docstring''' import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging snake_case_ : str = logging.get_logger(__name__) snake_case_ : int = "▁" snake_case_ : str = {"vocab_file": "vocab.txt", "sentencepiece_model_ckpt": "sentencepiece.bpe.model"} snake_case_ : int = { "sentencepiece_model_file": "sentencepiece.bpe.model", "vocab_file": "vocab.txt", } snake_case_ : Optional[Any] = { "vocab_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", }, "sentencepiece_model_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", }, } snake_case_ : Dict = { "ernie-m-base": 5_14, "ernie-m-large": 5_14, } snake_case_ : Any = { "ernie-m-base": {"do_lower_case": False}, "ernie-m-large": {"do_lower_case": False}, } class __a (lowerCamelCase ): __a : List[str] = ["input_ids"] __a : Union[str, Any] = VOCAB_FILES_NAMES __a : Tuple = PRETRAINED_INIT_CONFIGURATION __a : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a : Optional[int] = PRETRAINED_VOCAB_FILES_MAP __a : Union[str, Any] = RESOURCE_FILES_NAMES def __init__( self : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : int=None , __magic_name__ : str=False , __magic_name__ : int="utf8" , __magic_name__ : Optional[int]="[UNK]" , __magic_name__ : Dict="[SEP]" , __magic_name__ : List[Any]="[PAD]" , __magic_name__ : str="[CLS]" , __magic_name__ : Optional[int]="[MASK]" , __magic_name__ : Optional[Dict[str, Any]] = None , **__magic_name__ : Union[str, Any] , ) -> None: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. UpperCAmelCase_ : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , pad_token=__magic_name__ , cls_token=__magic_name__ , mask_token=__magic_name__ , vocab_file=__magic_name__ , encoding=__magic_name__ , sp_model_kwargs=self.sp_model_kwargs , **__magic_name__ , ) UpperCAmelCase_ : Optional[Any] = do_lower_case UpperCAmelCase_ : List[str] = sentencepiece_model_ckpt UpperCAmelCase_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__magic_name__ ) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: UpperCAmelCase_ : List[Any] = self.load_vocab(filepath=__magic_name__ ) else: UpperCAmelCase_ : str = {self.sp_model.id_to_piece(__magic_name__ ): id for id in range(self.sp_model.get_piece_size() )} UpperCAmelCase_ : int = {v: k for k, v in self.vocab.items()} def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Any ) -> Any: """simple docstring""" if text is None: return None UpperCAmelCase_ : str = self.tokenize(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ : str = '''''', [] for i, ch in enumerate(__magic_name__ ): if ch in self.SP_CHAR_MAPPING: UpperCAmelCase_ : Optional[int] = self.SP_CHAR_MAPPING.get(__magic_name__ ) else: UpperCAmelCase_ : Union[str, Any] = unicodedata.normalize('''NFKC''' , __magic_name__ ) if self.is_whitespace(__magic_name__ ): continue normalized_text += ch char_mapping.extend([i] * len(__magic_name__ ) ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = normalized_text, [], 0 if self.do_lower_case: UpperCAmelCase_ : Optional[int] = text.lower() for token in split_tokens: if token[:1] == "▁": UpperCAmelCase_ : Tuple = token[1:] UpperCAmelCase_ : int = text[offset:].index(__magic_name__ ) + offset UpperCAmelCase_ : Optional[int] = start + len(__magic_name__ ) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) ) UpperCAmelCase_ : int = end return token_mapping @property def UpperCAmelCase__ ( self : Any ) -> Any: """simple docstring""" return len(self.vocab ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def __getstate__( self : str ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.__dict__.copy() UpperCAmelCase_ : Optional[Any] = None return state def __setstate__( self : str , __magic_name__ : Any ) -> Dict: """simple docstring""" UpperCAmelCase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): UpperCAmelCase_ : int = {} UpperCAmelCase_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.sentencepiece_model_ckpt ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Any ) -> List[str]: """simple docstring""" return "".join((self.SP_CHAR_MAPPING.get(__magic_name__ , __magic_name__ ) for c in text) ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Tuple , __magic_name__ : Any=False , __magic_name__ : List[str]=64 , __magic_name__ : List[str]=0.1 ) -> List[str]: """simple docstring""" if self.sp_model_kwargs.get('''enable_sampling''' ) is True: UpperCAmelCase_ : Dict = True if self.sp_model_kwargs.get('''alpha''' ) is not None: UpperCAmelCase_ : Union[str, Any] = self.sp_model_kwargs.get('''alpha''' ) if self.sp_model_kwargs.get('''nbest_size''' ) is not None: UpperCAmelCase_ : Any = self.sp_model_kwargs.get('''nbest_size''' ) if not enable_sampling: UpperCAmelCase_ : Dict = self.sp_model.EncodeAsPieces(__magic_name__ ) else: UpperCAmelCase_ : Dict = self.sp_model.SampleEncodeAsPieces(__magic_name__ , __magic_name__ , __magic_name__ ) UpperCAmelCase_ : List[Any] = [] for pi, piece in enumerate(__magic_name__ ): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(__magic_name__ ) and pi != 0: new_pieces.append(__magic_name__ ) continue else: continue UpperCAmelCase_ : List[str] = 0 for i, chunk in enumerate(__magic_name__ ): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(__magic_name__ ) or self.is_punct(__magic_name__ ): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) new_pieces.append(__magic_name__ ) UpperCAmelCase_ : List[Any] = i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) UpperCAmelCase_ : List[str] = i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) UpperCAmelCase_ : str = i if len(__magic_name__ ) > lst_i: new_pieces.append(piece[lst_i:] ) return new_pieces def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Optional[int] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = ''''''.join(__magic_name__ ).replace(__magic_name__ , ''' ''' ).strip() return out_string def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, Any] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : str = self.convert_ids_to_tokens(__magic_name__ ) UpperCAmelCase_ : Optional[Any] = ''''''.join(__magic_name__ ).replace(__magic_name__ , ''' ''' ).strip() return out_string def UpperCAmelCase__ ( self : str , __magic_name__ : Optional[Any] ) -> List[Any]: """simple docstring""" return self.vocab.get(__magic_name__ , self.vocab.get(self.unk_token ) ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.reverse_vocab.get(__magic_name__ , self.unk_token ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Any , __magic_name__ : Union[str, Any]=None ) -> Any: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase_ : Union[str, Any] = [self.cls_token_id] UpperCAmelCase_ : List[Any] = [self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def UpperCAmelCase__ ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : List[str]=None ) -> int: """simple docstring""" if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def UpperCAmelCase__ ( self : Dict , __magic_name__ : Optional[Any] , __magic_name__ : List[str]=None , __magic_name__ : Optional[Any]=False ) -> Optional[int]: """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__magic_name__ )) + [1, 1] + ([0] * len(__magic_name__ )) + [1] return [1] + ([0] * len(__magic_name__ )) + [1] def UpperCAmelCase__ ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method if token_ids_a is None: # [CLS] X [SEP] return (len(__magic_name__ ) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(__magic_name__ ) + 1) + [1] * (len(__magic_name__ ) + 3) def UpperCAmelCase__ ( self : Dict , __magic_name__ : str ) -> Tuple: """simple docstring""" if "\u4e00" <= char <= "\u9fff": return True return False def UpperCAmelCase__ ( self : int , __magic_name__ : Optional[int] ) -> str: """simple docstring""" if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def UpperCAmelCase__ ( self : int , __magic_name__ : Optional[Any] ) -> Dict: """simple docstring""" if char in ",;:.?!~,;:。?!《》【】": return True return False def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Any ) -> Union[str, Any]: """simple docstring""" if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(__magic_name__ ) == 1: UpperCAmelCase_ : Optional[Any] = unicodedata.category(__magic_name__ ) if cat == "Zs": return True return False def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : Tuple ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[Any] = {} with io.open(__magic_name__ , '''r''' , encoding='''utf-8''' ) as f: for index, line in enumerate(__magic_name__ ): UpperCAmelCase_ : List[Any] = line.rstrip('''\n''' ) UpperCAmelCase_ : Dict = int(__magic_name__ ) return token_to_idx def UpperCAmelCase__ ( self : Dict , __magic_name__ : str , __magic_name__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = 0 if os.path.isdir(__magic_name__ ): UpperCAmelCase_ : Any = os.path.join( __magic_name__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) else: UpperCAmelCase_ : List[str] = (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory with open(__magic_name__ , '''w''' , encoding='''utf-8''' ) as writer: for token, token_index in sorted(self.vocab.items() , key=lambda __magic_name__ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ''' Please check that the vocabulary is not corrupted!''' ) UpperCAmelCase_ : Dict = token_index writer.write(token + '''\n''' ) index += 1 UpperCAmelCase_ : Union[str, Any] = os.path.join(__magic_name__ , '''sentencepiece.bpe.model''' ) with open(__magic_name__ , '''wb''' ) as fi: UpperCAmelCase_ : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (vocab_file,)
644
0
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_download, hf_hub_url from PIL import Image from transformers import DetaConfig, DetaForObjectDetection, DetaImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() snake_case_ : List[Any] = logging.get_logger(__name__) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict ) -> Any: UpperCAmelCase_ : Optional[int] = SwinConfig( embed_dim=192, depths=(2, 2, 18, 2), num_heads=(6, 12, 24, 48), window_size=12, out_features=['''stage2''', '''stage3''', '''stage4'''], ) UpperCAmelCase_ : Optional[int] = DetaConfig( backbone_config=SCREAMING_SNAKE_CASE__, num_queries=900, encoder_ffn_dim=2048, decoder_ffn_dim=2048, num_feature_levels=5, assign_first_stage=SCREAMING_SNAKE_CASE__, with_box_refine=SCREAMING_SNAKE_CASE__, two_stage=SCREAMING_SNAKE_CASE__, ) # set labels UpperCAmelCase_ : Any = '''huggingface/label-files''' if "o365" in model_name: UpperCAmelCase_ : List[Any] = 366 UpperCAmelCase_ : Any = '''object365-id2label.json''' else: UpperCAmelCase_ : List[Any] = 91 UpperCAmelCase_ : List[str] = '''coco-detection-id2label.json''' UpperCAmelCase_ : Dict = num_labels UpperCAmelCase_ : Optional[Any] = json.load(open(cached_download(hf_hub_url(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, repo_type='''dataset''' ) ), '''r''' ) ) UpperCAmelCase_ : int = {int(SCREAMING_SNAKE_CASE__ ): v for k, v in idalabel.items()} UpperCAmelCase_ : Any = idalabel UpperCAmelCase_ : Tuple = {v: k for k, v in idalabel.items()} return config def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[int]: UpperCAmelCase_ : List[Any] = [] # stem # fmt: off rename_keys.append(('''backbone.0.body.patch_embed.proj.weight''', '''model.backbone.model.embeddings.patch_embeddings.projection.weight''') ) rename_keys.append(('''backbone.0.body.patch_embed.proj.bias''', '''model.backbone.model.embeddings.patch_embeddings.projection.bias''') ) rename_keys.append(('''backbone.0.body.patch_embed.norm.weight''', '''model.backbone.model.embeddings.norm.weight''') ) rename_keys.append(('''backbone.0.body.patch_embed.norm.bias''', '''model.backbone.model.embeddings.norm.bias''') ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.norm1.weight""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.norm1.bias""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_bias_table""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.attn.relative_position_index""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.attn.proj.weight""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.attn.proj.bias""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.norm2.weight""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.norm2.bias""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.weight""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc1.bias""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.weight""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.weight""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.blocks.{j}.mlp.fc2.bias""", F"""model.backbone.model.encoder.layers.{i}.blocks.{j}.output.dense.bias""") ) if i < 3: rename_keys.append((F"""backbone.0.body.layers.{i}.downsample.reduction.weight""", F"""model.backbone.model.encoder.layers.{i}.downsample.reduction.weight""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.downsample.norm.weight""", F"""model.backbone.model.encoder.layers.{i}.downsample.norm.weight""") ) rename_keys.append((F"""backbone.0.body.layers.{i}.downsample.norm.bias""", F"""model.backbone.model.encoder.layers.{i}.downsample.norm.bias""") ) rename_keys.append(('''backbone.0.body.norm1.weight''', '''model.backbone.model.hidden_states_norms.stage2.weight''') ) rename_keys.append(('''backbone.0.body.norm1.bias''', '''model.backbone.model.hidden_states_norms.stage2.bias''') ) rename_keys.append(('''backbone.0.body.norm2.weight''', '''model.backbone.model.hidden_states_norms.stage3.weight''') ) rename_keys.append(('''backbone.0.body.norm2.bias''', '''model.backbone.model.hidden_states_norms.stage3.bias''') ) rename_keys.append(('''backbone.0.body.norm3.weight''', '''model.backbone.model.hidden_states_norms.stage4.weight''') ) rename_keys.append(('''backbone.0.body.norm3.bias''', '''model.backbone.model.hidden_states_norms.stage4.bias''') ) # transformer encoder for i in range(config.encoder_layers ): rename_keys.append((F"""transformer.encoder.layers.{i}.self_attn.sampling_offsets.weight""", F"""model.encoder.layers.{i}.self_attn.sampling_offsets.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.self_attn.sampling_offsets.bias""", F"""model.encoder.layers.{i}.self_attn.sampling_offsets.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.self_attn.attention_weights.weight""", F"""model.encoder.layers.{i}.self_attn.attention_weights.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.self_attn.attention_weights.bias""", F"""model.encoder.layers.{i}.self_attn.attention_weights.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.self_attn.value_proj.weight""", F"""model.encoder.layers.{i}.self_attn.value_proj.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.self_attn.value_proj.bias""", F"""model.encoder.layers.{i}.self_attn.value_proj.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.self_attn.output_proj.weight""", F"""model.encoder.layers.{i}.self_attn.output_proj.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.self_attn.output_proj.bias""", F"""model.encoder.layers.{i}.self_attn.output_proj.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.norm1.weight""", F"""model.encoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.norm1.bias""", F"""model.encoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.weight""", F"""model.encoder.layers.{i}.fc1.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.linear1.bias""", F"""model.encoder.layers.{i}.fc1.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.weight""", F"""model.encoder.layers.{i}.fc2.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.linear2.bias""", F"""model.encoder.layers.{i}.fc2.bias""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.weight""", F"""model.encoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((F"""transformer.encoder.layers.{i}.norm2.bias""", F"""model.encoder.layers.{i}.final_layer_norm.bias""") ) # transformer decoder for i in range(config.decoder_layers ): rename_keys.append((F"""transformer.decoder.layers.{i}.cross_attn.sampling_offsets.weight""", F"""model.decoder.layers.{i}.encoder_attn.sampling_offsets.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.cross_attn.sampling_offsets.bias""", F"""model.decoder.layers.{i}.encoder_attn.sampling_offsets.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.cross_attn.attention_weights.weight""", F"""model.decoder.layers.{i}.encoder_attn.attention_weights.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.cross_attn.attention_weights.bias""", F"""model.decoder.layers.{i}.encoder_attn.attention_weights.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.cross_attn.value_proj.weight""", F"""model.decoder.layers.{i}.encoder_attn.value_proj.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.cross_attn.value_proj.bias""", F"""model.decoder.layers.{i}.encoder_attn.value_proj.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.cross_attn.output_proj.weight""", F"""model.decoder.layers.{i}.encoder_attn.output_proj.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.cross_attn.output_proj.bias""", F"""model.decoder.layers.{i}.encoder_attn.output_proj.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm1.weight""", F"""model.decoder.layers.{i}.encoder_attn_layer_norm.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm1.bias""", F"""model.decoder.layers.{i}.encoder_attn_layer_norm.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.self_attn.out_proj.weight""", F"""model.decoder.layers.{i}.self_attn.out_proj.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.self_attn.out_proj.bias""", F"""model.decoder.layers.{i}.self_attn.out_proj.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm2.weight""", F"""model.decoder.layers.{i}.self_attn_layer_norm.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm2.bias""", F"""model.decoder.layers.{i}.self_attn_layer_norm.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.weight""", F"""model.decoder.layers.{i}.fc1.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.linear1.bias""", F"""model.decoder.layers.{i}.fc1.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.weight""", F"""model.decoder.layers.{i}.fc2.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.linear2.bias""", F"""model.decoder.layers.{i}.fc2.bias""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.weight""", F"""model.decoder.layers.{i}.final_layer_norm.weight""") ) rename_keys.append((F"""transformer.decoder.layers.{i}.norm3.bias""", F"""model.decoder.layers.{i}.final_layer_norm.bias""") ) # fmt: on return rename_keys def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : List[Any], SCREAMING_SNAKE_CASE__ : int ) -> Dict: UpperCAmelCase_ : str = dct.pop(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = val def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: UpperCAmelCase_ : List[Any] = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): UpperCAmelCase_ : str = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) UpperCAmelCase_ : Union[str, Any] = state_dict.pop(F"""backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.weight""" ) UpperCAmelCase_ : str = state_dict.pop(F"""backbone.0.body.layers.{i}.blocks.{j}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase_ : Optional[int] = in_proj_weight[:dim, :] UpperCAmelCase_ : List[str] = in_proj_bias[: dim] UpperCAmelCase_ : int = in_proj_weight[ dim : dim * 2, : ] UpperCAmelCase_ : Optional[Any] = in_proj_bias[ dim : dim * 2 ] UpperCAmelCase_ : List[str] = in_proj_weight[ -dim :, : ] UpperCAmelCase_ : Dict = in_proj_bias[-dim :] # fmt: on def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : List[Any] ) -> Any: # transformer decoder self-attention layers UpperCAmelCase_ : List[Any] = config.d_model for i in range(config.decoder_layers ): # read in weights + bias of input projection layer of self-attention UpperCAmelCase_ : List[str] = state_dict.pop(F"""transformer.decoder.layers.{i}.self_attn.in_proj_weight""" ) UpperCAmelCase_ : List[str] = state_dict.pop(F"""transformer.decoder.layers.{i}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase_ : str = in_proj_weight[:hidden_size, :] UpperCAmelCase_ : Tuple = in_proj_bias[:hidden_size] UpperCAmelCase_ : Any = in_proj_weight[ hidden_size : hidden_size * 2, : ] UpperCAmelCase_ : Optional[int] = in_proj_bias[hidden_size : hidden_size * 2] UpperCAmelCase_ : Optional[Any] = in_proj_weight[-hidden_size:, :] UpperCAmelCase_ : List[Any] = in_proj_bias[-hidden_size:] def lowerCamelCase_ ( ) -> Any: UpperCAmelCase_ : Any = '''http://images.cocodataset.org/val2017/000000039769.jpg''' UpperCAmelCase_ : Any = Image.open(requests.get(SCREAMING_SNAKE_CASE__, stream=SCREAMING_SNAKE_CASE__ ).raw ) return im @torch.no_grad() def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Any: UpperCAmelCase_ : List[str] = get_deta_config(SCREAMING_SNAKE_CASE__ ) # load original state dict if model_name == "deta-swin-large": UpperCAmelCase_ : int = hf_hub_download(repo_id='''nielsr/deta-checkpoints''', filename='''adet_swin_ft.pth''' ) elif model_name == "deta-swin-large-o365": UpperCAmelCase_ : Dict = hf_hub_download(repo_id='''jozhang97/deta-swin-l-o365''', filename='''deta_swin_pt_o365.pth''' ) else: raise ValueError(F"""Model name {model_name} not supported""" ) UpperCAmelCase_ : Any = torch.load(SCREAMING_SNAKE_CASE__, map_location='''cpu''' )['''model'''] # original state dict for name, param in state_dict.items(): print(SCREAMING_SNAKE_CASE__, param.shape ) # rename keys UpperCAmelCase_ : Dict = create_rename_keys(SCREAMING_SNAKE_CASE__ ) for src, dest in rename_keys: rename_key(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) read_in_swin_q_k_v(SCREAMING_SNAKE_CASE__, config.backbone_config ) read_in_decoder_q_k_v(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # fix some prefixes for key in state_dict.copy().keys(): if "transformer.decoder.class_embed" in key or "transformer.decoder.bbox_embed" in key: UpperCAmelCase_ : Union[str, Any] = state_dict.pop(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Tuple = val if "input_proj" in key: UpperCAmelCase_ : List[str] = state_dict.pop(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Tuple = val if "level_embed" in key or "pos_trans" in key or "pix_trans" in key or "enc_output" in key: UpperCAmelCase_ : Union[str, Any] = state_dict.pop(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[str] = val # finally, create HuggingFace model and load state dict UpperCAmelCase_ : int = DetaForObjectDetection(SCREAMING_SNAKE_CASE__ ) model.load_state_dict(SCREAMING_SNAKE_CASE__ ) model.eval() UpperCAmelCase_ : int = '''cuda''' if torch.cuda.is_available() else '''cpu''' model.to(SCREAMING_SNAKE_CASE__ ) # load image processor UpperCAmelCase_ : Union[str, Any] = DetaImageProcessor(format='''coco_detection''' ) # verify our conversion on image UpperCAmelCase_ : str = prepare_img() UpperCAmelCase_ : str = processor(images=SCREAMING_SNAKE_CASE__, return_tensors='''pt''' ) UpperCAmelCase_ : Union[str, Any] = encoding['''pixel_values'''] UpperCAmelCase_ : str = model(pixel_values.to(SCREAMING_SNAKE_CASE__ ) ) # verify logits print('''Logits:''', outputs.logits[0, :3, :3] ) print('''Boxes:''', outputs.pred_boxes[0, :3, :3] ) if model_name == "deta-swin-large": UpperCAmelCase_ : List[str] = torch.tensor( [[-7.63_08, -2.84_85, -5.37_37], [-7.20_37, -4.55_05, -4.80_27], [-7.29_43, -4.26_11, -4.66_17]] ) UpperCAmelCase_ : int = torch.tensor([[0.49_87, 0.49_69, 0.99_99], [0.25_49, 0.54_98, 0.48_05], [0.54_98, 0.27_57, 0.05_69]] ) elif model_name == "deta-swin-large-o365": UpperCAmelCase_ : Optional[int] = torch.tensor( [[-8.01_22, -3.57_20, -4.97_17], [-8.15_47, -3.68_86, -4.63_89], [-7.66_10, -3.61_94, -5.01_34]] ) UpperCAmelCase_ : Optional[int] = torch.tensor([[0.25_23, 0.55_49, 0.48_81], [0.77_15, 0.41_49, 0.46_01], [0.55_03, 0.27_53, 0.05_75]] ) assert torch.allclose(outputs.logits[0, :3, :3], expected_logits.to(SCREAMING_SNAKE_CASE__ ), atol=1E-4 ) assert torch.allclose(outputs.pred_boxes[0, :3, :3], expected_boxes.to(SCREAMING_SNAKE_CASE__ ), atol=1E-4 ) print('''Everything ok!''' ) if pytorch_dump_folder_path: # Save model and processor logger.info(F"""Saving PyTorch model and processor to {pytorch_dump_folder_path}...""" ) Path(SCREAMING_SNAKE_CASE__ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) model.save_pretrained(SCREAMING_SNAKE_CASE__ ) processor.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Push to hub if push_to_hub: print('''Pushing model and processor to hub...''' ) model.push_to_hub(F"""jozhang97/{model_name}""" ) processor.push_to_hub(F"""jozhang97/{model_name}""" ) if __name__ == "__main__": snake_case_ : Any = argparse.ArgumentParser() parser.add_argument( "--model_name", type=str, default="deta-swin-large", choices=["deta-swin-large", "deta-swin-large-o365"], help="Name of the 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 or not to push the converted model to the 🤗 hub." ) snake_case_ : List[str] = parser.parse_args() convert_deta_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
721
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) UpperCAmelCase_ : Union[str, Any] = len(bin(SCREAMING_SNAKE_CASE__ )[3:] ) UpperCAmelCase_ : Union[str, Any] = bin(abs(SCREAMING_SNAKE_CASE__ ) - (1 << binary_number_length) )[3:] UpperCAmelCase_ : Optional[Any] = ( ( '''1''' + '''0''' * (binary_number_length - len(SCREAMING_SNAKE_CASE__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
644
0
def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : list[int] ) -> list[list[int]]: UpperCAmelCase_ : int = [] if len(SCREAMING_SNAKE_CASE__ ) == 1: return [nums.copy()] for _ in range(len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ : List[Any] = nums.pop(0 ) UpperCAmelCase_ : Optional[Any] = permute(SCREAMING_SNAKE_CASE__ ) for perm in permutations: perm.append(SCREAMING_SNAKE_CASE__ ) result.extend(SCREAMING_SNAKE_CASE__ ) nums.append(SCREAMING_SNAKE_CASE__ ) return result def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: def backtrack(SCREAMING_SNAKE_CASE__ : Union[str, Any] ): if start == len(SCREAMING_SNAKE_CASE__ ) - 1: output.append(nums[:] ) else: for i in range(SCREAMING_SNAKE_CASE__, len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ : Tuple = nums[i], nums[start] backtrack(start + 1 ) UpperCAmelCase_ : int = nums[i], nums[start] # backtrack UpperCAmelCase_ : Optional[int] = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function snake_case_ : Tuple = permutea([1, 2, 3]) print(res) doctest.testmod()
700
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. UpperCAmelCase_ : List[str] = [[1, 2, 4], [1, 2, 3, 4]] UpperCAmelCase_ : List[str] = DisjunctiveConstraint(__magic_name__ ) self.assertTrue(isinstance(dc.token_ids , __magic_name__ ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). UpperCAmelCase_ : Tuple = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(__magic_name__ ) # fails here def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] UpperCAmelCase_ : List[str] = DisjunctiveConstraint(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) UpperCAmelCase_ : Dict = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : str = dc.update(2 ) UpperCAmelCase_ : Optional[Any] = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(3 ) UpperCAmelCase_ : Dict = stepped is True and completed is True and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase__ ( self : int ) -> Dict: """simple docstring""" UpperCAmelCase_ : Any = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] UpperCAmelCase_ : Tuple = DisjunctiveConstraint(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
644
0
'''simple docstring''' import argparse import torch from transformers import ( WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaForAudioFrameClassification, WavaVecaForSequenceClassification, WavaVecaForXVector, logging, ) logging.set_verbosity_info() snake_case_ : str = logging.get_logger(__name__) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : List[str], SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: UpperCAmelCase_ : Union[str, Any] = WavaVecaForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__, config=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Dict = downstream_dict['''projector.weight'''] UpperCAmelCase_ : int = downstream_dict['''projector.bias'''] UpperCAmelCase_ : List[Any] = downstream_dict['''model.post_net.linear.weight'''] UpperCAmelCase_ : Any = downstream_dict['''model.post_net.linear.bias'''] return model def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: UpperCAmelCase_ : Dict = WavaVecaForAudioFrameClassification.from_pretrained(SCREAMING_SNAKE_CASE__, config=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : str = downstream_dict['''model.linear.weight'''] UpperCAmelCase_ : Optional[int] = downstream_dict['''model.linear.bias'''] return model def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : int ) -> Any: UpperCAmelCase_ : int = WavaVecaForXVector.from_pretrained(SCREAMING_SNAKE_CASE__, config=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = downstream_dict['''connector.weight'''] UpperCAmelCase_ : Any = downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): UpperCAmelCase_ : List[Any] = downstream_dict[ F"""model.framelevel_feature_extractor.module.{i}.kernel.weight""" ] UpperCAmelCase_ : Optional[Any] = downstream_dict[F"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""] UpperCAmelCase_ : Union[str, Any] = downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] UpperCAmelCase_ : int = downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] UpperCAmelCase_ : Dict = downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] UpperCAmelCase_ : Dict = downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] UpperCAmelCase_ : Optional[Any] = downstream_dict['''objective.W'''] return model @torch.no_grad() def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : int ) -> Union[str, Any]: UpperCAmelCase_ : Optional[int] = torch.load(SCREAMING_SNAKE_CASE__, map_location='''cpu''' ) UpperCAmelCase_ : List[str] = checkpoint['''Downstream'''] UpperCAmelCase_ : List[str] = WavaVecaConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Any = WavaVecaFeatureExtractor.from_pretrained( SCREAMING_SNAKE_CASE__, return_attention_mask=SCREAMING_SNAKE_CASE__, do_normalize=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Tuple = hf_config.architectures[0] if arch.endswith('''ForSequenceClassification''' ): UpperCAmelCase_ : List[Any] = convert_classification(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) elif arch.endswith('''ForAudioFrameClassification''' ): UpperCAmelCase_ : int = convert_diarization(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) elif arch.endswith('''ForXVector''' ): UpperCAmelCase_ : Tuple = convert_xvector(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) else: raise NotImplementedError(F"""S3PRL weights conversion is not supported for {arch}""" ) if hf_config.use_weighted_layer_sum: UpperCAmelCase_ : str = checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": snake_case_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument( "--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model." ) parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.") parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.") snake_case_ : Any = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
701
'''simple docstring''' import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": snake_case_ : List[Any] = pd.read_csv("sample_data.csv", header=None) snake_case_ : Optional[Any] = df.shape[:1][0] # If you're using some other dataset input the target column snake_case_ : Any = df.iloc[:, 1:2] snake_case_ : str = actual_data.values.reshape(len_data, 1) snake_case_ : Optional[Any] = MinMaxScaler().fit_transform(actual_data) snake_case_ : List[str] = 10 snake_case_ : Any = 5 snake_case_ : Any = 20 snake_case_ : Tuple = len_data - periods * look_back snake_case_ : str = actual_data[:division] snake_case_ : Optional[int] = actual_data[division - look_back :] snake_case_ ,snake_case_ : Any = [], [] snake_case_ ,snake_case_ : Union[str, Any] = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) snake_case_ : Any = np.array(train_x) snake_case_ : Optional[Any] = np.array(test_x) snake_case_ : Optional[Any] = np.array([list(i.ravel()) for i in train_y]) snake_case_ : List[str] = np.array([list(i.ravel()) for i in test_y]) snake_case_ : List[Any] = Sequential() model.add(LSTM(1_28, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(1_28, 1))) model.add(Dense(forward_days)) model.compile(loss="mean_squared_error", optimizer="adam") snake_case_ : Dict = model.fit( x_train, y_train, epochs=1_50, verbose=1, shuffle=True, batch_size=4 ) snake_case_ : Optional[Any] = model.predict(x_test)
644
0
'''simple docstring''' import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class __a (nn.Module ): __a : int __a : int __a : float = 0.0 __a : int = 1 __a : int = 1 __a : bool = True __a : bool = False __a : bool = False __a : bool = False __a : jnp.dtype = jnp.floataa def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" UpperCAmelCase_ : List[str] = [] UpperCAmelCase_ : List[Any] = [] for i in range(self.num_layers ): UpperCAmelCase_ : Union[str, Any] = self.in_channels if i == 0 else self.out_channels UpperCAmelCase_ : List[Any] = FlaxResnetBlockaD( in_channels=__magic_name__ , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(__magic_name__ ) UpperCAmelCase_ : List[str] = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(__magic_name__ ) UpperCAmelCase_ : int = resnets UpperCAmelCase_ : Optional[Any] = attentions if self.add_downsample: UpperCAmelCase_ : Tuple = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : Tuple , __magic_name__ : str , __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : Dict=True ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : int = () for resnet, attn in zip(self.resnets , self.attentions ): UpperCAmelCase_ : Union[str, Any] = resnet(__magic_name__ , __magic_name__ , deterministic=__magic_name__ ) UpperCAmelCase_ : Tuple = attn(__magic_name__ , __magic_name__ , deterministic=__magic_name__ ) output_states += (hidden_states,) if self.add_downsample: UpperCAmelCase_ : int = self.downsamplers_a(__magic_name__ ) output_states += (hidden_states,) return hidden_states, output_states class __a (nn.Module ): __a : int __a : int __a : float = 0.0 __a : int = 1 __a : bool = True __a : jnp.dtype = jnp.floataa def UpperCAmelCase__ ( self : str ) -> int: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = [] for i in range(self.num_layers ): UpperCAmelCase_ : List[Any] = self.in_channels if i == 0 else self.out_channels UpperCAmelCase_ : Dict = FlaxResnetBlockaD( in_channels=__magic_name__ , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(__magic_name__ ) UpperCAmelCase_ : Optional[int] = resnets if self.add_downsample: UpperCAmelCase_ : Union[str, Any] = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : int , __magic_name__ : Any , __magic_name__ : int , __magic_name__ : Optional[Any]=True ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = () for resnet in self.resnets: UpperCAmelCase_ : Optional[Any] = resnet(__magic_name__ , __magic_name__ , deterministic=__magic_name__ ) output_states += (hidden_states,) if self.add_downsample: UpperCAmelCase_ : Dict = self.downsamplers_a(__magic_name__ ) output_states += (hidden_states,) return hidden_states, output_states class __a (nn.Module ): __a : int __a : int __a : int __a : float = 0.0 __a : int = 1 __a : int = 1 __a : bool = True __a : bool = False __a : bool = False __a : bool = False __a : jnp.dtype = jnp.floataa def UpperCAmelCase__ ( self : int ) -> int: """simple docstring""" UpperCAmelCase_ : Optional[Any] = [] UpperCAmelCase_ : Dict = [] for i in range(self.num_layers ): UpperCAmelCase_ : List[Any] = self.in_channels if (i == self.num_layers - 1) else self.out_channels UpperCAmelCase_ : str = self.prev_output_channel if i == 0 else self.out_channels UpperCAmelCase_ : Any = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(__magic_name__ ) UpperCAmelCase_ : str = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(__magic_name__ ) UpperCAmelCase_ : Dict = resnets UpperCAmelCase_ : Any = attentions if self.add_upsample: UpperCAmelCase_ : Tuple = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : int , __magic_name__ : Optional[int] , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , __magic_name__ : str , __magic_name__ : List[Any]=True ) -> List[Any]: """simple docstring""" for resnet, attn in zip(self.resnets , self.attentions ): # pop res hidden states UpperCAmelCase_ : List[str] = res_hidden_states_tuple[-1] UpperCAmelCase_ : int = res_hidden_states_tuple[:-1] UpperCAmelCase_ : Optional[int] = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) UpperCAmelCase_ : str = resnet(__magic_name__ , __magic_name__ , deterministic=__magic_name__ ) UpperCAmelCase_ : Optional[int] = attn(__magic_name__ , __magic_name__ , deterministic=__magic_name__ ) if self.add_upsample: UpperCAmelCase_ : int = self.upsamplers_a(__magic_name__ ) return hidden_states class __a (nn.Module ): __a : int __a : int __a : int __a : float = 0.0 __a : int = 1 __a : bool = True __a : jnp.dtype = jnp.floataa def UpperCAmelCase__ ( self : List[str] ) -> int: """simple docstring""" UpperCAmelCase_ : Any = [] for i in range(self.num_layers ): UpperCAmelCase_ : int = self.in_channels if (i == self.num_layers - 1) else self.out_channels UpperCAmelCase_ : Any = self.prev_output_channel if i == 0 else self.out_channels UpperCAmelCase_ : List[Any] = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(__magic_name__ ) UpperCAmelCase_ : Optional[int] = resnets if self.add_upsample: UpperCAmelCase_ : int = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__( self : List[Any] , __magic_name__ : int , __magic_name__ : int , __magic_name__ : Union[str, Any] , __magic_name__ : str=True ) -> Optional[Any]: """simple docstring""" for resnet in self.resnets: # pop res hidden states UpperCAmelCase_ : Tuple = res_hidden_states_tuple[-1] UpperCAmelCase_ : Optional[Any] = res_hidden_states_tuple[:-1] UpperCAmelCase_ : Tuple = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) UpperCAmelCase_ : Dict = resnet(__magic_name__ , __magic_name__ , deterministic=__magic_name__ ) if self.add_upsample: UpperCAmelCase_ : Union[str, Any] = self.upsamplers_a(__magic_name__ ) return hidden_states class __a (nn.Module ): __a : int __a : float = 0.0 __a : int = 1 __a : int = 1 __a : bool = False __a : bool = False __a : jnp.dtype = jnp.floataa def UpperCAmelCase__ ( self : str ) -> Tuple: """simple docstring""" UpperCAmelCase_ : int = [ FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) ] UpperCAmelCase_ : List[Any] = [] for _ in range(self.num_layers ): UpperCAmelCase_ : Optional[Any] = FlaxTransformeraDModel( in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(__magic_name__ ) UpperCAmelCase_ : List[str] = FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(__magic_name__ ) UpperCAmelCase_ : Any = resnets UpperCAmelCase_ : Optional[int] = attentions def __call__( self : str , __magic_name__ : int , __magic_name__ : Optional[int] , __magic_name__ : List[str] , __magic_name__ : List[Any]=True ) -> Any: """simple docstring""" UpperCAmelCase_ : Dict = self.resnets[0](__magic_name__ , __magic_name__ ) for attn, resnet in zip(self.attentions , self.resnets[1:] ): UpperCAmelCase_ : Any = attn(__magic_name__ , __magic_name__ , deterministic=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = resnet(__magic_name__ , __magic_name__ , deterministic=__magic_name__ ) return hidden_states
702
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker snake_case_ : Union[str, Any] = "CompVis/stable-diffusion-v1-1" snake_case_ : Dict = "CompVis/stable-diffusion-v1-2" snake_case_ : Any = "CompVis/stable-diffusion-v1-3" snake_case_ : str = "CompVis/stable-diffusion-v1-4" class __a (lowerCamelCase ): def __init__( self : Any , __magic_name__ : AutoencoderKL , __magic_name__ : CLIPTextModel , __magic_name__ : CLIPTokenizer , __magic_name__ : UNetaDConditionModel , __magic_name__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __magic_name__ : StableDiffusionSafetyChecker , __magic_name__ : CLIPImageProcessor , __magic_name__ : bool = True , ) -> str: """simple docstring""" super()._init_() UpperCAmelCase_ : Any = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Dict = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : List[Any] = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Tuple = StableDiffusionPipeline( vae=__magic_name__ , text_encoder=__magic_name__ , tokenizer=__magic_name__ , unet=__magic_name__ , scheduler=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , requires_safety_checker=__magic_name__ , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def UpperCAmelCase__ ( self : Tuple ) -> Dict[str, Any]: """simple docstring""" return {k: getattr(self , __magic_name__ ) for k in self.config.keys() if not k.startswith('''_''' )} def UpperCAmelCase__ ( self : Dict , __magic_name__ : Optional[Union[str, int]] = "auto" ) -> int: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ : List[str] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" self.enable_attention_slicing(__magic_name__ ) @torch.no_grad() def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Tuple , ) -> Optional[int]: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Any , ) -> Any: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Dict , ) -> List[str]: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : int , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Optional[int] , ) -> str: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Optional[int] , ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : int = '''cuda''' if torch.cuda.is_available() else '''cpu''' self.to(__magic_name__ ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` must be divisible by 8 but are {height} and {width}.""" ) # Get first result from Stable Diffusion Checkpoint v1.1 UpperCAmelCase_ : Optional[int] = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCAmelCase_ : int = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCAmelCase_ : str = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCAmelCase_ : str = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
644
0
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker snake_case_ : Union[str, Any] = "CompVis/stable-diffusion-v1-1" snake_case_ : Dict = "CompVis/stable-diffusion-v1-2" snake_case_ : Any = "CompVis/stable-diffusion-v1-3" snake_case_ : str = "CompVis/stable-diffusion-v1-4" class __a (lowerCamelCase ): def __init__( self : Any , __magic_name__ : AutoencoderKL , __magic_name__ : CLIPTextModel , __magic_name__ : CLIPTokenizer , __magic_name__ : UNetaDConditionModel , __magic_name__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __magic_name__ : StableDiffusionSafetyChecker , __magic_name__ : CLIPImageProcessor , __magic_name__ : bool = True , ) -> str: """simple docstring""" super()._init_() UpperCAmelCase_ : Any = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Dict = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : List[Any] = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Tuple = StableDiffusionPipeline( vae=__magic_name__ , text_encoder=__magic_name__ , tokenizer=__magic_name__ , unet=__magic_name__ , scheduler=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , requires_safety_checker=__magic_name__ , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def UpperCAmelCase__ ( self : Tuple ) -> Dict[str, Any]: """simple docstring""" return {k: getattr(self , __magic_name__ ) for k in self.config.keys() if not k.startswith('''_''' )} def UpperCAmelCase__ ( self : Dict , __magic_name__ : Optional[Union[str, int]] = "auto" ) -> int: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ : List[str] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" self.enable_attention_slicing(__magic_name__ ) @torch.no_grad() def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Tuple , ) -> Optional[int]: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Any , ) -> Any: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Dict , ) -> List[str]: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : int , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Optional[int] , ) -> str: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Optional[int] , ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : int = '''cuda''' if torch.cuda.is_available() else '''cpu''' self.to(__magic_name__ ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` must be divisible by 8 but are {height} and {width}.""" ) # Get first result from Stable Diffusion Checkpoint v1.1 UpperCAmelCase_ : Optional[int] = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCAmelCase_ : int = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCAmelCase_ : str = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCAmelCase_ : str = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
703
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler snake_case_ : Optional[int] = 16 snake_case_ : Tuple = 32 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Accelerator, SCREAMING_SNAKE_CASE__ : int = 16, SCREAMING_SNAKE_CASE__ : str = "bert-base-cased" ) -> Dict: UpperCAmelCase_ : Dict = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = load_dataset('''glue''', '''mrpc''' ) def tokenize_function(SCREAMING_SNAKE_CASE__ : Optional[int] ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase_ : Union[str, Any] = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=SCREAMING_SNAKE_CASE__, max_length=SCREAMING_SNAKE_CASE__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase_ : Tuple = datasets.map( SCREAMING_SNAKE_CASE__, batched=SCREAMING_SNAKE_CASE__, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], load_from_cache_file=SCREAMING_SNAKE_CASE__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase_ : Optional[Any] = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(SCREAMING_SNAKE_CASE__ : str ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(SCREAMING_SNAKE_CASE__, padding='''max_length''', max_length=128, return_tensors='''pt''' ) return tokenizer.pad(SCREAMING_SNAKE_CASE__, padding='''longest''', return_tensors='''pt''' ) # Instantiate dataloaders. UpperCAmelCase_ : str = DataLoader( tokenized_datasets['''train'''], shuffle=SCREAMING_SNAKE_CASE__, collate_fn=SCREAMING_SNAKE_CASE__, batch_size=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = DataLoader( tokenized_datasets['''validation'''], shuffle=SCREAMING_SNAKE_CASE__, collate_fn=SCREAMING_SNAKE_CASE__, batch_size=SCREAMING_SNAKE_CASE__ ) return train_dataloader, eval_dataloader def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Optional[int], SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Any ) -> Any: model.eval() UpperCAmelCase_ : List[str] = 0 for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase_ : Dict = model(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : str = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCAmelCase_ , UpperCAmelCase_ : List[str] = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(SCREAMING_SNAKE_CASE__ ) - 1: UpperCAmelCase_ : Tuple = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCAmelCase_ : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=SCREAMING_SNAKE_CASE__, references=SCREAMING_SNAKE_CASE__, ) UpperCAmelCase_ : List[str] = metric.compute() return eval_metric["accuracy"] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : int ) -> Tuple: # Initialize accelerator UpperCAmelCase_ : Union[str, Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase_ : int = config['''lr'''] UpperCAmelCase_ : Optional[int] = int(config['''num_epochs'''] ) UpperCAmelCase_ : Optional[int] = int(config['''seed'''] ) UpperCAmelCase_ : List[str] = int(config['''batch_size'''] ) UpperCAmelCase_ : Optional[int] = args.model_name_or_path set_seed(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = get_dataloaders(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase_ : List[Any] = AutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__, return_dict=SCREAMING_SNAKE_CASE__ ) # Instantiate optimizer UpperCAmelCase_ : str = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCAmelCase_ : List[str] = optimizer_cls(params=model.parameters(), lr=SCREAMING_SNAKE_CASE__ ) if accelerator.state.deepspeed_plugin is not None: UpperCAmelCase_ : List[Any] = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: UpperCAmelCase_ : Tuple = 1 UpperCAmelCase_ : int = (len(SCREAMING_SNAKE_CASE__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCAmelCase_ : Tuple = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE__, num_warmup_steps=0, num_training_steps=SCREAMING_SNAKE_CASE__, ) else: UpperCAmelCase_ : Any = DummyScheduler(SCREAMING_SNAKE_CASE__, total_num_steps=SCREAMING_SNAKE_CASE__, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = accelerator.prepare( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase_ : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly UpperCAmelCase_ : Dict = 0 UpperCAmelCase_ : int = evaluate.load('''glue''', '''mrpc''' ) UpperCAmelCase_ : Optional[Any] = num_epochs if args.partial_train_epoch is not None: UpperCAmelCase_ : List[Any] = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) UpperCAmelCase_ : Tuple = args.resume_from_checkpoint.split('''epoch_''' )[1] UpperCAmelCase_ : int = '''''' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break UpperCAmelCase_ : Union[str, Any] = int(SCREAMING_SNAKE_CASE__ ) + 1 UpperCAmelCase_ : Dict = evaluation_loop(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) accelerator.print('''resumed checkpoint performance:''', SCREAMING_SNAKE_CASE__ ) accelerator.print('''resumed checkpoint\'s scheduler\'s lr:''', lr_scheduler.get_lr()[0] ) accelerator.print('''resumed optimizers\'s lr:''', optimizer.param_groups[0]['''lr'''] ) with open(os.path.join(args.output_dir, F"""state_{starting_epoch-1}.json""" ), '''r''' ) as f: UpperCAmelCase_ : Optional[int] = json.load(SCREAMING_SNAKE_CASE__ ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model UpperCAmelCase_ : int = {} for epoch in range(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Optional[int] = model(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Any = outputs.loss UpperCAmelCase_ : Tuple = loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 UpperCAmelCase_ : Tuple = F"""epoch_{epoch}""" UpperCAmelCase_ : Optional[int] = os.path.join(args.output_dir, SCREAMING_SNAKE_CASE__ ) accelerator.save_state(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = evaluation_loop(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[Any] = accuracy UpperCAmelCase_ : Any = lr_scheduler.get_lr()[0] UpperCAmelCase_ : List[str] = optimizer.param_groups[0]['''lr'''] UpperCAmelCase_ : Tuple = epoch UpperCAmelCase_ : Dict = overall_step accelerator.print(F"""epoch {epoch}:""", SCREAMING_SNAKE_CASE__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F"""state_{epoch}.json""" ), '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( ) -> List[str]: UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''', type=SCREAMING_SNAKE_CASE__, default='''bert-base-cased''', help='''Path to pretrained model or model identifier from huggingface.co/models.''', required=SCREAMING_SNAKE_CASE__, ) parser.add_argument( '''--output_dir''', type=SCREAMING_SNAKE_CASE__, default='''.''', help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''', ) parser.add_argument( '''--resume_from_checkpoint''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''If the training should continue from a checkpoint folder.''', ) parser.add_argument( '''--partial_train_epoch''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''If passed, the training will stop after this number of epochs.''', ) parser.add_argument( '''--num_epochs''', type=SCREAMING_SNAKE_CASE__, default=2, help='''Number of train epochs.''', ) UpperCAmelCase_ : Optional[int] = parser.parse_args() UpperCAmelCase_ : List[Any] = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
644
0
import argparse import torch from transformers import ( UniSpeechSatConfig, UniSpeechSatForAudioFrameClassification, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, WavaVecaFeatureExtractor, logging, ) logging.set_verbosity_info() snake_case_ : List[Any] = logging.get_logger(__name__) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : List[str], SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[int]: UpperCAmelCase_ : Optional[int] = UniSpeechSatForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__, config=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[Any] = downstream_dict['''projector.weight'''] UpperCAmelCase_ : List[Any] = downstream_dict['''projector.bias'''] UpperCAmelCase_ : Any = downstream_dict['''model.post_net.linear.weight'''] UpperCAmelCase_ : str = downstream_dict['''model.post_net.linear.bias'''] return model def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]: UpperCAmelCase_ : Optional[Any] = UniSpeechSatForAudioFrameClassification.from_pretrained(SCREAMING_SNAKE_CASE__, config=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Any = downstream_dict['''model.linear.weight'''] UpperCAmelCase_ : Dict = downstream_dict['''model.linear.bias'''] return model def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str], SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: UpperCAmelCase_ : Tuple = UniSpeechSatForXVector.from_pretrained(SCREAMING_SNAKE_CASE__, config=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = downstream_dict['''connector.weight'''] UpperCAmelCase_ : List[Any] = downstream_dict['''connector.bias'''] for i, kernel_size in enumerate(hf_config.tdnn_kernel ): UpperCAmelCase_ : Any = downstream_dict[ F"""model.framelevel_feature_extractor.module.{i}.kernel.weight""" ] UpperCAmelCase_ : Dict = downstream_dict[F"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""] UpperCAmelCase_ : Any = downstream_dict['''model.utterancelevel_feature_extractor.linear1.weight'''] UpperCAmelCase_ : Dict = downstream_dict['''model.utterancelevel_feature_extractor.linear1.bias'''] UpperCAmelCase_ : Optional[int] = downstream_dict['''model.utterancelevel_feature_extractor.linear2.weight'''] UpperCAmelCase_ : List[Any] = downstream_dict['''model.utterancelevel_feature_extractor.linear2.bias'''] UpperCAmelCase_ : int = downstream_dict['''objective.W'''] return model @torch.no_grad() def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Optional[int], SCREAMING_SNAKE_CASE__ : List[str], SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: UpperCAmelCase_ : Dict = torch.load(SCREAMING_SNAKE_CASE__, map_location='''cpu''' ) UpperCAmelCase_ : int = checkpoint['''Downstream'''] UpperCAmelCase_ : List[Any] = UniSpeechSatConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Tuple = WavaVecaFeatureExtractor.from_pretrained( SCREAMING_SNAKE_CASE__, return_attention_mask=SCREAMING_SNAKE_CASE__, do_normalize=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Union[str, Any] = hf_config.architectures[0] if arch.endswith('''ForSequenceClassification''' ): UpperCAmelCase_ : Any = convert_classification(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) elif arch.endswith('''ForAudioFrameClassification''' ): UpperCAmelCase_ : Tuple = convert_diarization(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) elif arch.endswith('''ForXVector''' ): UpperCAmelCase_ : Optional[int] = convert_xvector(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) else: raise NotImplementedError(F"""S3PRL weights conversion is not supported for {arch}""" ) if hf_config.use_weighted_layer_sum: UpperCAmelCase_ : Tuple = checkpoint['''Featurizer''']['''weights'''] hf_feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ ) hf_model.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": snake_case_ : Dict = argparse.ArgumentParser() parser.add_argument( "--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model." ) parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.") parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.") snake_case_ : str = parser.parse_args() convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
704
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : list[int] ) -> list[list[int]]: UpperCAmelCase_ : int = [] if len(SCREAMING_SNAKE_CASE__ ) == 1: return [nums.copy()] for _ in range(len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ : List[Any] = nums.pop(0 ) UpperCAmelCase_ : Optional[Any] = permute(SCREAMING_SNAKE_CASE__ ) for perm in permutations: perm.append(SCREAMING_SNAKE_CASE__ ) result.extend(SCREAMING_SNAKE_CASE__ ) nums.append(SCREAMING_SNAKE_CASE__ ) return result def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: def backtrack(SCREAMING_SNAKE_CASE__ : Union[str, Any] ): if start == len(SCREAMING_SNAKE_CASE__ ) - 1: output.append(nums[:] ) else: for i in range(SCREAMING_SNAKE_CASE__, len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ , UpperCAmelCase_ : Tuple = nums[i], nums[start] backtrack(start + 1 ) UpperCAmelCase_ , UpperCAmelCase_ : int = nums[i], nums[start] # backtrack UpperCAmelCase_ : Optional[int] = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function snake_case_ : Tuple = permutea([1, 2, 3]) print(res) doctest.testmod()
644
0
'''simple docstring''' import gc import random import tempfile import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, ControlNetModel, DDIMScheduler, StableDiffusionControlNetImgaImgPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() class __a (lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : Dict = StableDiffusionControlNetImgaImgPipeline __a : Optional[int] = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} __a : str = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __a : Union[str, Any] = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({"control_image"} ) __a : str = IMAGE_TO_IMAGE_IMAGE_PARAMS def UpperCAmelCase__ ( self : Tuple ) -> int: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase_ : Union[str, Any] = 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 , ) torch.manual_seed(0 ) UpperCAmelCase_ : str = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) torch.manual_seed(0 ) UpperCAmelCase_ : str = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=__magic_name__ , set_alpha_to_one=__magic_name__ , ) torch.manual_seed(0 ) UpperCAmelCase_ : str = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCAmelCase_ : Any = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) UpperCAmelCase_ : List[Any] = CLIPTextModel(__magic_name__ ) UpperCAmelCase_ : Any = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) UpperCAmelCase_ : int = { '''unet''': unet, '''controlnet''': controlnet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : int , __magic_name__ : Union[str, Any]=0 ) -> List[str]: """simple docstring""" if str(__magic_name__ ).startswith('''mps''' ): UpperCAmelCase_ : str = torch.manual_seed(__magic_name__ ) else: UpperCAmelCase_ : Optional[int] = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) UpperCAmelCase_ : List[Any] = 2 UpperCAmelCase_ : Tuple = randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__magic_name__ , device=torch.device(__magic_name__ ) , ) UpperCAmelCase_ : List[str] = floats_tensor(control_image.shape , rng=random.Random(__magic_name__ ) ).to(__magic_name__ ) UpperCAmelCase_ : Dict = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCAmelCase_ : Optional[int] = Image.fromarray(np.uinta(__magic_name__ ) ).convert('''RGB''' ).resize((64, 64) ) UpperCAmelCase_ : int = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', '''image''': image, '''control_image''': control_image, } return inputs def UpperCAmelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def UpperCAmelCase__ ( self : int ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) class __a (lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : str = StableDiffusionControlNetImgaImgPipeline __a : Tuple = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} __a : Optional[Any] = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS __a : List[Any] = frozenset([] ) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess def UpperCAmelCase__ ( self : int ) -> int: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase_ : Optional[int] = 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 , ) torch.manual_seed(0 ) def init_weights(__magic_name__ : str ): if isinstance(__magic_name__ , torch.nn.Convad ): torch.nn.init.normal(m.weight ) m.bias.data.fill_(1.0 ) UpperCAmelCase_ : Optional[Any] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(__magic_name__ ) torch.manual_seed(0 ) UpperCAmelCase_ : Optional[int] = ControlNetModel( block_out_channels=(32, 64) , layers_per_block=2 , in_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , cross_attention_dim=32 , conditioning_embedding_out_channels=(16, 32) , ) controlneta.controlnet_down_blocks.apply(__magic_name__ ) torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = DDIMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=__magic_name__ , set_alpha_to_one=__magic_name__ , ) torch.manual_seed(0 ) UpperCAmelCase_ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , ) torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) UpperCAmelCase_ : Any = CLIPTextModel(__magic_name__ ) UpperCAmelCase_ : Tuple = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ) UpperCAmelCase_ : Tuple = MultiControlNetModel([controlneta, controlneta] ) UpperCAmelCase_ : Union[str, Any] = { '''unet''': unet, '''controlnet''': controlnet, '''scheduler''': scheduler, '''vae''': vae, '''text_encoder''': text_encoder, '''tokenizer''': tokenizer, '''safety_checker''': None, '''feature_extractor''': None, } return components def UpperCAmelCase__ ( self : List[str] , __magic_name__ : List[Any] , __magic_name__ : Optional[int]=0 ) -> List[Any]: """simple docstring""" if str(__magic_name__ ).startswith('''mps''' ): UpperCAmelCase_ : Any = torch.manual_seed(__magic_name__ ) else: UpperCAmelCase_ : Optional[Any] = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = 2 UpperCAmelCase_ : Tuple = [ randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__magic_name__ , device=torch.device(__magic_name__ ) , ), randn_tensor( (1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor) , generator=__magic_name__ , device=torch.device(__magic_name__ ) , ), ] UpperCAmelCase_ : Any = floats_tensor(control_image[0].shape , rng=random.Random(__magic_name__ ) ).to(__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0] UpperCAmelCase_ : List[Any] = Image.fromarray(np.uinta(__magic_name__ ) ).convert('''RGB''' ).resize((64, 64) ) UpperCAmelCase_ : List[Any] = { '''prompt''': '''A painting of a squirrel eating a burger''', '''generator''': generator, '''num_inference_steps''': 2, '''guidance_scale''': 6.0, '''output_type''': '''numpy''', '''image''': image, '''control_image''': control_image, } return inputs def UpperCAmelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Optional[int] = self.get_dummy_components() UpperCAmelCase_ : List[str] = self.pipeline_class(**__magic_name__ ) pipe.to(__magic_name__ ) UpperCAmelCase_ : List[Any] = 10.0 UpperCAmelCase_ : Optional[int] = 4 UpperCAmelCase_ : Optional[Any] = self.get_dummy_inputs(__magic_name__ ) UpperCAmelCase_ : Tuple = steps UpperCAmelCase_ : List[Any] = scale UpperCAmelCase_ : str = pipe(**__magic_name__ )[0] UpperCAmelCase_ : Any = self.get_dummy_inputs(__magic_name__ ) UpperCAmelCase_ : Dict = steps UpperCAmelCase_ : Dict = scale UpperCAmelCase_ : str = pipe(**__magic_name__ , control_guidance_start=0.1 , control_guidance_end=0.2 )[0] UpperCAmelCase_ : Any = self.get_dummy_inputs(__magic_name__ ) UpperCAmelCase_ : int = steps UpperCAmelCase_ : Union[str, Any] = scale UpperCAmelCase_ : Optional[int] = pipe(**__magic_name__ , control_guidance_start=[0.1, 0.3] , control_guidance_end=[0.2, 0.7] )[0] UpperCAmelCase_ : Union[str, Any] = self.get_dummy_inputs(__magic_name__ ) UpperCAmelCase_ : Optional[int] = steps UpperCAmelCase_ : List[Any] = scale UpperCAmelCase_ : Union[str, Any] = pipe(**__magic_name__ , control_guidance_start=0.4 , control_guidance_end=[0.5, 0.8] )[0] # make sure that all outputs are different assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 assert np.sum(np.abs(output_a - output_a ) ) > 1E-3 def UpperCAmelCase__ ( self : int ) -> Tuple: """simple docstring""" return self._test_attention_slicing_forward_pass(expected_max_diff=2E-3 ) @unittest.skipIf( torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , ) def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2E-3 ) def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" self._test_inference_batch_single_identical(expected_max_diff=2E-3 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Dict: """simple docstring""" UpperCAmelCase_ : Optional[int] = self.get_dummy_components() UpperCAmelCase_ : str = self.pipeline_class(**__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) with tempfile.TemporaryDirectory() as tmpdir: try: # save_pretrained is not implemented for Multi-ControlNet pipe.save_pretrained(__magic_name__ ) except NotImplementedError: pass @slow @require_torch_gpu class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[int] = ControlNetModel.from_pretrained('''lllyasviel/sd-controlnet-canny''' ) UpperCAmelCase_ : Any = StableDiffusionControlNetImgaImgPipeline.from_pretrained( '''runwayml/stable-diffusion-v1-5''' , safety_checker=__magic_name__ , controlnet=__magic_name__ ) pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Dict = torch.Generator(device='''cpu''' ).manual_seed(0 ) UpperCAmelCase_ : Dict = '''evil space-punk bird''' UpperCAmelCase_ : str = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png''' ).resize((5_12, 5_12) ) UpperCAmelCase_ : List[Any] = load_image( '''https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png''' ).resize((5_12, 5_12) ) UpperCAmelCase_ : List[Any] = pipe( __magic_name__ , __magic_name__ , control_image=__magic_name__ , generator=__magic_name__ , output_type='''np''' , num_inference_steps=50 , strength=0.6 , ) UpperCAmelCase_ : Tuple = output.images[0] assert image.shape == (5_12, 5_12, 3) UpperCAmelCase_ : Optional[int] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy''' ) assert np.abs(expected_image - image ).max() < 9E-2
705
'''simple docstring''' class __a : def __init__( self : List[Any] , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : Optional[Any] = size UpperCAmelCase_ : Tuple = [0] * size UpperCAmelCase_ : Optional[Any] = [0] * size @staticmethod def UpperCAmelCase__ ( __magic_name__ : int ) -> int: """simple docstring""" return index | (index + 1) @staticmethod def UpperCAmelCase__ ( __magic_name__ : int ) -> int: """simple docstring""" return (index & (index + 1)) - 1 def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : int , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : int = value while index < self.size: UpperCAmelCase_ : str = self.get_prev(__magic_name__ ) + 1 if current_left_border == index: UpperCAmelCase_ : List[str] = value else: UpperCAmelCase_ : Optional[int] = max(__magic_name__ , __magic_name__ , __magic_name__ ) UpperCAmelCase_ : Tuple = self.get_next(__magic_name__ ) def UpperCAmelCase__ ( self : Any , __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" right -= 1 # Because of right is exclusive UpperCAmelCase_ : List[str] = 0 while left <= right: UpperCAmelCase_ : Optional[Any] = self.get_prev(__magic_name__ ) if left <= current_left: UpperCAmelCase_ : Dict = max(__magic_name__ , self.tree[right] ) UpperCAmelCase_ : Optional[Any] = current_left else: UpperCAmelCase_ : str = max(__magic_name__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
644
0
'''simple docstring''' import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __a (unittest.TestCase ): @property def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def UpperCAmelCase__ ( self : Dict ) -> Tuple: """simple docstring""" UpperCAmelCase_ : List[Any] = self.dummy_uncond_unet UpperCAmelCase_ : Dict = KarrasVeScheduler() UpperCAmelCase_ : Union[str, Any] = KarrasVePipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Dict = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[int] = pipe(num_inference_steps=2 , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Tuple = torch.manual_seed(0 ) UpperCAmelCase_ : str = pipe(num_inference_steps=2 , generator=__magic_name__ , output_type='''numpy''' , return_dict=__magic_name__ )[0] UpperCAmelCase_ : Union[str, Any] = image[0, -3:, -3:, -1] UpperCAmelCase_ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase_ : Dict = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : List[str] = '''google/ncsnpp-celebahq-256''' UpperCAmelCase_ : List[str] = UNetaDModel.from_pretrained(__magic_name__ ) UpperCAmelCase_ : List[Any] = KarrasVeScheduler() UpperCAmelCase_ : Any = KarrasVePipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Dict = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = pipe(num_inference_steps=20 , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) UpperCAmelCase_ : Optional[Any] = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
706
'''simple docstring''' import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __a : def __init__( self : List[str] , __magic_name__ : List[str] , __magic_name__ : str=13 , __magic_name__ : Union[str, Any]=7 , __magic_name__ : Union[str, Any]=True , __magic_name__ : Any=True , __magic_name__ : List[str]=False , __magic_name__ : Optional[int]=True , __magic_name__ : Dict=99 , __magic_name__ : Tuple=32 , __magic_name__ : int=5 , __magic_name__ : Dict=4 , __magic_name__ : Tuple=37 , __magic_name__ : Optional[int]="gelu" , __magic_name__ : List[str]=0.1 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : str=5_12 , __magic_name__ : Union[str, Any]=16 , __magic_name__ : int=2 , __magic_name__ : List[Any]=0.0_2 , __magic_name__ : Tuple=3 , __magic_name__ : Union[str, Any]=4 , __magic_name__ : Optional[int]=None , ) -> str: """simple docstring""" UpperCAmelCase_ : Any = parent UpperCAmelCase_ : Union[str, Any] = batch_size UpperCAmelCase_ : List[Any] = seq_length UpperCAmelCase_ : str = is_training UpperCAmelCase_ : Any = use_input_mask UpperCAmelCase_ : List[str] = use_token_type_ids UpperCAmelCase_ : Union[str, Any] = use_labels UpperCAmelCase_ : Dict = vocab_size UpperCAmelCase_ : Optional[Any] = hidden_size UpperCAmelCase_ : Dict = num_hidden_layers UpperCAmelCase_ : List[Any] = num_attention_heads UpperCAmelCase_ : Optional[int] = intermediate_size UpperCAmelCase_ : Union[str, Any] = hidden_act UpperCAmelCase_ : str = hidden_dropout_prob UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase_ : Any = max_position_embeddings UpperCAmelCase_ : str = type_vocab_size UpperCAmelCase_ : Optional[Any] = type_sequence_label_size UpperCAmelCase_ : List[Any] = initializer_range UpperCAmelCase_ : int = num_labels UpperCAmelCase_ : Optional[int] = num_choices UpperCAmelCase_ : Tuple = scope def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : Union[str, Any] = None if self.use_input_mask: UpperCAmelCase_ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ : str = None if self.use_token_type_ids: UpperCAmelCase_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Tuple = None UpperCAmelCase_ : List[str] = None UpperCAmelCase_ : Union[str, Any] = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase_ : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" return BioGptConfig( 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=__magic_name__ , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : Tuple , __magic_name__ : str , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = BioGptModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Dict = model(__magic_name__ , attention_mask=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Tuple , __magic_name__ : List[str] , __magic_name__ : Optional[int] , ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptForCausalLM(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : List[Any] = model(__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase__ ( self : str , __magic_name__ : Optional[int] , __magic_name__ : Tuple , __magic_name__ : List[str] , __magic_name__ : int , __magic_name__ : str , *__magic_name__ : Any ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() # create attention mask UpperCAmelCase_ : Optional[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=__magic_name__ ) UpperCAmelCase_ : Any = self.seq_length // 2 UpperCAmelCase_ : Tuple = 0 # first forward pass UpperCAmelCase_ , UpperCAmelCase_ : Dict = model(__magic_name__ , attention_mask=__magic_name__ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase_ : Tuple = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCAmelCase_ : List[str] = ids_tensor((1,) , __magic_name__ ).item() + 1 UpperCAmelCase_ : Tuple = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCAmelCase_ : str = random_other_next_tokens # append to next input_ids and attn_mask UpperCAmelCase_ : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase_ : int = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=__magic_name__ )] , dim=1 , ) # get two different outputs UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] UpperCAmelCase_ : int = model(__magic_name__ , past_key_values=__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] # select random slice UpperCAmelCase_ : Optional[int] = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase_ : Union[str, Any] = output_from_no_past[:, -1, random_slice_idx].detach() UpperCAmelCase_ : Dict = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Dict , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , *__magic_name__ : str ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptModel(config=__magic_name__ ).to(__magic_name__ ).eval() UpperCAmelCase_ : Optional[int] = torch.ones(input_ids.shape , dtype=torch.long , device=__magic_name__ ) # first forward pass UpperCAmelCase_ : Union[str, Any] = model(__magic_name__ , attention_mask=__magic_name__ , use_cache=__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ : int = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCAmelCase_ : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase_ : Any = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCAmelCase_ : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase_ : List[str] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] UpperCAmelCase_ : Optional[Any] = model(__magic_name__ , attention_mask=__magic_name__ , past_key_values=__magic_name__ )[ '''last_hidden_state''' ] # select random slice UpperCAmelCase_ : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase_ : str = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCAmelCase_ : Optional[int] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-3 ) ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : str , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , *__magic_name__ : Any , __magic_name__ : List[Any]=False ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = BioGptForCausalLM(__magic_name__ ) model.to(__magic_name__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCAmelCase_ : List[str] = model(__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Optional[int] , *__magic_name__ : List[str] ) -> str: """simple docstring""" UpperCAmelCase_ : int = BioGptModel(__magic_name__ ) UpperCAmelCase_ : Dict = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.0_0_1 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.0_1 ) def UpperCAmelCase__ ( self : int , __magic_name__ : Tuple , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , *__magic_name__ : Any ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : str = self.num_labels UpperCAmelCase_ : Any = BioGptForTokenClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" UpperCAmelCase_ : List[Any] = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : int = config_and_inputs UpperCAmelCase_ : Any = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __a (lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : str = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) __a : List[Any] = (BioGptForCausalLM,) if is_torch_available() else () __a : Union[str, Any] = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) __a : List[str] = False def UpperCAmelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" UpperCAmelCase_ : List[str] = BioGptModelTester(self ) UpperCAmelCase_ : Optional[Any] = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ : str = type self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*__magic_name__ , gradient_checkpointing=__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*__magic_name__ ) def UpperCAmelCase__ ( self : Dict ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*__magic_name__ ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*__magic_name__ ) @slow def UpperCAmelCase__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) model.to(__magic_name__ ) UpperCAmelCase_ : List[str] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : Tuple = '''left''' # Define PAD Token = EOS Token = 50256 UpperCAmelCase_ : List[Any] = tokenizer.eos_token UpperCAmelCase_ : List[Any] = model.config.eos_token_id # use different length sentences to test batching UpperCAmelCase_ : Tuple = [ '''Hello, my dog is a little''', '''Today, I''', ] UpperCAmelCase_ : Optional[Any] = tokenizer(__magic_name__ , return_tensors='''pt''' , padding=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = inputs['''input_ids'''].to(__magic_name__ ) UpperCAmelCase_ : Any = model.generate( input_ids=__magic_name__ , attention_mask=inputs['''attention_mask'''].to(__magic_name__ ) , ) UpperCAmelCase_ : Union[str, Any] = tokenizer(sentences[0] , return_tensors='''pt''' ).input_ids.to(__magic_name__ ) UpperCAmelCase_ : Tuple = model.generate(input_ids=__magic_name__ ) UpperCAmelCase_ : List[str] = inputs_non_padded.shape[-1] - inputs['''attention_mask'''][-1].long().sum().cpu().item() UpperCAmelCase_ : List[Any] = tokenizer(sentences[1] , return_tensors='''pt''' ).input_ids.to(__magic_name__ ) UpperCAmelCase_ : Tuple = model.generate(input_ids=__magic_name__ , max_length=model.config.max_length - num_paddings ) UpperCAmelCase_ : int = tokenizer.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Dict = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = [ '''Hello, my dog is a little bit bigger than a little bit.''', '''Today, I have a good idea of how to use the information''', ] self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertListEqual(__magic_name__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : List[Any] = BioGptModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : str = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : List[str] = 3 UpperCAmelCase_ : Tuple = input_dict['''input_ids'''] UpperCAmelCase_ : Dict = input_ids.ne(1 ).to(__magic_name__ ) UpperCAmelCase_ : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCAmelCase_ : Dict = BioGptForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : int = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : List[Any] = 3 UpperCAmelCase_ : Optional[int] = '''multi_label_classification''' UpperCAmelCase_ : int = input_dict['''input_ids'''] UpperCAmelCase_ : str = input_ids.ne(1 ).to(__magic_name__ ) UpperCAmelCase_ : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCAmelCase_ : Union[str, Any] = BioGptForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : str = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __a (unittest.TestCase ): @slow def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" UpperCAmelCase_ : str = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : List[str] = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCAmelCase_ : str = model(__magic_name__ )[0] UpperCAmelCase_ : Optional[int] = 4_23_84 UpperCAmelCase_ : Tuple = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , __magic_name__ ) UpperCAmelCase_ : List[Any] = torch.tensor( [[[-9.5_2_3_6, -9.8_9_1_8, 1_0.4_5_5_7], [-1_1.0_4_6_9, -9.6_4_2_3, 8.1_0_2_2], [-8.8_6_6_4, -7.8_8_2_6, 5.5_3_2_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __magic_name__ , atol=1E-4 ) ) @slow def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Any = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : str = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) model.to(__magic_name__ ) torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = tokenizer('''COVID-19 is''' , return_tensors='''pt''' ).to(__magic_name__ ) UpperCAmelCase_ : Optional[int] = model.generate( **__magic_name__ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=__magic_name__ , ) UpperCAmelCase_ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = ( '''COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the''' ''' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and''' ''' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),''' ''' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and''' ''' more than 800,000 deaths.''' ) self.assertEqual(__magic_name__ , __magic_name__ )
644
0
'''simple docstring''' import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class __a (lowerCamelCase , unittest.TestCase ): # TODO: is there an appropriate internal test set? __a : Optional[Any] = "ssube/stable-diffusion-x4-upscaler-onnx" def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Union[str, Any]=0 ) -> List[str]: """simple docstring""" UpperCAmelCase_ : List[Any] = floats_tensor((1, 3, 1_28, 1_28) , rng=random.Random(__magic_name__ ) ) UpperCAmelCase_ : List[str] = torch.manual_seed(__magic_name__ ) UpperCAmelCase_ : int = { '''prompt''': '''A painting of a squirrel eating a burger''', '''image''': image, '''generator''': generator, '''num_inference_steps''': 3, '''guidance_scale''': 7.5, '''output_type''': '''numpy''', } return inputs def UpperCAmelCase__ ( self : Dict ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Dict = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : List[str] = self.get_dummy_inputs() UpperCAmelCase_ : List[Any] = pipe(**__magic_name__ ).images UpperCAmelCase_ : str = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Optional[Any] = np.array( [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3] ) assert np.abs(image_slice - expected_slice ).max() < 1E-1 def UpperCAmelCase__ ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) UpperCAmelCase_ : Any = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : int = self.get_dummy_inputs() UpperCAmelCase_ : Union[str, Any] = pipe(**__magic_name__ ).images UpperCAmelCase_ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Any = np.array( [0.6_8_9_8_8_9_2, 0.5_9_2_4_0_5_5_6, 0.5_2_4_9_9_5_2_7, 0.5_8_8_6_6_2_1_5, 0.5_2_2_5_8_2_3_5, 0.5_2_5_7_2_7_1_5, 0.6_2_4_1_4_4_7_3, 0.6_1_7_4_3_8_7, 0.6_2_1_4_9_6_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" UpperCAmelCase_ : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) UpperCAmelCase_ : int = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = self.get_dummy_inputs() UpperCAmelCase_ : str = pipe(**__magic_name__ ).images UpperCAmelCase_ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Dict = np.array( [0.7_6_5_9_2_7_8, 0.7_6_4_3_7_6_6_4, 0.7_5_5_7_9_1_0_7, 0.7_6_9_1_1_1_6, 0.7_7_6_6_6_9_8_6, 0.7_7_2_7_6_7_2, 0.7_7_5_8_6_6_4, 0.7_8_1_2_2_2_6, 0.7_6_9_4_2_5_1_5] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def UpperCAmelCase__ ( self : int ) -> Dict: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) UpperCAmelCase_ : Optional[Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : List[str] = self.get_dummy_inputs() UpperCAmelCase_ : Optional[int] = pipe(**__magic_name__ ).images UpperCAmelCase_ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Optional[Any] = np.array( [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 def UpperCAmelCase__ ( self : Tuple ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint , provider='''CPUExecutionProvider''' ) UpperCAmelCase_ : Dict = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : List[Any] = self.get_dummy_inputs() UpperCAmelCase_ : int = pipe(**__magic_name__ ).images UpperCAmelCase_ : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Union[str, Any] = np.array( [0.7_7_4_2_4_4_9_6, 0.7_7_3_6_0_1, 0.7_6_4_5_2_8_8, 0.7_7_6_9_5_9_8, 0.7_7_7_2_7_3_9, 0.7_7_3_8_6_8_8, 0.7_8_1_8_7_2_3_3, 0.7_7_8_7_9_5_8_4, 0.7_6_7_0_4_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 @nightly @require_onnxruntime @require_torch_gpu class __a (unittest.TestCase ): @property def UpperCAmelCase__ ( self : Any ) -> int: """simple docstring""" return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" UpperCAmelCase_ : Dict = ort.SessionOptions() UpperCAmelCase_ : Optional[int] = False return options def UpperCAmelCase__ ( self : Any ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) UpperCAmelCase_ : int = init_image.resize((1_28, 1_28) ) # using the PNDM scheduler by default UpperCAmelCase_ : Any = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : List[Any] = '''A fantasy landscape, trending on artstation''' UpperCAmelCase_ : str = torch.manual_seed(0 ) UpperCAmelCase_ : List[Any] = pipe( prompt=__magic_name__ , image=__magic_name__ , guidance_scale=7.5 , num_inference_steps=10 , generator=__magic_name__ , output_type='''np''' , ) UpperCAmelCase_ : List[str] = output.images UpperCAmelCase_ : Dict = images[0, 2_55:2_58, 3_83:3_86, -1] assert images.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : int = np.array([0.4_8_8_3, 0.4_9_4_7, 0.4_9_8_0, 0.4_9_7_5, 0.4_9_8_2, 0.4_9_8_0, 0.5_0_0_0, 0.5_0_0_6, 0.4_9_7_2] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2 def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/img2img/sketch-mountains-input.jpg''' ) UpperCAmelCase_ : int = init_image.resize((1_28, 1_28) ) UpperCAmelCase_ : Optional[int] = LMSDiscreteScheduler.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , subfolder='''scheduler''' ) UpperCAmelCase_ : int = OnnxStableDiffusionUpscalePipeline.from_pretrained( '''ssube/stable-diffusion-x4-upscaler-onnx''' , scheduler=__magic_name__ , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : List[Any] = '''A fantasy landscape, trending on artstation''' UpperCAmelCase_ : Any = torch.manual_seed(0 ) UpperCAmelCase_ : Dict = pipe( prompt=__magic_name__ , image=__magic_name__ , guidance_scale=7.5 , num_inference_steps=20 , generator=__magic_name__ , output_type='''np''' , ) UpperCAmelCase_ : int = output.images UpperCAmelCase_ : List[str] = images[0, 2_55:2_58, 3_83:3_86, -1] assert images.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Optional[Any] = np.array( [0.5_0_1_7_3_7_5_3, 0.5_0_2_2_3_3_5_6, 0.5_0_2_0_3_9, 0.5_0_2_3_3_0_3_6, 0.5_0_2_3_7_2_5, 0.5_0_2_2_6_0_1, 0.5_0_1_8_7_5_8, 0.5_0_2_3_4_0_8_5, 0.5_0_2_4_1_5_6_6] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2E-2
707
'''simple docstring''' import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class __a (lowerCamelCase , unittest.TestCase ): __a : List[str] = BlenderbotSmallTokenizer __a : List[Any] = False def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" super().setUp() UpperCAmelCase_ : Tuple = ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__'''] UpperCAmelCase_ : Optional[Any] = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) UpperCAmelCase_ : int = ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', ''''''] UpperCAmelCase_ : Optional[Any] = {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''} UpperCAmelCase_ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__magic_name__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__magic_name__ ) ) def UpperCAmelCase__ ( self : List[Any] , **__magic_name__ : Dict ) -> Tuple: """simple docstring""" kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : List[str] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : str = '''adapt act apte''' UpperCAmelCase_ : Tuple = '''adapt act apte''' return input_text, output_text def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" UpperCAmelCase_ : str = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCAmelCase_ : List[Any] = '''adapt act apte''' UpperCAmelCase_ : Dict = ['''adapt''', '''act''', '''ap@@''', '''te'''] UpperCAmelCase_ : Dict = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) UpperCAmelCase_ : Tuple = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" UpperCAmelCase_ : List[Any] = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) assert tok('''sam''' ).input_ids == [13_84] UpperCAmelCase_ : Optional[int] = '''I am a small frog.''' UpperCAmelCase_ : List[str] = tok([src_text] , padding=__magic_name__ , truncation=__magic_name__ )['''input_ids'''] UpperCAmelCase_ : Dict = tok.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ , clean_up_tokenization_spaces=__magic_name__ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) UpperCAmelCase_ : List[Any] = '''I am a small frog .''' UpperCAmelCase_ : Any = '''.''' UpperCAmelCase_ : List[Any] = tok(__magic_name__ )['''input_ids'''] UpperCAmelCase_ : Optional[int] = tok(__magic_name__ )['''input_ids'''] assert encoded[-1] == encoded_dot[0]
644
0
'''simple docstring''' import os import unittest from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer from transformers.testing_utils import get_tests_dir from ...test_tokenization_common import TokenizerTesterMixin snake_case_ : int = get_tests_dir("fixtures/test_sentencepiece_bpe.model") class __a (lowerCamelCase , unittest.TestCase ): __a : str = BartphoTokenizer __a : Any = False __a : Dict = True def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" super().setUp() UpperCAmelCase_ : Tuple = ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] UpperCAmelCase_ : Optional[int] = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) UpperCAmelCase_ : Optional[int] = {'''unk_token''': '''<unk>'''} UpperCAmelCase_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''monolingual_vocab_file'''] ) with open(self.monolingual_vocab_file , '''w''' , encoding='''utf-8''' ) as fp: for token in vocab_tokens: fp.write(F"""{token} {vocab_tokens[token]}\n""" ) UpperCAmelCase_ : int = BartphoTokenizer(__magic_name__ , self.monolingual_vocab_file , **self.special_tokens_map ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self : str , **__magic_name__ : Dict ) -> Optional[Any]: """simple docstring""" kwargs.update(self.special_tokens_map ) return BartphoTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : Tuple ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = '''This is a là test''' UpperCAmelCase_ : List[Any] = '''This is a<unk><unk> test''' return input_text, output_text def UpperCAmelCase__ ( self : List[Any] ) -> Any: """simple docstring""" UpperCAmelCase_ : str = BartphoTokenizer(__magic_name__ , self.monolingual_vocab_file , **self.special_tokens_map ) UpperCAmelCase_ : str = '''This is a là test''' UpperCAmelCase_ : int = '''▁This ▁is ▁a ▁l à ▁t est'''.split() UpperCAmelCase_ : str = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) UpperCAmelCase_ : Dict = tokens + [tokenizer.unk_token] UpperCAmelCase_ : Dict = [4, 5, 6, 3, 3, 7, 8, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ )
708
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" UpperCAmelCase_ : Dict = get_activation('''swish''' ) self.assertIsInstance(__magic_name__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , 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 : Tuple ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = get_activation('''silu''' ) self.assertIsInstance(__magic_name__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , 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 : Tuple ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Optional[int] = get_activation('''mish''' ) self.assertIsInstance(__magic_name__ , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , 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 : str ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = get_activation('''gelu''' ) self.assertIsInstance(__magic_name__ , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , 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 )
644
0
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler snake_case_ : Optional[int] = 16 snake_case_ : Tuple = 32 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Accelerator, SCREAMING_SNAKE_CASE__ : int = 16, SCREAMING_SNAKE_CASE__ : str = "bert-base-cased" ) -> Dict: UpperCAmelCase_ : Dict = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = load_dataset('''glue''', '''mrpc''' ) def tokenize_function(SCREAMING_SNAKE_CASE__ : Optional[int] ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase_ : Union[str, Any] = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=SCREAMING_SNAKE_CASE__, max_length=SCREAMING_SNAKE_CASE__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase_ : Tuple = datasets.map( SCREAMING_SNAKE_CASE__, batched=SCREAMING_SNAKE_CASE__, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], load_from_cache_file=SCREAMING_SNAKE_CASE__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase_ : Optional[Any] = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(SCREAMING_SNAKE_CASE__ : str ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(SCREAMING_SNAKE_CASE__, padding='''max_length''', max_length=128, return_tensors='''pt''' ) return tokenizer.pad(SCREAMING_SNAKE_CASE__, padding='''longest''', return_tensors='''pt''' ) # Instantiate dataloaders. UpperCAmelCase_ : str = DataLoader( tokenized_datasets['''train'''], shuffle=SCREAMING_SNAKE_CASE__, collate_fn=SCREAMING_SNAKE_CASE__, batch_size=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = DataLoader( tokenized_datasets['''validation'''], shuffle=SCREAMING_SNAKE_CASE__, collate_fn=SCREAMING_SNAKE_CASE__, batch_size=SCREAMING_SNAKE_CASE__ ) return train_dataloader, eval_dataloader def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Optional[int], SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Any ) -> Any: model.eval() UpperCAmelCase_ : List[str] = 0 for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase_ : Dict = model(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : str = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCAmelCase_ : List[str] = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(SCREAMING_SNAKE_CASE__ ) - 1: UpperCAmelCase_ : Tuple = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCAmelCase_ : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=SCREAMING_SNAKE_CASE__, references=SCREAMING_SNAKE_CASE__, ) UpperCAmelCase_ : List[str] = metric.compute() return eval_metric["accuracy"] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : int ) -> Tuple: # Initialize accelerator UpperCAmelCase_ : Union[str, Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase_ : int = config['''lr'''] UpperCAmelCase_ : Optional[int] = int(config['''num_epochs'''] ) UpperCAmelCase_ : Optional[int] = int(config['''seed'''] ) UpperCAmelCase_ : List[str] = int(config['''batch_size'''] ) UpperCAmelCase_ : Optional[int] = args.model_name_or_path set_seed(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Union[str, Any] = get_dataloaders(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase_ : List[Any] = AutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__, return_dict=SCREAMING_SNAKE_CASE__ ) # Instantiate optimizer UpperCAmelCase_ : str = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCAmelCase_ : List[str] = optimizer_cls(params=model.parameters(), lr=SCREAMING_SNAKE_CASE__ ) if accelerator.state.deepspeed_plugin is not None: UpperCAmelCase_ : List[Any] = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: UpperCAmelCase_ : Tuple = 1 UpperCAmelCase_ : int = (len(SCREAMING_SNAKE_CASE__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCAmelCase_ : Tuple = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE__, num_warmup_steps=0, num_training_steps=SCREAMING_SNAKE_CASE__, ) else: UpperCAmelCase_ : Any = DummyScheduler(SCREAMING_SNAKE_CASE__, total_num_steps=SCREAMING_SNAKE_CASE__, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCAmelCase_ : Union[str, Any] = accelerator.prepare( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase_ : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly UpperCAmelCase_ : Dict = 0 UpperCAmelCase_ : int = evaluate.load('''glue''', '''mrpc''' ) UpperCAmelCase_ : Optional[Any] = num_epochs if args.partial_train_epoch is not None: UpperCAmelCase_ : List[Any] = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) UpperCAmelCase_ : Tuple = args.resume_from_checkpoint.split('''epoch_''' )[1] UpperCAmelCase_ : int = '''''' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break UpperCAmelCase_ : Union[str, Any] = int(SCREAMING_SNAKE_CASE__ ) + 1 UpperCAmelCase_ : Dict = evaluation_loop(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) accelerator.print('''resumed checkpoint performance:''', SCREAMING_SNAKE_CASE__ ) accelerator.print('''resumed checkpoint\'s scheduler\'s lr:''', lr_scheduler.get_lr()[0] ) accelerator.print('''resumed optimizers\'s lr:''', optimizer.param_groups[0]['''lr'''] ) with open(os.path.join(args.output_dir, F"""state_{starting_epoch-1}.json""" ), '''r''' ) as f: UpperCAmelCase_ : Optional[int] = json.load(SCREAMING_SNAKE_CASE__ ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model UpperCAmelCase_ : int = {} for epoch in range(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Optional[int] = model(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Any = outputs.loss UpperCAmelCase_ : Tuple = loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 UpperCAmelCase_ : Tuple = F"""epoch_{epoch}""" UpperCAmelCase_ : Optional[int] = os.path.join(args.output_dir, SCREAMING_SNAKE_CASE__ ) accelerator.save_state(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = evaluation_loop(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[Any] = accuracy UpperCAmelCase_ : Any = lr_scheduler.get_lr()[0] UpperCAmelCase_ : List[str] = optimizer.param_groups[0]['''lr'''] UpperCAmelCase_ : Tuple = epoch UpperCAmelCase_ : Dict = overall_step accelerator.print(F"""epoch {epoch}:""", SCREAMING_SNAKE_CASE__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F"""state_{epoch}.json""" ), '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( ) -> List[str]: UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''', type=SCREAMING_SNAKE_CASE__, default='''bert-base-cased''', help='''Path to pretrained model or model identifier from huggingface.co/models.''', required=SCREAMING_SNAKE_CASE__, ) parser.add_argument( '''--output_dir''', type=SCREAMING_SNAKE_CASE__, default='''.''', help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''', ) parser.add_argument( '''--resume_from_checkpoint''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''If the training should continue from a checkpoint folder.''', ) parser.add_argument( '''--partial_train_epoch''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''If passed, the training will stop after this number of epochs.''', ) parser.add_argument( '''--num_epochs''', type=SCREAMING_SNAKE_CASE__, default=2, help='''Number of train epochs.''', ) UpperCAmelCase_ : Optional[int] = parser.parse_args() UpperCAmelCase_ : List[Any] = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
709
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging snake_case_ : Union[str, Any] = logging.get_logger(__name__) class __a (lowerCamelCase ): __a : Tuple = ["pixel_values"] def __init__( self : List[Any] , __magic_name__ : bool = True , __magic_name__ : int = 32 , __magic_name__ : Union[str, Any]=PILImageResampling.BILINEAR , __magic_name__ : bool = True , **__magic_name__ : List[str] , ) -> None: """simple docstring""" UpperCAmelCase_ : int = do_resize UpperCAmelCase_ : Tuple = do_rescale UpperCAmelCase_ : List[Any] = size_divisor UpperCAmelCase_ : Any = resample super().__init__(**__magic_name__ ) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : np.ndarray , __magic_name__ : int , __magic_name__ : str , __magic_name__ : Optional[ChannelDimension] = None , **__magic_name__ : Tuple ) -> np.ndarray: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : List[str] = get_image_size(__magic_name__ ) # Rounds the height and width down to the closest multiple of size_divisor UpperCAmelCase_ : Dict = height // size_divisor * size_divisor UpperCAmelCase_ : Dict = width // size_divisor * size_divisor UpperCAmelCase_ : Any = resize(__magic_name__ , (new_h, new_w) , resample=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) return image def UpperCAmelCase__ ( self : int , __magic_name__ : np.ndarray , __magic_name__ : float , __magic_name__ : Optional[ChannelDimension] = None , **__magic_name__ : Optional[Any] ) -> np.ndarray: """simple docstring""" return rescale(image=__magic_name__ , scale=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : str , __magic_name__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[int] = None , __magic_name__ : Any=None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[Union[TensorType, str]] = None , __magic_name__ : ChannelDimension = ChannelDimension.FIRST , **__magic_name__ : Tuple , ) -> BatchFeature: """simple docstring""" UpperCAmelCase_ : Dict = do_resize if do_resize is not None else self.do_resize UpperCAmelCase_ : str = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ : Any = size_divisor if size_divisor is not None else self.size_divisor UpperCAmelCase_ : Dict = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('''size_divisor is required for resizing''' ) UpperCAmelCase_ : Optional[int] = make_list_of_images(__magic_name__ ) if not valid_images(__magic_name__ ): raise ValueError('''Invalid image(s)''' ) # All transformations expect numpy arrays. UpperCAmelCase_ : List[str] = [to_numpy_array(__magic_name__ ) for img in images] if do_resize: UpperCAmelCase_ : str = [self.resize(__magic_name__ , size_divisor=__magic_name__ , resample=__magic_name__ ) for image in images] if do_rescale: UpperCAmelCase_ : Tuple = [self.rescale(__magic_name__ , scale=1 / 2_55 ) for image in images] UpperCAmelCase_ : Union[str, Any] = [to_channel_dimension_format(__magic_name__ , __magic_name__ ) for image in images] UpperCAmelCase_ : int = {'''pixel_values''': images} return BatchFeature(data=__magic_name__ , tensor_type=__magic_name__ )
644
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) snake_case_ = {"configuration_plbart": ["PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "PLBartConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = ["PLBartTokenizer"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ = [ "PLBART_PRETRAINED_MODEL_ARCHIVE_LIST", "PLBartForCausalLM", "PLBartForConditionalGeneration", "PLBartForSequenceClassification", "PLBartModel", "PLBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_plbart import PLBART_PRETRAINED_CONFIG_ARCHIVE_MAP, PLBartConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_plbart import PLBartTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_plbart import ( PLBART_PRETRAINED_MODEL_ARCHIVE_LIST, PLBartForCausalLM, PLBartForConditionalGeneration, PLBartForSequenceClassification, PLBartModel, PLBartPreTrainedModel, ) else: import sys snake_case_ = _LazyModule(__name__, globals()["__file__"], _import_structure)
710
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int = 10, SCREAMING_SNAKE_CASE__ : int = 22 ) -> int: UpperCAmelCase_ : Optional[int] = range(1, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = range(1, SCREAMING_SNAKE_CASE__ ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(f'''{solution(10, 22) = }''')
644
0
'''simple docstring''' import torch from diffusers import StableDiffusionPipeline snake_case_ : int = "path-to-your-trained-model" snake_case_ : Optional[Any] = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to("cuda") snake_case_ : int = "A photo of sks dog in a bucket" snake_case_ : Optional[Any] = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0] image.save("dog-bucket.png")
711
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __a (lowerCamelCase ): __a : int = "dandelin/vilt-b32-finetuned-vqa" __a : Any = ( "This is a tool that answers a question about an image. It takes an input named `image` which should be the " "image containing the information, as well as a `question` which should be the question in English. It " "returns a text that is the answer to the question." ) __a : Any = "image_qa" __a : str = AutoProcessor __a : Any = AutoModelForVisualQuestionAnswering __a : List[Any] = ["image", "text"] __a : int = ["text"] def __init__( self : Tuple , *__magic_name__ : Any , **__magic_name__ : Any ) -> Tuple: """simple docstring""" requires_backends(self , ['''vision'''] ) super().__init__(*__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : "Image" , __magic_name__ : str ) -> Tuple: """simple docstring""" return self.pre_processor(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) def UpperCAmelCase__ ( self : Any , __magic_name__ : List[str] ) -> Optional[Any]: """simple docstring""" with torch.no_grad(): return self.model(**__magic_name__ ).logits def UpperCAmelCase__ ( self : int , __magic_name__ : int ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Dict = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
644
0
'''simple docstring''' import json import os from functools import lru_cache from typing import TYPE_CHECKING, List, Optional, Tuple import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation snake_case_ : Optional[Any] = logging.get_logger(__name__) snake_case_ : str = { "vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_config_file": "tokenizer_config.json", } snake_case_ : Any = { "vocab_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"}, "merges_file": {"facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"}, "tokenizer_config_file": { "facebook/blenderbot-3B": "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json" }, } snake_case_ : List[Any] = {"facebook/blenderbot-3B": 1_28} @lru_cache() # Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode def lowerCamelCase_ ( ) -> List[Any]: UpperCAmelCase_ : Any = ( list(range(ord('''!''' ), ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ), ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ), ord('''ÿ''' ) + 1 ) ) ) UpperCAmelCase_ : Optional[int] = bs[:] UpperCAmelCase_ : List[Any] = 0 for b in range(2**8 ): if b not in bs: bs.append(SCREAMING_SNAKE_CASE__ ) cs.append(2**8 + n ) n += 1 UpperCAmelCase_ : Dict = [chr(SCREAMING_SNAKE_CASE__ ) for n in cs] return dict(zip(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Any ) -> str: UpperCAmelCase_ : List[Any] = set() UpperCAmelCase_ : Any = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCAmelCase_ : Optional[int] = char return pairs class __a (lowerCamelCase ): __a : List[Any] = VOCAB_FILES_NAMES __a : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP __a : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a : List[Any] = ["input_ids", "attention_mask"] def __init__( self : int , __magic_name__ : List[str] , __magic_name__ : Any , __magic_name__ : str="replace" , __magic_name__ : Optional[Any]="<s>" , __magic_name__ : List[Any]="</s>" , __magic_name__ : Any="</s>" , __magic_name__ : List[str]="<s>" , __magic_name__ : Union[str, Any]="<unk>" , __magic_name__ : List[str]="<pad>" , __magic_name__ : str="<mask>" , __magic_name__ : Any=False , **__magic_name__ : Tuple , ) -> Tuple: """simple docstring""" UpperCAmelCase_ : int = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else bos_token UpperCAmelCase_ : int = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else eos_token UpperCAmelCase_ : str = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else sep_token UpperCAmelCase_ : Tuple = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else cls_token UpperCAmelCase_ : Optional[int] = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else unk_token UpperCAmelCase_ : Dict = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase_ : Dict = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else mask_token super().__init__( errors=__magic_name__ , bos_token=__magic_name__ , eos_token=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , cls_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , add_prefix_space=__magic_name__ , **__magic_name__ , ) with open(__magic_name__ , encoding='''utf-8''' ) as vocab_handle: UpperCAmelCase_ : Dict = json.load(__magic_name__ ) UpperCAmelCase_ : List[Any] = {v: k for k, v in self.encoder.items()} UpperCAmelCase_ : Any = errors # how to handle errors in decoding UpperCAmelCase_ : Optional[int] = bytes_to_unicode() UpperCAmelCase_ : List[Any] = {v: k for k, v in self.byte_encoder.items()} with open(__magic_name__ , encoding='''utf-8''' ) as merges_handle: UpperCAmelCase_ : str = merges_handle.read().split('''\n''' )[1:-1] UpperCAmelCase_ : List[Any] = [tuple(merge.split() ) for merge in bpe_merges] UpperCAmelCase_ : Tuple = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) UpperCAmelCase_ : List[str] = {} UpperCAmelCase_ : Union[str, Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions UpperCAmelCase_ : Any = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.roberta.tokenization_roberta.RobertaTokenizer.vocab_size with Roberta->Blenderbot, RoBERTa->Blenderbot def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" return len(self.encoder ) def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase__ ( self : int , __magic_name__ : List[str] ) -> str: """simple docstring""" if token in self.cache: return self.cache[token] UpperCAmelCase_ : List[Any] = tuple(__magic_name__ ) UpperCAmelCase_ : int = get_pairs(__magic_name__ ) if not pairs: return token while True: UpperCAmelCase_ : Any = min(__magic_name__ , key=lambda __magic_name__ : self.bpe_ranks.get(__magic_name__ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break UpperCAmelCase_ : Optional[int] = bigram UpperCAmelCase_ : int = [] UpperCAmelCase_ : List[str] = 0 while i < len(__magic_name__ ): try: UpperCAmelCase_ : Any = word.index(__magic_name__ , __magic_name__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) UpperCAmelCase_ : Optional[int] = j if word[i] == first and i < len(__magic_name__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 UpperCAmelCase_ : Union[str, Any] = tuple(__magic_name__ ) UpperCAmelCase_ : List[Any] = new_word if len(__magic_name__ ) == 1: break else: UpperCAmelCase_ : Any = get_pairs(__magic_name__ ) UpperCAmelCase_ : Optional[int] = ''' '''.join(__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = word return word def UpperCAmelCase__ ( self : int , __magic_name__ : List[Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = [] for token in re.findall(self.pat , __magic_name__ ): UpperCAmelCase_ : Tuple = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__magic_name__ ).split(''' ''' ) ) return bpe_tokens def UpperCAmelCase__ ( self : str , __magic_name__ : str ) -> str: """simple docstring""" return self.encoder.get(__magic_name__ , self.encoder.get(self.unk_token ) ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : List[Any] ) -> List[Any]: """simple docstring""" return self.decoder.get(__magic_name__ ) def UpperCAmelCase__ ( self : int , __magic_name__ : Tuple ) -> str: """simple docstring""" UpperCAmelCase_ : Optional[Any] = ''''''.join(__magic_name__ ) UpperCAmelCase_ : Tuple = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase_ : List[Any] = os.path.join( __magic_name__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase_ : Tuple = os.path.join( __magic_name__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(__magic_name__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__magic_name__ , ensure_ascii=__magic_name__ ) + '''\n''' ) UpperCAmelCase_ : int = 0 with open(__magic_name__ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __magic_name__ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) UpperCAmelCase_ : Optional[int] = token_index writer.write(''' '''.join(__magic_name__ ) + '''\n''' ) index += 1 return vocab_file, merge_file def UpperCAmelCase__ ( self : str , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None , __magic_name__ : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) if token_ids_a is None: return [1] + ([0] * len(__magic_name__ )) + [1] return [1] + ([0] * len(__magic_name__ )) + [1, 1] + ([0] * len(__magic_name__ )) + [1] def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCAmelCase_ : Any = [self.sep_token_id] UpperCAmelCase_ : Optional[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 : List[Any] , __magic_name__ : List[Any] , __magic_name__ : str=False , **__magic_name__ : Optional[Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Optional[Any] = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__magic_name__ ) > 0 and not text[0].isspace()): UpperCAmelCase_ : List[str] = ''' ''' + text return (text, kwargs) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ) -> List[Any]: """simple docstring""" return token_ids_a + [self.eos_token_id] def UpperCAmelCase__ ( self : Dict , __magic_name__ : "Conversation" ) -> List[int]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = [] for is_user, text in conversation.iter_texts(): if is_user: # We need to space prefix as it's being done within blenderbot inputs.append(''' ''' + text ) else: # Generated responses should contain them already. inputs.append(__magic_name__ ) UpperCAmelCase_ : Optional[int] = ''' '''.join(__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = self.encode(__magic_name__ ) if len(__magic_name__ ) > self.model_max_length: UpperCAmelCase_ : Tuple = input_ids[-self.model_max_length :] logger.warning(F"""Trimmed input from conversation as it was longer than {self.model_max_length} tokens.""" ) return input_ids
712
'''simple docstring''' from collections.abc import Iterable from typing import Any class __a : def __init__( self : Optional[Any] , __magic_name__ : int | None = None ) -> Tuple: """simple docstring""" UpperCAmelCase_ : List[str] = value UpperCAmelCase_ : Node | None = None # Added in order to delete a node easier UpperCAmelCase_ : Node | None = None UpperCAmelCase_ : Node | None = None def __repr__( self : List[str] ) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({F"""{self.value}""": (self.left, self.right)} , indent=1 ) class __a : def __init__( self : int , __magic_name__ : Node | None = None ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : str = root def __str__( self : Any ) -> str: """simple docstring""" return str(self.root ) def UpperCAmelCase__ ( self : Any , __magic_name__ : Node , __magic_name__ : Node | None ) -> None: """simple docstring""" if new_children is not None: # reset its kids UpperCAmelCase_ : Dict = node.parent if node.parent is not None: # reset its parent if self.is_right(__magic_name__ ): # If it is the right children UpperCAmelCase_ : Optional[Any] = new_children else: UpperCAmelCase_ : Optional[int] = new_children else: UpperCAmelCase_ : List[str] = new_children def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Node ) -> bool: """simple docstring""" if node.parent and node.parent.right: return node == node.parent.right return False def UpperCAmelCase__ ( self : Union[str, Any] ) -> bool: """simple docstring""" return self.root is None def UpperCAmelCase__ ( self : Any , __magic_name__ : str ) -> None: """simple docstring""" UpperCAmelCase_ : Tuple = Node(__magic_name__ ) # create a new Node if self.empty(): # if Tree is empty UpperCAmelCase_ : List[Any] = new_node # set its root else: # Tree is not empty UpperCAmelCase_ : str = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: UpperCAmelCase_ : Union[str, Any] = new_node # We insert the new node in a leaf break else: UpperCAmelCase_ : List[Any] = parent_node.left else: if parent_node.right is None: UpperCAmelCase_ : List[Any] = new_node break else: UpperCAmelCase_ : Union[str, Any] = parent_node.right UpperCAmelCase_ : Union[str, Any] = parent_node def UpperCAmelCase__ ( self : Optional[Any] , *__magic_name__ : List[str] ) -> None: """simple docstring""" for value in values: self.__insert(__magic_name__ ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : int ) -> Node | None: """simple docstring""" if self.empty(): raise IndexError('''Warning: Tree is empty! please use another.''' ) else: UpperCAmelCase_ : str = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: UpperCAmelCase_ : List[str] = node.left if value < node.value else node.right return node def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Node | None = None ) -> Node | None: """simple docstring""" if node is None: if self.root is None: return None UpperCAmelCase_ : Dict = self.root if not self.empty(): while node.right is not None: UpperCAmelCase_ : Any = node.right return node def UpperCAmelCase__ ( self : Dict , __magic_name__ : Node | None = None ) -> Node | None: """simple docstring""" if node is None: UpperCAmelCase_ : Optional[int] = self.root if self.root is None: return None if not self.empty(): UpperCAmelCase_ : Union[str, Any] = self.root while node.left is not None: UpperCAmelCase_ : Dict = node.left return node def UpperCAmelCase__ ( self : Tuple , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : List[str] = self.search(__magic_name__ ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(__magic_name__ , __magic_name__ ) elif node.left is None: # Has only right children self.__reassign_nodes(__magic_name__ , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(__magic_name__ , node.left ) else: UpperCAmelCase_ : List[str] = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore UpperCAmelCase_ : Optional[int] = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Node | None ) -> Iterable: """simple docstring""" if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : List[Any]=None ) -> Any: """simple docstring""" if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : list , __magic_name__ : Node | None ) -> None: """simple docstring""" if node: self.inorder(__magic_name__ , node.left ) arr.append(node.value ) self.inorder(__magic_name__ , node.right ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : int , __magic_name__ : Node ) -> int: """simple docstring""" UpperCAmelCase_ : list[int] = [] self.inorder(__magic_name__ , __magic_name__ ) # append all values to list using inorder traversal return arr[k - 1] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Node | None ) -> list[Node]: UpperCAmelCase_ : Any = [] if curr_node is not None: UpperCAmelCase_ : Any = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def lowerCamelCase_ ( ) -> None: UpperCAmelCase_ : str = (8, 3, 6, 1, 10, 14, 13, 4, 7) UpperCAmelCase_ : Tuple = BinarySearchTree() for i in testlist: t.insert(SCREAMING_SNAKE_CASE__ ) # Prints all the elements of the list in order traversal print(SCREAMING_SNAKE_CASE__ ) if t.search(6 ) is not None: print('''The value 6 exists''' ) else: print('''The value 6 doesn\'t exist''' ) if t.search(-1 ) is not None: print('''The value -1 exists''' ) else: print('''The value -1 doesn\'t exist''' ) if not t.empty(): print('''Max Value: ''', t.get_max().value ) # type: ignore print('''Min Value: ''', t.get_min().value ) # type: ignore for i in testlist: t.remove(SCREAMING_SNAKE_CASE__ ) print(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
644
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : List[str] = [[1, 2, 4], [1, 2, 3, 4]] UpperCAmelCase_ : List[str] = DisjunctiveConstraint(__magic_name__ ) self.assertTrue(isinstance(dc.token_ids , __magic_name__ ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" UpperCAmelCase_ : Tuple = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(__magic_name__ ) # fails here def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] UpperCAmelCase_ : List[str] = DisjunctiveConstraint(__magic_name__ ) UpperCAmelCase_ : List[Any] = dc.update(1 ) UpperCAmelCase_ : Dict = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ : str = dc.update(2 ) UpperCAmelCase_ : Optional[Any] = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ : List[Any] = dc.update(3 ) UpperCAmelCase_ : Dict = stepped is True and completed is True and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase__ ( self : int ) -> Dict: """simple docstring""" UpperCAmelCase_ : Any = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] UpperCAmelCase_ : Tuple = DisjunctiveConstraint(__magic_name__ ) UpperCAmelCase_ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ : Optional[int] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ : int = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) UpperCAmelCase_ : int = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() UpperCAmelCase_ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ : Optional[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ : Optional[int] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
713
'''simple docstring''' import sys import turtle def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float] ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : int, ) -> None: my_pen.up() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) if depth == 0: return triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( "Correct format for using this script: " "python fractals.py <int:depth_for_fractal>" ) snake_case_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor("red") snake_case_ : Tuple = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
644
0
import copy import os import cva import numpy as np from matplotlib import pyplot as plt class __a : def __init__( self : int ) -> int: """simple docstring""" UpperCAmelCase_ : Optional[Any] = '''''' UpperCAmelCase_ : Tuple = '''''' UpperCAmelCase_ : int = [] UpperCAmelCase_ : str = 0 UpperCAmelCase_ : str = 2_56 UpperCAmelCase_ : Any = 0 UpperCAmelCase_ : List[str] = 0 UpperCAmelCase_ : Dict = 0 UpperCAmelCase_ : Tuple = 0 def UpperCAmelCase__ ( self : Any , __magic_name__ : Tuple ) -> Tuple: """simple docstring""" UpperCAmelCase_ : int = cva.imread(__magic_name__ , 0 ) UpperCAmelCase_ : str = copy.deepcopy(self.img ) UpperCAmelCase_ : int = plt.hist(self.img.ravel() , 2_56 , [0, 2_56] , label='''x''' ) UpperCAmelCase_ : Union[str, Any] = np.sum(__magic_name__ ) for i in range(len(__magic_name__ ) ): UpperCAmelCase_ : Dict = x[i] / self.k self.sk += prk UpperCAmelCase_ : List[Any] = (self.L - 1) * self.sk if self.rem != 0: UpperCAmelCase_ : str = int(last % last ) UpperCAmelCase_ : Tuple = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__magic_name__ ) UpperCAmelCase_ : List[Any] = int(np.ma.count(self.img ) / self.img[1].size ) UpperCAmelCase_ : str = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): UpperCAmelCase_ : List[str] = self.img[j][i] if num != self.last_list[num]: UpperCAmelCase_ : Any = self.last_list[num] cva.imwrite('''output_data/output.jpg''' , self.img ) def UpperCAmelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" plt.hist(self.img.ravel() , 2_56 , [0, 2_56] ) def UpperCAmelCase__ ( self : List[str] ) -> Any: """simple docstring""" cva.imshow('''Output-Image''' , self.img ) cva.imshow('''Input-Image''' , self.original_image ) cva.waitKey(50_00 ) cva.destroyAllWindows() if __name__ == "__main__": snake_case_ : Dict = os.path.join(os.path.basename(__file__), "image_data/input.jpg") snake_case_ : Tuple = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
714
'''simple docstring''' import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device snake_case_ : List[str] = False class __a (unittest.TestCase ): pass @nightly @require_torch_gpu class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCAmelCase_ : Optional[int] = torch.manual_seed(0 ) UpperCAmelCase_ : Union[str, Any] = pipe.dual_guided( prompt='''first prompt''' , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__magic_name__ ) UpperCAmelCase_ : Optional[int] = VersatileDiffusionPipeline.from_pretrained(__magic_name__ , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Any = generator.manual_seed(0 ) UpperCAmelCase_ : Dict = pipe.dual_guided( prompt='''first prompt''' , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : str = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = '''cyberpunk 2077''' UpperCAmelCase_ : Union[str, Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCAmelCase_ : Tuple = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = pipe.dual_guided( prompt=__magic_name__ , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images UpperCAmelCase_ : List[str] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Union[str, Any] = np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 UpperCAmelCase_ : Tuple = '''A painting of a squirrel eating a burger ''' UpperCAmelCase_ : Optional[int] = torch.manual_seed(0 ) UpperCAmelCase_ : List[Any] = pipe.text_to_image( prompt=__magic_name__ , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images UpperCAmelCase_ : Tuple = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Any = np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 UpperCAmelCase_ : Tuple = pipe.image_variation(__magic_name__ , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Optional[Any] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : List[str] = np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
644
0
'''simple docstring''' import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __a : def __init__( self : int , __magic_name__ : Optional[Any] , __magic_name__ : Any=13 , __magic_name__ : Any=7 , __magic_name__ : Union[str, Any]=True , __magic_name__ : Union[str, Any]=True , __magic_name__ : str=True , __magic_name__ : Optional[int]=True , __magic_name__ : List[Any]=99 , __magic_name__ : int=24 , __magic_name__ : Optional[int]=2 , __magic_name__ : Tuple=6 , __magic_name__ : Union[str, Any]=37 , __magic_name__ : Optional[Any]="gelu" , __magic_name__ : Any=0.1 , __magic_name__ : str=0.1 , __magic_name__ : Tuple=5_12 , __magic_name__ : Union[str, Any]=16 , __magic_name__ : Tuple=2 , __magic_name__ : Tuple=0.0_2 , __magic_name__ : Optional[Any]=3 , __magic_name__ : Optional[int]=None , __magic_name__ : Any=10_00 , ) -> str: """simple docstring""" UpperCAmelCase_ : Tuple = parent UpperCAmelCase_ : Optional[int] = batch_size UpperCAmelCase_ : List[str] = seq_length UpperCAmelCase_ : Dict = is_training UpperCAmelCase_ : List[str] = use_input_mask UpperCAmelCase_ : Any = use_token_type_ids UpperCAmelCase_ : Any = use_labels UpperCAmelCase_ : Any = vocab_size UpperCAmelCase_ : Dict = hidden_size UpperCAmelCase_ : Tuple = num_hidden_layers UpperCAmelCase_ : Tuple = num_attention_heads UpperCAmelCase_ : int = intermediate_size UpperCAmelCase_ : Union[str, Any] = hidden_act UpperCAmelCase_ : Optional[int] = hidden_dropout_prob UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase_ : Union[str, Any] = max_position_embeddings UpperCAmelCase_ : int = type_vocab_size UpperCAmelCase_ : List[Any] = type_sequence_label_size UpperCAmelCase_ : int = initializer_range UpperCAmelCase_ : Dict = num_labels UpperCAmelCase_ : List[str] = scope UpperCAmelCase_ : List[str] = range_bbox def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCAmelCase_ : List[str] = bbox[i, j, 3] UpperCAmelCase_ : Dict = bbox[i, j, 1] UpperCAmelCase_ : Optional[Any] = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCAmelCase_ : List[str] = bbox[i, j, 2] UpperCAmelCase_ : Tuple = bbox[i, j, 0] UpperCAmelCase_ : Union[str, Any] = t UpperCAmelCase_ : int = None if self.use_input_mask: UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCAmelCase_ : Optional[int] = None if self.use_token_type_ids: UpperCAmelCase_ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Dict = None UpperCAmelCase_ : Tuple = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : int = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : int , ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = LiltModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Optional[Any] = model(__magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : List[Any] = model(__magic_name__ , bbox=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : Optional[int] = model(__magic_name__ , bbox=__magic_name__ ) 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 : int , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[int] , __magic_name__ : List[Any] , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Any = self.num_labels UpperCAmelCase_ : List[Any] = LiltForTokenClassification(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : List[Any] = model( __magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : int , __magic_name__ : Tuple , __magic_name__ : Any , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : str = LiltForQuestionAnswering(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Optional[Any] = model( __magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , start_positions=__magic_name__ , end_positions=__magic_name__ , ) 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 : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = self.prepare_config_and_inputs() ( UpperCAmelCase_ ) : Optional[int] = config_and_inputs UpperCAmelCase_ : Tuple = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class __a (lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : Tuple = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __a : Any = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __a : Union[str, Any] = False __a : int = False def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : int ) -> str: """simple docstring""" return True def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = LiltModelTester(self ) UpperCAmelCase_ : List[Any] = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ : Tuple = type self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @slow def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Optional[int] = LiltModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) @require_torch @slow class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" UpperCAmelCase_ : str = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''' ).to(__magic_name__ ) UpperCAmelCase_ : Any = torch.tensor([[1, 2]] , device=__magic_name__ ) UpperCAmelCase_ : int = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=__magic_name__ ) # forward pass with torch.no_grad(): UpperCAmelCase_ : Optional[int] = model(input_ids=__magic_name__ , bbox=__magic_name__ ) UpperCAmelCase_ : int = torch.Size([1, 2, 7_68] ) UpperCAmelCase_ : List[str] = torch.tensor( [[-0.0_6_5_3, 0.0_9_5_0, -0.0_0_6_1], [-0.0_5_4_5, 0.0_9_2_6, -0.0_3_2_4]] , device=__magic_name__ , ) self.assertTrue(outputs.last_hidden_state.shape , __magic_name__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , __magic_name__ , atol=1E-3 ) )
715
'''simple docstring''' snake_case_ : int = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
644
0
'''simple docstring''' import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion" ) snake_case_ : List[Any] = None snake_case_ : Union[str, Any] = { "7B": 1_10_08, "13B": 1_38_24, "30B": 1_79_20, "65B": 2_20_16, "70B": 2_86_72, } snake_case_ : Dict = { "7B": 1, "7Bf": 1, "13B": 2, "13Bf": 2, "30B": 4, "65B": 8, "70B": 8, "70Bf": 8, } def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str], SCREAMING_SNAKE_CASE__ : Tuple=1, SCREAMING_SNAKE_CASE__ : List[str]=256 ) -> Dict: return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Any ) -> Union[str, Any]: with open(SCREAMING_SNAKE_CASE__, '''r''' ) as f: return json.load(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: with open(SCREAMING_SNAKE_CASE__, '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : List[Any]=True ) -> Dict: os.makedirs(SCREAMING_SNAKE_CASE__, exist_ok=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = os.path.join(SCREAMING_SNAKE_CASE__, '''tmp''' ) os.makedirs(SCREAMING_SNAKE_CASE__, exist_ok=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Any = read_json(os.path.join(SCREAMING_SNAKE_CASE__, '''params.json''' ) ) UpperCAmelCase_ : Dict = NUM_SHARDS[model_size] UpperCAmelCase_ : Any = params['''n_layers'''] UpperCAmelCase_ : Union[str, Any] = params['''n_heads'''] UpperCAmelCase_ : Optional[int] = n_heads // num_shards UpperCAmelCase_ : List[str] = params['''dim'''] UpperCAmelCase_ : Tuple = dim // n_heads UpperCAmelCase_ : Optional[Any] = 10000.0 UpperCAmelCase_ : Optional[int] = 1.0 / (base ** (torch.arange(0, SCREAMING_SNAKE_CASE__, 2 ).float() / dims_per_head)) if "n_kv_heads" in params: UpperCAmelCase_ : Tuple = params['''n_kv_heads'''] # for GQA / MQA UpperCAmelCase_ : str = n_heads_per_shard // num_key_value_heads UpperCAmelCase_ : str = dim // num_key_value_heads else: # compatibility with other checkpoints UpperCAmelCase_ : List[Any] = n_heads UpperCAmelCase_ : List[Any] = n_heads_per_shard UpperCAmelCase_ : Tuple = dim # permute for sliced rotary def permute(SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : int=n_heads, SCREAMING_SNAKE_CASE__ : List[Any]=dim, SCREAMING_SNAKE_CASE__ : Dict=dim ): return w.view(SCREAMING_SNAKE_CASE__, dima // n_heads // 2, 2, SCREAMING_SNAKE_CASE__ ).transpose(1, 2 ).reshape(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) print(F"""Fetching all parameters from the checkpoint at {input_base_path}.""" ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) UpperCAmelCase_ : int = torch.load(os.path.join(SCREAMING_SNAKE_CASE__, '''consolidated.00.pth''' ), map_location='''cpu''' ) else: # Sharded UpperCAmelCase_ : List[str] = [ torch.load(os.path.join(SCREAMING_SNAKE_CASE__, F"""consolidated.{i:02d}.pth""" ), map_location='''cpu''' ) for i in range(SCREAMING_SNAKE_CASE__ ) ] UpperCAmelCase_ : Dict = 0 UpperCAmelCase_ : str = {'''weight_map''': {}} for layer_i in range(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Any = F"""pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin""" if model_size == "7B": # Unsharded UpperCAmelCase_ : Optional[int] = { F"""model.layers.{layer_i}.self_attn.q_proj.weight""": permute( loaded[F"""layers.{layer_i}.attention.wq.weight"""] ), F"""model.layers.{layer_i}.self_attn.k_proj.weight""": permute( loaded[F"""layers.{layer_i}.attention.wk.weight"""] ), F"""model.layers.{layer_i}.self_attn.v_proj.weight""": loaded[F"""layers.{layer_i}.attention.wv.weight"""], F"""model.layers.{layer_i}.self_attn.o_proj.weight""": loaded[F"""layers.{layer_i}.attention.wo.weight"""], F"""model.layers.{layer_i}.mlp.gate_proj.weight""": loaded[F"""layers.{layer_i}.feed_forward.w1.weight"""], F"""model.layers.{layer_i}.mlp.down_proj.weight""": loaded[F"""layers.{layer_i}.feed_forward.w2.weight"""], F"""model.layers.{layer_i}.mlp.up_proj.weight""": loaded[F"""layers.{layer_i}.feed_forward.w3.weight"""], F"""model.layers.{layer_i}.input_layernorm.weight""": loaded[F"""layers.{layer_i}.attention_norm.weight"""], F"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[F"""layers.{layer_i}.ffn_norm.weight"""], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. UpperCAmelCase_ : Optional[int] = { F"""model.layers.{layer_i}.input_layernorm.weight""": loaded[0][ F"""layers.{layer_i}.attention_norm.weight""" ].clone(), F"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[0][ F"""layers.{layer_i}.ffn_norm.weight""" ].clone(), } UpperCAmelCase_ : Optional[int] = permute( torch.cat( [ loaded[i][F"""layers.{layer_i}.attention.wq.weight"""].view(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ], dim=0, ).reshape(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) ) UpperCAmelCase_ : Any = permute( torch.cat( [ loaded[i][F"""layers.{layer_i}.attention.wk.weight"""].view( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ], dim=0, ).reshape(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, ) UpperCAmelCase_ : Any = torch.cat( [ loaded[i][F"""layers.{layer_i}.attention.wv.weight"""].view( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ) ], dim=0, ).reshape(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[Any] = torch.cat( [loaded[i][F"""layers.{layer_i}.attention.wo.weight"""] for i in range(SCREAMING_SNAKE_CASE__ )], dim=1 ) UpperCAmelCase_ : str = torch.cat( [loaded[i][F"""layers.{layer_i}.feed_forward.w1.weight"""] for i in range(SCREAMING_SNAKE_CASE__ )], dim=0 ) UpperCAmelCase_ : Tuple = torch.cat( [loaded[i][F"""layers.{layer_i}.feed_forward.w2.weight"""] for i in range(SCREAMING_SNAKE_CASE__ )], dim=1 ) UpperCAmelCase_ : Tuple = torch.cat( [loaded[i][F"""layers.{layer_i}.feed_forward.w3.weight"""] for i in range(SCREAMING_SNAKE_CASE__ )], dim=0 ) UpperCAmelCase_ : Optional[int] = inv_freq for k, v in state_dict.items(): UpperCAmelCase_ : Dict = filename param_count += v.numel() torch.save(SCREAMING_SNAKE_CASE__, os.path.join(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) ) UpperCAmelCase_ : str = F"""pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin""" if model_size == "7B": # Unsharded UpperCAmelCase_ : Optional[Any] = { '''model.embed_tokens.weight''': loaded['''tok_embeddings.weight'''], '''model.norm.weight''': loaded['''norm.weight'''], '''lm_head.weight''': loaded['''output.weight'''], } else: UpperCAmelCase_ : str = { '''model.norm.weight''': loaded[0]['''norm.weight'''], '''model.embed_tokens.weight''': torch.cat( [loaded[i]['''tok_embeddings.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )], dim=1 ), '''lm_head.weight''': torch.cat([loaded[i]['''output.weight'''] for i in range(SCREAMING_SNAKE_CASE__ )], dim=0 ), } for k, v in state_dict.items(): UpperCAmelCase_ : List[str] = filename param_count += v.numel() torch.save(SCREAMING_SNAKE_CASE__, os.path.join(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) ) # Write configs UpperCAmelCase_ : Any = {'''total_size''': param_count * 2} write_json(SCREAMING_SNAKE_CASE__, os.path.join(SCREAMING_SNAKE_CASE__, '''pytorch_model.bin.index.json''' ) ) UpperCAmelCase_ : str = params['''ffn_dim_multiplier'''] if '''ffn_dim_multiplier''' in params else 1 UpperCAmelCase_ : List[Any] = params['''multiple_of'''] if '''multiple_of''' in params else 256 UpperCAmelCase_ : str = LlamaConfig( hidden_size=SCREAMING_SNAKE_CASE__, intermediate_size=compute_intermediate_size(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), num_attention_heads=params['''n_heads'''], num_hidden_layers=params['''n_layers'''], rms_norm_eps=params['''norm_eps'''], num_key_value_heads=SCREAMING_SNAKE_CASE__, ) config.save_pretrained(SCREAMING_SNAKE_CASE__ ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print('''Loading the checkpoint in a Llama model.''' ) UpperCAmelCase_ : int = LlamaForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__, torch_dtype=torch.floataa, low_cpu_mem_usage=SCREAMING_SNAKE_CASE__ ) # Avoid saving this as part of the config. del model.config._name_or_path print('''Saving in the Transformers format.''' ) model.save_pretrained(SCREAMING_SNAKE_CASE__, safe_serialization=SCREAMING_SNAKE_CASE__ ) shutil.rmtree(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: # Initialize the tokenizer based on the `spm` model UpperCAmelCase_ : Optional[int] = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"""Saving a {tokenizer_class.__name__} to {tokenizer_path}.""" ) UpperCAmelCase_ : List[str] = tokenizer_class(SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( ) -> str: UpperCAmelCase_ : Optional[Any] = argparse.ArgumentParser() parser.add_argument( '''--input_dir''', help='''Location of LLaMA weights, which contains tokenizer.model and model folders''', ) parser.add_argument( '''--model_size''', choices=['''7B''', '''7Bf''', '''13B''', '''13Bf''', '''30B''', '''65B''', '''70B''', '''70Bf''', '''tokenizer_only'''], ) parser.add_argument( '''--output_dir''', help='''Location to write HF model and tokenizer''', ) parser.add_argument('''--safe_serialization''', type=SCREAMING_SNAKE_CASE__, help='''Whether or not to save using `safetensors`.''' ) UpperCAmelCase_ : Union[str, Any] = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir, input_base_path=os.path.join(args.input_dir, args.model_size ), model_size=args.model_size, safe_serialization=args.safe_serialization, ) UpperCAmelCase_ : Any = os.path.join(args.input_dir, '''tokenizer.model''' ) write_tokenizer(args.output_dir, SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
716
'''simple docstring''' import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __a (unittest.TestCase ): @property def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def UpperCAmelCase__ ( self : Dict ) -> Tuple: """simple docstring""" UpperCAmelCase_ : List[Any] = self.dummy_uncond_unet UpperCAmelCase_ : Dict = KarrasVeScheduler() UpperCAmelCase_ : Union[str, Any] = KarrasVePipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Dict = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[int] = pipe(num_inference_steps=2 , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Tuple = torch.manual_seed(0 ) UpperCAmelCase_ : str = pipe(num_inference_steps=2 , generator=__magic_name__ , output_type='''numpy''' , return_dict=__magic_name__ )[0] UpperCAmelCase_ : Union[str, Any] = image[0, -3:, -3:, -1] UpperCAmelCase_ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase_ : Dict = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : List[str] = '''google/ncsnpp-celebahq-256''' UpperCAmelCase_ : List[str] = UNetaDModel.from_pretrained(__magic_name__ ) UpperCAmelCase_ : List[Any] = KarrasVeScheduler() UpperCAmelCase_ : Any = KarrasVePipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Dict = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = pipe(num_inference_steps=20 , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) UpperCAmelCase_ : Optional[Any] = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
644
0
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> int: '''simple docstring''' while b: UpperCAmelCase_ : List[str] = b, a % b return a def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> int: '''simple docstring''' return a if b == 0 else euclidean_gcd_recursive(SCREAMING_SNAKE_CASE__, a % b ) def lowerCamelCase_ ( ) -> List[Any]: '''simple docstring''' print(F"""euclidean_gcd(3, 5) = {euclidean_gcd(3, 5 )}""" ) print(F"""euclidean_gcd(5, 3) = {euclidean_gcd(5, 3 )}""" ) print(F"""euclidean_gcd(1, 3) = {euclidean_gcd(1, 3 )}""" ) print(F"""euclidean_gcd(3, 6) = {euclidean_gcd(3, 6 )}""" ) print(F"""euclidean_gcd(6, 3) = {euclidean_gcd(6, 3 )}""" ) print(F"""euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3, 5 )}""" ) print(F"""euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5, 3 )}""" ) print(F"""euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1, 3 )}""" ) print(F"""euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3, 6 )}""" ) print(F"""euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6, 3 )}""" ) if __name__ == "__main__": main()
717
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class __a (lowerCamelCase ): __a : List[Any] = "openai/whisper-base" __a : Optional[Any] = ( "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the " "transcribed text." ) __a : Any = "transcriber" __a : str = WhisperProcessor __a : List[Any] = WhisperForConditionalGeneration __a : int = ["audio"] __a : Optional[Any] = ["text"] def UpperCAmelCase__ ( self : Dict , __magic_name__ : List[str] ) -> Optional[int]: """simple docstring""" return self.pre_processor(__magic_name__ , return_tensors='''pt''' ).input_features def UpperCAmelCase__ ( self : Dict , __magic_name__ : Dict ) -> Tuple: """simple docstring""" return self.model.generate(inputs=__magic_name__ ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Dict ) -> str: """simple docstring""" return self.pre_processor.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ )[0]
644
0
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging snake_case_ : Union[str, Any] = logging.get_logger(__name__) class __a (lowerCamelCase ): __a : Tuple = ["pixel_values"] def __init__( self : List[Any] , __magic_name__ : bool = True , __magic_name__ : int = 32 , __magic_name__ : Union[str, Any]=PILImageResampling.BILINEAR , __magic_name__ : bool = True , **__magic_name__ : List[str] , ) -> None: """simple docstring""" UpperCAmelCase_ : int = do_resize UpperCAmelCase_ : Tuple = do_rescale UpperCAmelCase_ : List[Any] = size_divisor UpperCAmelCase_ : Any = resample super().__init__(**__magic_name__ ) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : np.ndarray , __magic_name__ : int , __magic_name__ : str , __magic_name__ : Optional[ChannelDimension] = None , **__magic_name__ : Tuple ) -> np.ndarray: """simple docstring""" UpperCAmelCase_ : List[str] = get_image_size(__magic_name__ ) # Rounds the height and width down to the closest multiple of size_divisor UpperCAmelCase_ : Dict = height // size_divisor * size_divisor UpperCAmelCase_ : Dict = width // size_divisor * size_divisor UpperCAmelCase_ : Any = resize(__magic_name__ , (new_h, new_w) , resample=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) return image def UpperCAmelCase__ ( self : int , __magic_name__ : np.ndarray , __magic_name__ : float , __magic_name__ : Optional[ChannelDimension] = None , **__magic_name__ : Optional[Any] ) -> np.ndarray: """simple docstring""" return rescale(image=__magic_name__ , scale=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : str , __magic_name__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[int] = None , __magic_name__ : Any=None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[Union[TensorType, str]] = None , __magic_name__ : ChannelDimension = ChannelDimension.FIRST , **__magic_name__ : Tuple , ) -> BatchFeature: """simple docstring""" UpperCAmelCase_ : Dict = do_resize if do_resize is not None else self.do_resize UpperCAmelCase_ : str = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ : Any = size_divisor if size_divisor is not None else self.size_divisor UpperCAmelCase_ : Dict = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('''size_divisor is required for resizing''' ) UpperCAmelCase_ : Optional[int] = make_list_of_images(__magic_name__ ) if not valid_images(__magic_name__ ): raise ValueError('''Invalid image(s)''' ) # All transformations expect numpy arrays. UpperCAmelCase_ : List[str] = [to_numpy_array(__magic_name__ ) for img in images] if do_resize: UpperCAmelCase_ : str = [self.resize(__magic_name__ , size_divisor=__magic_name__ , resample=__magic_name__ ) for image in images] if do_rescale: UpperCAmelCase_ : Tuple = [self.rescale(__magic_name__ , scale=1 / 2_55 ) for image in images] UpperCAmelCase_ : Union[str, Any] = [to_channel_dimension_format(__magic_name__ , __magic_name__ ) for image in images] UpperCAmelCase_ : int = {'''pixel_values''': images} return BatchFeature(data=__magic_name__ , tensor_type=__magic_name__ )
718
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> int: return abs(SCREAMING_SNAKE_CASE__ ) if a == 0 else greatest_common_divisor(b % a, SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = y, x % y return abs(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( ) -> Optional[int]: try: UpperCAmelCase_ : Optional[Any] = input('''Enter two integers separated by comma (,): ''' ).split(''',''' ) UpperCAmelCase_ : Optional[int] = int(nums[0] ) UpperCAmelCase_ : List[Any] = int(nums[1] ) print( F"""greatest_common_divisor({num_a}, {num_a}) = """ F"""{greatest_common_divisor(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )}""" ) print(F"""By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )}""" ) except (IndexError, UnboundLocalError, ValueError): print('''Wrong input''' ) if __name__ == "__main__": main()
644
0
'''simple docstring''' from scipy.stats import pearsonr, spearmanr from sklearn.metrics import fa_score, matthews_corrcoef import datasets snake_case_ : List[str] = "\\n@inproceedings{wang2019glue,\n title={{GLUE}: A Multi-Task Benchmark and Analysis Platform for Natural Language Understanding},\n author={Wang, Alex and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R.},\n note={In the Proceedings of ICLR.},\n year={2019}\n}\n" snake_case_ : Optional[Any] = "\\nGLUE, the General Language Understanding Evaluation benchmark\n(https://gluebenchmark.com/) is a collection of resources for training,\nevaluating, and analyzing natural language understanding systems.\n" snake_case_ : List[str] = "\nCompute GLUE evaluation metric associated to each GLUE dataset.\nArgs:\n predictions: list of predictions to score.\n Each translation should be tokenized into a list of tokens.\n references: list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\nReturns: depending on the GLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"pearson\": Pearson Correlation\n \"spearmanr\": Spearman Correlation\n \"matthews_correlation\": Matthew Correlation\nExamples:\n\n >>> glue_metric = datasets.load_metric('glue', 'sst2') # 'sst2' or any of [\"mnli\", \"mnli_mismatched\", \"mnli_matched\", \"qnli\", \"rte\", \"wnli\", \"hans\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'mrpc') # 'mrpc' or 'qqp'\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'stsb')\n >>> references = [0., 1., 2., 3., 4., 5.]\n >>> predictions = [0., 1., 2., 3., 4., 5.]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print({\"pearson\": round(results[\"pearson\"], 2), \"spearmanr\": round(results[\"spearmanr\"], 2)})\n {'pearson': 1.0, 'spearmanr': 1.0}\n\n >>> glue_metric = datasets.load_metric('glue', 'cola')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[Any]: return float((preds == labels).mean() ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : Dict ) -> Optional[int]: UpperCAmelCase_ : Union[str, Any] = simple_accuracy(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Union[str, Any] = float(fa_score(y_true=SCREAMING_SNAKE_CASE__, y_pred=SCREAMING_SNAKE_CASE__ ) ) return { "accuracy": acc, "f1": fa, } def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str], SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: UpperCAmelCase_ : Optional[Any] = float(pearsonr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )[0] ) UpperCAmelCase_ : Any = float(spearmanr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )[0] ) return { "pearson": pearson_corr, "spearmanr": spearman_corr, } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __a (datasets.Metric ): def UpperCAmelCase__ ( self : Optional[int] ) -> int: """simple docstring""" if self.config_name not in [ "sst2", "mnli", "mnli_mismatched", "mnli_matched", "cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), '''references''': datasets.Value('''int64''' if self.config_name != '''stsb''' else '''float32''' ), } ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' , ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] ) -> Any: """simple docstring""" if self.config_name == "cola": return {"matthews_correlation": matthews_corrcoef(__magic_name__ , __magic_name__ )} elif self.config_name == "stsb": return pearson_and_spearman(__magic_name__ , __magic_name__ ) elif self.config_name in ["mrpc", "qqp"]: return acc_and_fa(__magic_name__ , __magic_name__ ) elif self.config_name in ["sst2", "mnli", "mnli_mismatched", "mnli_matched", "qnli", "rte", "wnli", "hans"]: return {"accuracy": simple_accuracy(__magic_name__ , __magic_name__ )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["sst2", "mnli", "mnli_mismatched", "mnli_matched", ''' '''"cola", "stsb", "mrpc", "qqp", "qnli", "rte", "wnli", "hans"]''' )
719
'''simple docstring''' import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __a : def __init__( self : int , __magic_name__ : Optional[Any] , __magic_name__ : Any=13 , __magic_name__ : Any=7 , __magic_name__ : Union[str, Any]=True , __magic_name__ : Union[str, Any]=True , __magic_name__ : str=True , __magic_name__ : Optional[int]=True , __magic_name__ : List[Any]=99 , __magic_name__ : int=24 , __magic_name__ : Optional[int]=2 , __magic_name__ : Tuple=6 , __magic_name__ : Union[str, Any]=37 , __magic_name__ : Optional[Any]="gelu" , __magic_name__ : Any=0.1 , __magic_name__ : str=0.1 , __magic_name__ : Tuple=5_12 , __magic_name__ : Union[str, Any]=16 , __magic_name__ : Tuple=2 , __magic_name__ : Tuple=0.0_2 , __magic_name__ : Optional[Any]=3 , __magic_name__ : Optional[int]=None , __magic_name__ : Any=10_00 , ) -> str: """simple docstring""" UpperCAmelCase_ : Tuple = parent UpperCAmelCase_ : Optional[int] = batch_size UpperCAmelCase_ : List[str] = seq_length UpperCAmelCase_ : Dict = is_training UpperCAmelCase_ : List[str] = use_input_mask UpperCAmelCase_ : Any = use_token_type_ids UpperCAmelCase_ : Any = use_labels UpperCAmelCase_ : Any = vocab_size UpperCAmelCase_ : Dict = hidden_size UpperCAmelCase_ : Tuple = num_hidden_layers UpperCAmelCase_ : Tuple = num_attention_heads UpperCAmelCase_ : int = intermediate_size UpperCAmelCase_ : Union[str, Any] = hidden_act UpperCAmelCase_ : Optional[int] = hidden_dropout_prob UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase_ : Union[str, Any] = max_position_embeddings UpperCAmelCase_ : int = type_vocab_size UpperCAmelCase_ : List[Any] = type_sequence_label_size UpperCAmelCase_ : int = initializer_range UpperCAmelCase_ : Dict = num_labels UpperCAmelCase_ : List[str] = scope UpperCAmelCase_ : List[str] = range_bbox def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCAmelCase_ : List[str] = bbox[i, j, 3] UpperCAmelCase_ : Dict = bbox[i, j, 1] UpperCAmelCase_ : Optional[Any] = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCAmelCase_ : List[str] = bbox[i, j, 2] UpperCAmelCase_ : Tuple = bbox[i, j, 0] UpperCAmelCase_ : Union[str, Any] = t UpperCAmelCase_ : int = None if self.use_input_mask: UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCAmelCase_ : Optional[int] = None if self.use_token_type_ids: UpperCAmelCase_ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Dict = None UpperCAmelCase_ : Tuple = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : int = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : int , ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = LiltModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Optional[Any] = model(__magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : List[Any] = model(__magic_name__ , bbox=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : Optional[int] = model(__magic_name__ , bbox=__magic_name__ ) 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 : int , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[int] , __magic_name__ : List[Any] , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Any = self.num_labels UpperCAmelCase_ : List[Any] = LiltForTokenClassification(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : List[Any] = model( __magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : int , __magic_name__ : Tuple , __magic_name__ : Any , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : str = LiltForQuestionAnswering(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Optional[Any] = model( __magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , start_positions=__magic_name__ , end_positions=__magic_name__ , ) 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 : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : Optional[int] = config_and_inputs UpperCAmelCase_ : Tuple = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class __a (lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : Tuple = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __a : Any = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __a : Union[str, Any] = False __a : int = False def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : int ) -> str: """simple docstring""" return True def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = LiltModelTester(self ) UpperCAmelCase_ : List[Any] = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ : Tuple = type self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @slow def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Optional[int] = LiltModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) @require_torch @slow class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" UpperCAmelCase_ : str = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''' ).to(__magic_name__ ) UpperCAmelCase_ : Any = torch.tensor([[1, 2]] , device=__magic_name__ ) UpperCAmelCase_ : int = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=__magic_name__ ) # forward pass with torch.no_grad(): UpperCAmelCase_ : Optional[int] = model(input_ids=__magic_name__ , bbox=__magic_name__ ) UpperCAmelCase_ : int = torch.Size([1, 2, 7_68] ) UpperCAmelCase_ : List[str] = torch.tensor( [[-0.0_6_5_3, 0.0_9_5_0, -0.0_0_6_1], [-0.0_5_4_5, 0.0_9_2_6, -0.0_3_2_4]] , device=__magic_name__ , ) self.assertTrue(outputs.last_hidden_state.shape , __magic_name__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , __magic_name__ , atol=1E-3 ) )
644
0
import math class __a : def __init__( self : Any , __magic_name__ : str=0 ) -> Union[str, Any]: # a graph with Node 0,1,...,N-1 """simple docstring""" UpperCAmelCase_ : Optional[Any] = n UpperCAmelCase_ : int = [ [math.inf for j in range(0 , __magic_name__ )] for i in range(0 , __magic_name__ ) ] # adjacency matrix for weight UpperCAmelCase_ : Dict = [ [math.inf for j in range(0 , __magic_name__ )] for i in range(0 , __magic_name__ ) ] # dp[i][j] stores minimum distance from i to j def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Tuple , __magic_name__ : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = w def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): UpperCAmelCase_ : Optional[Any] = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def UpperCAmelCase__ ( self : Any , __magic_name__ : List[str] , __magic_name__ : List[Any] ) -> Union[str, Any]: """simple docstring""" return self.dp[u][v] if __name__ == "__main__": snake_case_ : Any = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 10) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 10) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
720
'''simple docstring''' import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging snake_case_ : str = logging.get_logger(__name__) snake_case_ : int = "▁" snake_case_ : str = {"vocab_file": "vocab.txt", "sentencepiece_model_ckpt": "sentencepiece.bpe.model"} snake_case_ : int = { "sentencepiece_model_file": "sentencepiece.bpe.model", "vocab_file": "vocab.txt", } snake_case_ : Optional[Any] = { "vocab_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", }, "sentencepiece_model_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", }, } snake_case_ : Dict = { "ernie-m-base": 5_14, "ernie-m-large": 5_14, } snake_case_ : Any = { "ernie-m-base": {"do_lower_case": False}, "ernie-m-large": {"do_lower_case": False}, } class __a (lowerCamelCase ): __a : List[str] = ["input_ids"] __a : Union[str, Any] = VOCAB_FILES_NAMES __a : Tuple = PRETRAINED_INIT_CONFIGURATION __a : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a : Optional[int] = PRETRAINED_VOCAB_FILES_MAP __a : Union[str, Any] = RESOURCE_FILES_NAMES def __init__( self : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : int=None , __magic_name__ : str=False , __magic_name__ : int="utf8" , __magic_name__ : Optional[int]="[UNK]" , __magic_name__ : Dict="[SEP]" , __magic_name__ : List[Any]="[PAD]" , __magic_name__ : str="[CLS]" , __magic_name__ : Optional[int]="[MASK]" , __magic_name__ : Optional[Dict[str, Any]] = None , **__magic_name__ : Union[str, Any] , ) -> None: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. UpperCAmelCase_ : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , pad_token=__magic_name__ , cls_token=__magic_name__ , mask_token=__magic_name__ , vocab_file=__magic_name__ , encoding=__magic_name__ , sp_model_kwargs=self.sp_model_kwargs , **__magic_name__ , ) UpperCAmelCase_ : Optional[Any] = do_lower_case UpperCAmelCase_ : List[str] = sentencepiece_model_ckpt UpperCAmelCase_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__magic_name__ ) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: UpperCAmelCase_ : List[Any] = self.load_vocab(filepath=__magic_name__ ) else: UpperCAmelCase_ : str = {self.sp_model.id_to_piece(__magic_name__ ): id for id in range(self.sp_model.get_piece_size() )} UpperCAmelCase_ : int = {v: k for k, v in self.vocab.items()} def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Any ) -> Any: """simple docstring""" if text is None: return None UpperCAmelCase_ : str = self.tokenize(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ : str = '''''', [] for i, ch in enumerate(__magic_name__ ): if ch in self.SP_CHAR_MAPPING: UpperCAmelCase_ : Optional[int] = self.SP_CHAR_MAPPING.get(__magic_name__ ) else: UpperCAmelCase_ : Union[str, Any] = unicodedata.normalize('''NFKC''' , __magic_name__ ) if self.is_whitespace(__magic_name__ ): continue normalized_text += ch char_mapping.extend([i] * len(__magic_name__ ) ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = normalized_text, [], 0 if self.do_lower_case: UpperCAmelCase_ : Optional[int] = text.lower() for token in split_tokens: if token[:1] == "▁": UpperCAmelCase_ : Tuple = token[1:] UpperCAmelCase_ : int = text[offset:].index(__magic_name__ ) + offset UpperCAmelCase_ : Optional[int] = start + len(__magic_name__ ) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) ) UpperCAmelCase_ : int = end return token_mapping @property def UpperCAmelCase__ ( self : Any ) -> Any: """simple docstring""" return len(self.vocab ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def __getstate__( self : str ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.__dict__.copy() UpperCAmelCase_ : Optional[Any] = None return state def __setstate__( self : str , __magic_name__ : Any ) -> Dict: """simple docstring""" UpperCAmelCase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): UpperCAmelCase_ : int = {} UpperCAmelCase_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.sentencepiece_model_ckpt ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Any ) -> List[str]: """simple docstring""" return "".join((self.SP_CHAR_MAPPING.get(__magic_name__ , __magic_name__ ) for c in text) ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Tuple , __magic_name__ : Any=False , __magic_name__ : List[str]=64 , __magic_name__ : List[str]=0.1 ) -> List[str]: """simple docstring""" if self.sp_model_kwargs.get('''enable_sampling''' ) is True: UpperCAmelCase_ : Dict = True if self.sp_model_kwargs.get('''alpha''' ) is not None: UpperCAmelCase_ : Union[str, Any] = self.sp_model_kwargs.get('''alpha''' ) if self.sp_model_kwargs.get('''nbest_size''' ) is not None: UpperCAmelCase_ : Any = self.sp_model_kwargs.get('''nbest_size''' ) if not enable_sampling: UpperCAmelCase_ : Dict = self.sp_model.EncodeAsPieces(__magic_name__ ) else: UpperCAmelCase_ : Dict = self.sp_model.SampleEncodeAsPieces(__magic_name__ , __magic_name__ , __magic_name__ ) UpperCAmelCase_ : List[Any] = [] for pi, piece in enumerate(__magic_name__ ): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(__magic_name__ ) and pi != 0: new_pieces.append(__magic_name__ ) continue else: continue UpperCAmelCase_ : List[str] = 0 for i, chunk in enumerate(__magic_name__ ): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(__magic_name__ ) or self.is_punct(__magic_name__ ): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) new_pieces.append(__magic_name__ ) UpperCAmelCase_ : List[Any] = i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) UpperCAmelCase_ : List[str] = i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) UpperCAmelCase_ : str = i if len(__magic_name__ ) > lst_i: new_pieces.append(piece[lst_i:] ) return new_pieces def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Optional[int] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = ''''''.join(__magic_name__ ).replace(__magic_name__ , ''' ''' ).strip() return out_string def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, Any] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : str = self.convert_ids_to_tokens(__magic_name__ ) UpperCAmelCase_ : Optional[Any] = ''''''.join(__magic_name__ ).replace(__magic_name__ , ''' ''' ).strip() return out_string def UpperCAmelCase__ ( self : str , __magic_name__ : Optional[Any] ) -> List[Any]: """simple docstring""" return self.vocab.get(__magic_name__ , self.vocab.get(self.unk_token ) ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.reverse_vocab.get(__magic_name__ , self.unk_token ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Any , __magic_name__ : Union[str, Any]=None ) -> Any: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase_ : Union[str, Any] = [self.cls_token_id] UpperCAmelCase_ : List[Any] = [self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def UpperCAmelCase__ ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : List[str]=None ) -> int: """simple docstring""" if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def UpperCAmelCase__ ( self : Dict , __magic_name__ : Optional[Any] , __magic_name__ : List[str]=None , __magic_name__ : Optional[Any]=False ) -> Optional[int]: """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__magic_name__ )) + [1, 1] + ([0] * len(__magic_name__ )) + [1] return [1] + ([0] * len(__magic_name__ )) + [1] def UpperCAmelCase__ ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method if token_ids_a is None: # [CLS] X [SEP] return (len(__magic_name__ ) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(__magic_name__ ) + 1) + [1] * (len(__magic_name__ ) + 3) def UpperCAmelCase__ ( self : Dict , __magic_name__ : str ) -> Tuple: """simple docstring""" if "\u4e00" <= char <= "\u9fff": return True return False def UpperCAmelCase__ ( self : int , __magic_name__ : Optional[int] ) -> str: """simple docstring""" if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def UpperCAmelCase__ ( self : int , __magic_name__ : Optional[Any] ) -> Dict: """simple docstring""" if char in ",;:.?!~,;:。?!《》【】": return True return False def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Any ) -> Union[str, Any]: """simple docstring""" if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(__magic_name__ ) == 1: UpperCAmelCase_ : Optional[Any] = unicodedata.category(__magic_name__ ) if cat == "Zs": return True return False def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : Tuple ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[Any] = {} with io.open(__magic_name__ , '''r''' , encoding='''utf-8''' ) as f: for index, line in enumerate(__magic_name__ ): UpperCAmelCase_ : List[Any] = line.rstrip('''\n''' ) UpperCAmelCase_ : Dict = int(__magic_name__ ) return token_to_idx def UpperCAmelCase__ ( self : Dict , __magic_name__ : str , __magic_name__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = 0 if os.path.isdir(__magic_name__ ): UpperCAmelCase_ : Any = os.path.join( __magic_name__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) else: UpperCAmelCase_ : List[str] = (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory with open(__magic_name__ , '''w''' , encoding='''utf-8''' ) as writer: for token, token_index in sorted(self.vocab.items() , key=lambda __magic_name__ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ''' Please check that the vocabulary is not corrupted!''' ) UpperCAmelCase_ : Dict = token_index writer.write(token + '''\n''' ) index += 1 UpperCAmelCase_ : Union[str, Any] = os.path.join(__magic_name__ , '''sentencepiece.bpe.model''' ) with open(__magic_name__ , '''wb''' ) as fi: UpperCAmelCase_ : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (vocab_file,)
644
0
'''simple docstring''' import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging snake_case_ : Dict = logging.get_logger(__name__) snake_case_ : Optional[Any] = {"vocab_file": "spiece.model"} snake_case_ : Union[str, Any] = { "vocab_file": { "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model", "google/bigbird-roberta-large": ( "https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model" ), "google/bigbird-base-trivia-itc": ( "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model" ), } } snake_case_ : Any = { "google/bigbird-roberta-base": 40_96, "google/bigbird-roberta-large": 40_96, "google/bigbird-base-trivia-itc": 40_96, } class __a (lowerCamelCase ): __a : int = VOCAB_FILES_NAMES __a : Any = PRETRAINED_VOCAB_FILES_MAP __a : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a : Any = ["input_ids", "attention_mask"] __a : List[int] = [] def __init__( self : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : List[Any]="<unk>" , __magic_name__ : int="<s>" , __magic_name__ : int="</s>" , __magic_name__ : Dict="<pad>" , __magic_name__ : Dict="[SEP]" , __magic_name__ : Dict="[MASK]" , __magic_name__ : List[str]="[CLS]" , __magic_name__ : Optional[Dict[str, Any]] = None , **__magic_name__ : Optional[int] , ) -> None: """simple docstring""" UpperCAmelCase_ : Dict = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else bos_token UpperCAmelCase_ : Optional[Any] = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else eos_token UpperCAmelCase_ : int = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else unk_token UpperCAmelCase_ : Any = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else pad_token UpperCAmelCase_ : List[Any] = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else cls_token UpperCAmelCase_ : Any = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase_ : List[Any] = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else mask_token UpperCAmelCase_ : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__magic_name__ , eos_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , sep_token=__magic_name__ , mask_token=__magic_name__ , cls_token=__magic_name__ , sp_model_kwargs=self.sp_model_kwargs , **__magic_name__ , ) UpperCAmelCase_ : Optional[Any] = vocab_file UpperCAmelCase_ : str = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__magic_name__ ) @property def UpperCAmelCase__ ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return self.sp_model.get_piece_size() def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = {self.convert_ids_to_tokens(__magic_name__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Any ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : List[str] = self.__dict__.copy() UpperCAmelCase_ : Optional[Any] = None return state def __setstate__( self : int , __magic_name__ : List[str] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : int = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): UpperCAmelCase_ : Any = {} UpperCAmelCase_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCAmelCase__ ( self : Any , __magic_name__ : str ) -> List[str]: """simple docstring""" return self.sp_model.encode(__magic_name__ , out_type=__magic_name__ ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : List[str] ) -> Optional[int]: """simple docstring""" return self.sp_model.piece_to_id(__magic_name__ ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Optional[int] ) -> str: """simple docstring""" UpperCAmelCase_ : str = self.sp_model.IdToPiece(__magic_name__ ) return token def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : str ) -> Any: """simple docstring""" UpperCAmelCase_ : Any = [] UpperCAmelCase_ : List[str] = '''''' UpperCAmelCase_ : Optional[int] = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__magic_name__ ) + token UpperCAmelCase_ : Tuple = True UpperCAmelCase_ : List[str] = [] else: current_sub_tokens.append(__magic_name__ ) UpperCAmelCase_ : Any = False out_string += self.sp_model.decode(__magic_name__ ) return out_string.strip() def UpperCAmelCase__ ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : bool = False , __magic_name__ : bool = None , __magic_name__ : bool = True , **__magic_name__ : List[Any] , ) -> str: """simple docstring""" UpperCAmelCase_ : Tuple = kwargs.pop('''use_source_tokenizer''' , __magic_name__ ) UpperCAmelCase_ : str = self.convert_ids_to_tokens(__magic_name__ , skip_special_tokens=__magic_name__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 UpperCAmelCase_ : int = [] UpperCAmelCase_ : Dict = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(__magic_name__ ) ) UpperCAmelCase_ : List[Any] = [] sub_texts.append(__magic_name__ ) else: current_sub_text.append(__magic_name__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(__magic_name__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: UpperCAmelCase_ : List[str] = re.sub(R''' (\[(MASK|SEP)\])''' , R'''\1''' , ''' '''.join(__magic_name__ ) ) else: UpperCAmelCase_ : Union[str, Any] = ''''''.join(__magic_name__ ) UpperCAmelCase_ : Optional[int] = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: UpperCAmelCase_ : Any = self.clean_up_tokenization(__magic_name__ ) return clean_text else: return text def UpperCAmelCase__ ( self : str , __magic_name__ : str , __magic_name__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase_ : Tuple = os.path.join( __magic_name__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__magic_name__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __magic_name__ ) elif not os.path.isfile(self.vocab_file ): with open(__magic_name__ , '''wb''' ) as fi: UpperCAmelCase_ : int = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (out_vocab_file,) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : List[int] , __magic_name__ : 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] UpperCAmelCase_ : List[Any] = [self.cls_token_id] UpperCAmelCase_ : List[str] = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def UpperCAmelCase__ ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None , __magic_name__ : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) if token_ids_a is None: return [1] + ([0] * len(__magic_name__ )) + [1] return [1] + ([0] * len(__magic_name__ )) + [1] + ([0] * len(__magic_name__ )) + [1] def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCAmelCase_ : Optional[int] = [self.sep_token_id] UpperCAmelCase_ : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
721
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) UpperCAmelCase_ : Union[str, Any] = len(bin(SCREAMING_SNAKE_CASE__ )[3:] ) UpperCAmelCase_ : Union[str, Any] = bin(abs(SCREAMING_SNAKE_CASE__ ) - (1 << binary_number_length) )[3:] UpperCAmelCase_ : Optional[Any] = ( ( '''1''' + '''0''' * (binary_number_length - len(SCREAMING_SNAKE_CASE__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
644
0
import argparse import fairseq import torch from torch import nn from transformers import ( MBartaaTokenizer, MBartConfig, MBartForCausalLM, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() snake_case_ : Optional[int] = logging.get_logger(__name__) snake_case_ : Dict = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "mask_emb": "masked_spec_embed", } snake_case_ : int = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", ] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Optional[int], SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: for attribute in key.split('''.''' ): UpperCAmelCase_ : str = getattr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) if weight_type is not None: UpperCAmelCase_ : List[str] = getattr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ).shape else: UpperCAmelCase_ : str = hf_pointer.shape assert hf_shape == value.shape, ( F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" F""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCAmelCase_ : List[Any] = value elif weight_type == "weight_g": UpperCAmelCase_ : str = value elif weight_type == "weight_v": UpperCAmelCase_ : Tuple = value elif weight_type == "bias": UpperCAmelCase_ : str = value else: UpperCAmelCase_ : Optional[int] = value logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: UpperCAmelCase_ : List[Any] = [] UpperCAmelCase_ : Tuple = fairseq_model.state_dict() UpperCAmelCase_ : Tuple = hf_model.feature_extractor UpperCAmelCase_ : Union[str, Any] = hf_model.adapter for name, value in fairseq_dict.items(): UpperCAmelCase_ : Union[str, Any] = False if "conv_layers" in name: load_conv_layer( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, hf_model.config.feat_extract_norm == '''group''', ) UpperCAmelCase_ : List[str] = True elif any(x in name for x in ['''adaptor''', '''w2v_encoder.proj.''', '''w2v_proj_ln.'''] ): load_adapter(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: UpperCAmelCase_ : Union[str, Any] = True if "*" in mapped_key: UpperCAmelCase_ : List[str] = name.split(SCREAMING_SNAKE_CASE__ )[0].split('''.''' )[-2] UpperCAmelCase_ : Any = mapped_key.replace('''*''', SCREAMING_SNAKE_CASE__ ) if "weight_g" in name: UpperCAmelCase_ : Dict = '''weight_g''' elif "weight_v" in name: UpperCAmelCase_ : List[Any] = '''weight_v''' elif "bias" in name: UpperCAmelCase_ : Dict = '''bias''' elif "weight" in name: UpperCAmelCase_ : Dict = '''weight''' else: UpperCAmelCase_ : Optional[int] = None set_recursively(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) continue if not is_used: unused_weights.append(SCREAMING_SNAKE_CASE__ ) logger.warning(F"""Unused weights: {unused_weights}""" ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : Optional[int], SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Dict: UpperCAmelCase_ : Any = full_name.split('''conv_layers.''' )[-1] UpperCAmelCase_ : Union[str, Any] = name.split('''.''' ) UpperCAmelCase_ : int = int(items[0] ) UpperCAmelCase_ : List[Any] = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCAmelCase_ : Dict = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCAmelCase_ : Dict = value logger.info(F"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCAmelCase_ : List[Any] = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"""{full_name} has size {value.shape}, but""" F""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCAmelCase_ : Dict = value logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Any ) -> Union[str, Any]: UpperCAmelCase_ : Dict = full_name.split('''adaptor.''' )[-1] UpperCAmelCase_ : Union[str, Any] = name.split('''.''' ) if items[1].isdigit(): UpperCAmelCase_ : Union[str, Any] = int(items[1] ) else: UpperCAmelCase_ : Tuple = None if "adaptor" not in full_name: if "proj_ln" in full_name: # has to be layer norm if "bias" in name: assert ( value.shape == adapter.proj_layer_norm.bias.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found.""" UpperCAmelCase_ : int = value logger.info(F"""Adapter proj layer norm bias was initialized from {full_name}.""" ) if "weight" in name: assert ( value.shape == adapter.proj_layer_norm.weight.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found.""" UpperCAmelCase_ : Optional[Any] = value else: # has to be projection layer if "bias" in name: assert ( value.shape == adapter.proj.bias.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found.""" UpperCAmelCase_ : List[str] = value logger.info(F"""Adapter proj layer bias was initialized from {full_name}.""" ) if "weight" in name: assert ( value.shape == adapter.proj.weight.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found.""" UpperCAmelCase_ : int = value logger.info(F"""Adapter proj layer weight was initialized from {full_name}.""" ) elif isinstance(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): if "bias" in name: assert ( value.shape == adapter.layers[layer_id].conv.bias.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found.""" UpperCAmelCase_ : Tuple = value logger.info(F"""Adapter layer {layer_id} bias was initialized from {full_name}.""" ) elif "weight" in name: assert ( value.shape == adapter.layers[layer_id].conv.weight.data.shape ), F"""{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found.""" UpperCAmelCase_ : List[Any] = value logger.info(F"""Adapter layer {layer_id} bias was initialized from {full_name}.""" ) else: unused_weights.append(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str ) -> Dict: UpperCAmelCase_ : Dict = emb.weight.shape UpperCAmelCase_ : Any = nn.Linear(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, bias=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[int] = emb.weight.data return lin_layer @torch.no_grad() def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : List[Any], SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : List[str], SCREAMING_SNAKE_CASE__ : List[Any], SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : int, ) -> Any: UpperCAmelCase_ : Optional[Any] = WavaVecaConfig.from_pretrained( SCREAMING_SNAKE_CASE__, add_adapter=SCREAMING_SNAKE_CASE__, adapter_stride=SCREAMING_SNAKE_CASE__, adapter_kernel_size=SCREAMING_SNAKE_CASE__, use_auth_token=SCREAMING_SNAKE_CASE__, output_hidden_size=SCREAMING_SNAKE_CASE__, ) UpperCAmelCase_ : Optional[Any] = MBartConfig.from_pretrained(SCREAMING_SNAKE_CASE__ ) # load model UpperCAmelCase_ : int = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path], arg_overrides={ '''config_yaml''': config_yaml_path, '''data''': '''/'''.join(dict_path.split('''/''' )[:-1] ), '''w2v_path''': checkpoint_path, '''load_pretrained_decoder_from''': None, }, ) UpperCAmelCase_ : Any = model[0].eval() # load feature extractor UpperCAmelCase_ : List[str] = WavaVecaFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE__, use_auth_token=SCREAMING_SNAKE_CASE__ ) # set weights for wav2vec2 encoder UpperCAmelCase_ : int = WavaVecaModel(SCREAMING_SNAKE_CASE__ ) recursively_load_weights_wavaveca(model.encoder, SCREAMING_SNAKE_CASE__ ) # load decoder weights UpperCAmelCase_ : Union[str, Any] = MBartForCausalLM(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict(), strict=SCREAMING_SNAKE_CASE__ ) logger.warning(F"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(F"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) UpperCAmelCase_ : int = SpeechEncoderDecoderModel(encoder=SCREAMING_SNAKE_CASE__, decoder=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[str] = False UpperCAmelCase_ : int = MBartaaTokenizer(SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[str] = hf_wavavec.config.to_dict() UpperCAmelCase_ : Tuple = tokenizer.pad_token_id UpperCAmelCase_ : Optional[int] = tokenizer.bos_token_id UpperCAmelCase_ : Optional[int] = tokenizer.eos_token_id UpperCAmelCase_ : int = '''mbart50''' UpperCAmelCase_ : List[str] = '''wav2vec2''' UpperCAmelCase_ : Dict = tokenizer.eos_token_id UpperCAmelCase_ : List[str] = 250004 UpperCAmelCase_ : List[str] = tokenizer.eos_token_id UpperCAmelCase_ : Dict = SpeechEncoderDecoderConfig.from_dict(SCREAMING_SNAKE_CASE__ ) hf_wavavec.save_pretrained(SCREAMING_SNAKE_CASE__ ) feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": snake_case_ : int = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_yaml_path", default=None, type=str, help="Path to yaml file of fine-tuned model") parser.add_argument( "--encoder_config_path", default="facebook/wav2vec2-xls-r-1b", type=str, help="Path to hf encoder wav2vec2 checkpoint config", ) parser.add_argument( "--decoder_config_path", default="facebook/mbart-large-50-one-to-many-mmt", type=str, help="Path to hf decoder checkpoint config", ) parser.add_argument("--add_adapter", default=True, type=bool, help="whethere to add model adapter layers") parser.add_argument("--adapter_stride", default=2, type=int, help="stride of adapter layers") parser.add_argument("--adapter_kernel_size", default=3, type=int, help="kernel size of adapter layers") parser.add_argument("--encoder_output_dim", default=10_24, type=int, help="encoder output dim") parser.add_argument("--start_token_id", default=25_00_04, type=int, help="`decoder_start_token_id` of model config") snake_case_ : int = parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, args.config_yaml_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, add_adapter=args.add_adapter, adapter_kernel_size=args.adapter_kernel_size, adapter_stride=args.adapter_stride, decoder_start_token_id=args.start_token_id, encoder_output_dim=args.encoder_output_dim, )
700
'''simple docstring''' import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.generation import DisjunctiveConstraint @require_torch class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Optional[Any] ) -> List[Any]: """simple docstring""" # For consistency across different places the DisjunctiveConstraint is called, # dc.token_ids is a list of integers. It is also initialized only by integers. UpperCAmelCase_ : List[str] = [[1, 2, 4], [1, 2, 3, 4]] UpperCAmelCase_ : List[str] = DisjunctiveConstraint(__magic_name__ ) self.assertTrue(isinstance(dc.token_ids , __magic_name__ ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]] ) ) with self.assertRaises(__magic_name__ ): DisjunctiveConstraint([torch.LongTensor([1, 2, 4] ), torch.LongTensor([1, 2, 3, 4, 5] )] ) def UpperCAmelCase__ ( self : List[str] ) -> Dict: """simple docstring""" # We can't have constraints that are complete subsets of another. This leads to a preverse # interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint? # It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially # fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm # will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it). UpperCAmelCase_ : Tuple = [[1, 2], [1, 2, 3, 4]] with self.assertRaises(__magic_name__ ): DisjunctiveConstraint(__magic_name__ ) # fails here def UpperCAmelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = [[1, 2, 3], [1, 2, 4]] UpperCAmelCase_ : List[str] = DisjunctiveConstraint(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) UpperCAmelCase_ : Dict = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : str = dc.update(2 ) UpperCAmelCase_ : Optional[Any] = stepped is True and completed is False and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(3 ) UpperCAmelCase_ : Dict = stepped is True and completed is True and reset is False self.assertTrue(__magic_name__ ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 3] ) def UpperCAmelCase__ ( self : int ) -> Dict: """simple docstring""" UpperCAmelCase_ : Any = [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]] UpperCAmelCase_ : Tuple = DisjunctiveConstraint(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = dc.update(4 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.current_seq == [1, 2, 4] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : int = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.current_seq == [1, 2, 4, 5] ) dc.reset() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[Any] = dc.update(1 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 3 ) self.assertTrue(dc.current_seq == [1] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = dc.update(2 ) self.assertTrue(not dc.completed ) self.assertTrue(dc.remaining() == 2 ) self.assertTrue(dc.current_seq == [1, 2] ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = dc.update(5 ) self.assertTrue(dc.completed ) # Completed! self.assertTrue(dc.remaining() == 0 ) self.assertTrue(dc.current_seq == [1, 2, 5] )
644
0
'''simple docstring''' import os from collections import deque import torch from torch.utils.data import Dataset class __a (lowerCamelCase ): def __init__( self : List[Any] , __magic_name__ : Any="" , __magic_name__ : Tuple="train" ) -> int: """simple docstring""" assert os.path.isdir(__magic_name__ ) UpperCAmelCase_ : List[Any] = [] UpperCAmelCase_ : Union[str, Any] = os.listdir(__magic_name__ ) for story_filename in story_filenames_list: if "summary" in story_filename: continue UpperCAmelCase_ : Dict = os.path.join(__magic_name__ , __magic_name__ ) if not os.path.isfile(__magic_name__ ): continue self.documents.append(__magic_name__ ) def __len__( self : List[str] ) -> Optional[Any]: """simple docstring""" return len(self.documents ) def __getitem__( self : Union[str, Any] , __magic_name__ : Dict ) -> str: """simple docstring""" UpperCAmelCase_ : Optional[int] = self.documents[idx] UpperCAmelCase_ : str = document_path.split('''/''' )[-1] with open(__magic_name__ , encoding='''utf-8''' ) as source: UpperCAmelCase_ : str = source.read() UpperCAmelCase_ : List[Any] = process_story(__magic_name__ ) return document_name, story_lines, summary_lines def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: UpperCAmelCase_ : Tuple = list(filter(lambda SCREAMING_SNAKE_CASE__ : len(SCREAMING_SNAKE_CASE__ ) != 0, [line.strip() for line in raw_story.split('''\n''' )] ) ) # for some unknown reason some lines miss a period, add it UpperCAmelCase_ : int = [_add_missing_period(SCREAMING_SNAKE_CASE__ ) for line in nonempty_lines] # gather article lines UpperCAmelCase_ : List[Any] = [] UpperCAmelCase_ : Union[str, Any] = deque(SCREAMING_SNAKE_CASE__ ) while True: try: UpperCAmelCase_ : List[Any] = lines.popleft() if element.startswith('''@highlight''' ): break story_lines.append(SCREAMING_SNAKE_CASE__ ) except IndexError: # if "@highlight" is absent from the file we pop # all elements until there is None, raising an exception. return story_lines, [] # gather summary lines UpperCAmelCase_ : Optional[int] = list(filter(lambda SCREAMING_SNAKE_CASE__ : not t.startswith('''@highlight''' ), SCREAMING_SNAKE_CASE__ ) ) return story_lines, summary_lines def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> int: UpperCAmelCase_ : Union[str, Any] = ['''.''', '''!''', '''?''', '''...''', '''\'''', '''`''', '''"''', '''\u2019''', '''\u2019''', ''')'''] if line.startswith('''@highlight''' ): return line if line[-1] in END_TOKENS: return line return line + "." def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[Any]: if len(SCREAMING_SNAKE_CASE__ ) > block_size: return sequence[:block_size] else: sequence.extend([pad_token_id] * (block_size - len(SCREAMING_SNAKE_CASE__ )) ) return sequence def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: UpperCAmelCase_ : Optional[Any] = torch.ones_like(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : str = sequence == pad_token_id UpperCAmelCase_ : Tuple = 0 return mask def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : str ) -> Dict: UpperCAmelCase_ : Tuple = [tokenizer.encode(SCREAMING_SNAKE_CASE__ ) for line in story_lines] UpperCAmelCase_ : Any = [token for sentence in story_lines_token_ids for token in sentence] UpperCAmelCase_ : List[str] = [tokenizer.encode(SCREAMING_SNAKE_CASE__ ) for line in summary_lines] UpperCAmelCase_ : str = [token for sentence in summary_lines_token_ids for token in sentence] return story_token_ids, summary_token_ids def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> List[Any]: UpperCAmelCase_ : Tuple = [] for sequence in batch: UpperCAmelCase_ : Optional[int] = -1 UpperCAmelCase_ : Tuple = [] for s in sequence: if s == separator_token_id: sentence_num += 1 embeddings.append(sentence_num % 2 ) batch_embeddings.append(SCREAMING_SNAKE_CASE__ ) return torch.tensor(SCREAMING_SNAKE_CASE__ )
701
'''simple docstring''' import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.layers import LSTM, Dense from tensorflow.keras.models import Sequential if __name__ == "__main__": snake_case_ : List[Any] = pd.read_csv("sample_data.csv", header=None) snake_case_ : Optional[Any] = df.shape[:1][0] # If you're using some other dataset input the target column snake_case_ : Any = df.iloc[:, 1:2] snake_case_ : str = actual_data.values.reshape(len_data, 1) snake_case_ : Optional[Any] = MinMaxScaler().fit_transform(actual_data) snake_case_ : List[str] = 10 snake_case_ : Any = 5 snake_case_ : Any = 20 snake_case_ : Tuple = len_data - periods * look_back snake_case_ : str = actual_data[:division] snake_case_ : Optional[int] = actual_data[division - look_back :] snake_case_ ,snake_case_ : Any = [], [] snake_case_ ,snake_case_ : Union[str, Any] = [], [] for i in range(0, len(train_data) - forward_days - look_back + 1): train_x.append(train_data[i : i + look_back]) train_y.append(train_data[i + look_back : i + look_back + forward_days]) for i in range(0, len(test_data) - forward_days - look_back + 1): test_x.append(test_data[i : i + look_back]) test_y.append(test_data[i + look_back : i + look_back + forward_days]) snake_case_ : Any = np.array(train_x) snake_case_ : Optional[Any] = np.array(test_x) snake_case_ : Optional[Any] = np.array([list(i.ravel()) for i in train_y]) snake_case_ : List[str] = np.array([list(i.ravel()) for i in test_y]) snake_case_ : List[Any] = Sequential() model.add(LSTM(1_28, input_shape=(look_back, 1), return_sequences=True)) model.add(LSTM(64, input_shape=(1_28, 1))) model.add(Dense(forward_days)) model.compile(loss="mean_squared_error", optimizer="adam") snake_case_ : Dict = model.fit( x_train, y_train, epochs=1_50, verbose=1, shuffle=True, batch_size=4 ) snake_case_ : Optional[Any] = model.predict(x_test)
644
0
'''simple docstring''' import numpy as np def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : List[Any], SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : Any ) -> Optional[Any]: UpperCAmelCase_ : str = int(np.ceil((x_end - xa) / h ) ) UpperCAmelCase_ : str = np.zeros((n + 1,) ) UpperCAmelCase_ : Tuple = ya UpperCAmelCase_ : Optional[int] = xa for k in range(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : int = f(SCREAMING_SNAKE_CASE__, y[k] ) UpperCAmelCase_ : Optional[int] = f(x + 0.5 * h, y[k] + 0.5 * h * ka ) UpperCAmelCase_ : Optional[Any] = f(x + 0.5 * h, y[k] + 0.5 * h * ka ) UpperCAmelCase_ : int = f(x + h, y[k] + h * ka ) UpperCAmelCase_ : str = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
702
'''simple docstring''' from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker snake_case_ : Union[str, Any] = "CompVis/stable-diffusion-v1-1" snake_case_ : Dict = "CompVis/stable-diffusion-v1-2" snake_case_ : Any = "CompVis/stable-diffusion-v1-3" snake_case_ : str = "CompVis/stable-diffusion-v1-4" class __a (lowerCamelCase ): def __init__( self : Any , __magic_name__ : AutoencoderKL , __magic_name__ : CLIPTextModel , __magic_name__ : CLIPTokenizer , __magic_name__ : UNetaDConditionModel , __magic_name__ : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __magic_name__ : StableDiffusionSafetyChecker , __magic_name__ : CLIPImageProcessor , __magic_name__ : bool = True , ) -> str: """simple docstring""" super()._init_() UpperCAmelCase_ : Any = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Dict = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : List[Any] = StableDiffusionPipeline.from_pretrained(__magic_name__ ) UpperCAmelCase_ : Tuple = StableDiffusionPipeline( vae=__magic_name__ , text_encoder=__magic_name__ , tokenizer=__magic_name__ , unet=__magic_name__ , scheduler=__magic_name__ , safety_checker=__magic_name__ , feature_extractor=__magic_name__ , requires_safety_checker=__magic_name__ , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def UpperCAmelCase__ ( self : Tuple ) -> Dict[str, Any]: """simple docstring""" return {k: getattr(self , __magic_name__ ) for k in self.config.keys() if not k.startswith('''_''' )} def UpperCAmelCase__ ( self : Dict , __magic_name__ : Optional[Union[str, int]] = "auto" ) -> int: """simple docstring""" if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ : List[str] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" self.enable_attention_slicing(__magic_name__ ) @torch.no_grad() def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Tuple , ) -> Optional[int]: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Any , ) -> Any: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Dict , ) -> List[str]: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : int , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Optional[int] , ) -> str: """simple docstring""" return self.pipea( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) @torch.no_grad() def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Union[str, List[str]] , __magic_name__ : int = 5_12 , __magic_name__ : int = 5_12 , __magic_name__ : int = 50 , __magic_name__ : float = 7.5 , __magic_name__ : Optional[Union[str, List[str]]] = None , __magic_name__ : Optional[int] = 1 , __magic_name__ : float = 0.0 , __magic_name__ : Optional[torch.Generator] = None , __magic_name__ : Optional[torch.FloatTensor] = None , __magic_name__ : Optional[str] = "pil" , __magic_name__ : bool = True , __magic_name__ : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __magic_name__ : int = 1 , **__magic_name__ : Optional[int] , ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : int = '''cuda''' if torch.cuda.is_available() else '''cpu''' self.to(__magic_name__ ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` must be divisible by 8 but are {height} and {width}.""" ) # Get first result from Stable Diffusion Checkpoint v1.1 UpperCAmelCase_ : Optional[int] = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.2 UpperCAmelCase_ : int = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.3 UpperCAmelCase_ : str = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get first result from Stable Diffusion Checkpoint v1.4 UpperCAmelCase_ : str = self.textaimg_sda_a( prompt=__magic_name__ , height=__magic_name__ , width=__magic_name__ , num_inference_steps=__magic_name__ , guidance_scale=__magic_name__ , negative_prompt=__magic_name__ , num_images_per_prompt=__magic_name__ , eta=__magic_name__ , generator=__magic_name__ , latents=__magic_name__ , output_type=__magic_name__ , return_dict=__magic_name__ , callback=__magic_name__ , callback_steps=__magic_name__ , **__magic_name__ , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
644
0
'''simple docstring''' from __future__ import annotations def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : list[int], SCREAMING_SNAKE_CASE__ : int ) -> list[list[int]]: UpperCAmelCase_ : list[list[int]] = [] UpperCAmelCase_ : list[int] = [] UpperCAmelCase_ : Any = 0 UpperCAmelCase_ : Tuple = sum(SCREAMING_SNAKE_CASE__ ) create_state_space_tree(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) return result def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : list[int], SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : list[int], SCREAMING_SNAKE_CASE__ : list[list[int]], SCREAMING_SNAKE_CASE__ : int, ) -> None: if sum(SCREAMING_SNAKE_CASE__ ) > max_sum or (remaining_nums_sum + sum(SCREAMING_SNAKE_CASE__ )) < max_sum: return if sum(SCREAMING_SNAKE_CASE__ ) == max_sum: result.append(SCREAMING_SNAKE_CASE__ ) return for index in range(SCREAMING_SNAKE_CASE__, len(SCREAMING_SNAKE_CASE__ ) ): create_state_space_tree( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, index + 1, [*path, nums[index]], SCREAMING_SNAKE_CASE__, remaining_nums_sum - nums[index], ) snake_case_ : Optional[int] = [3, 34, 4, 12, 5, 2] snake_case_ : int = 9 snake_case_ : List[Any] = generate_sum_of_subsets_soln(nums, max_sum) print(*result)
703
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler snake_case_ : Optional[int] = 16 snake_case_ : Tuple = 32 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Accelerator, SCREAMING_SNAKE_CASE__ : int = 16, SCREAMING_SNAKE_CASE__ : str = "bert-base-cased" ) -> Dict: UpperCAmelCase_ : Dict = AutoTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = load_dataset('''glue''', '''mrpc''' ) def tokenize_function(SCREAMING_SNAKE_CASE__ : Optional[int] ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase_ : Union[str, Any] = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=SCREAMING_SNAKE_CASE__, max_length=SCREAMING_SNAKE_CASE__ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCAmelCase_ : Tuple = datasets.map( SCREAMING_SNAKE_CASE__, batched=SCREAMING_SNAKE_CASE__, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], load_from_cache_file=SCREAMING_SNAKE_CASE__ ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase_ : Optional[Any] = tokenized_datasets.rename_column('''label''', '''labels''' ) def collate_fn(SCREAMING_SNAKE_CASE__ : str ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(SCREAMING_SNAKE_CASE__, padding='''max_length''', max_length=128, return_tensors='''pt''' ) return tokenizer.pad(SCREAMING_SNAKE_CASE__, padding='''longest''', return_tensors='''pt''' ) # Instantiate dataloaders. UpperCAmelCase_ : str = DataLoader( tokenized_datasets['''train'''], shuffle=SCREAMING_SNAKE_CASE__, collate_fn=SCREAMING_SNAKE_CASE__, batch_size=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = DataLoader( tokenized_datasets['''validation'''], shuffle=SCREAMING_SNAKE_CASE__, collate_fn=SCREAMING_SNAKE_CASE__, batch_size=SCREAMING_SNAKE_CASE__ ) return train_dataloader, eval_dataloader def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Optional[int], SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Any ) -> Any: model.eval() UpperCAmelCase_ : List[str] = 0 for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase_ : Dict = model(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : str = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCAmelCase_ , UpperCAmelCase_ : List[str] = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(SCREAMING_SNAKE_CASE__ ) - 1: UpperCAmelCase_ : Tuple = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCAmelCase_ : int = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=SCREAMING_SNAKE_CASE__, references=SCREAMING_SNAKE_CASE__, ) UpperCAmelCase_ : List[str] = metric.compute() return eval_metric["accuracy"] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : int ) -> Tuple: # Initialize accelerator UpperCAmelCase_ : Union[str, Any] = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase_ : int = config['''lr'''] UpperCAmelCase_ : Optional[int] = int(config['''num_epochs'''] ) UpperCAmelCase_ : Optional[int] = int(config['''seed'''] ) UpperCAmelCase_ : List[str] = int(config['''batch_size'''] ) UpperCAmelCase_ : Optional[int] = args.model_name_or_path set_seed(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = get_dataloaders(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase_ : List[Any] = AutoModelForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__, return_dict=SCREAMING_SNAKE_CASE__ ) # Instantiate optimizer UpperCAmelCase_ : str = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCAmelCase_ : List[str] = optimizer_cls(params=model.parameters(), lr=SCREAMING_SNAKE_CASE__ ) if accelerator.state.deepspeed_plugin is not None: UpperCAmelCase_ : List[Any] = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: UpperCAmelCase_ : Tuple = 1 UpperCAmelCase_ : int = (len(SCREAMING_SNAKE_CASE__ ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCAmelCase_ : Tuple = get_linear_schedule_with_warmup( optimizer=SCREAMING_SNAKE_CASE__, num_warmup_steps=0, num_training_steps=SCREAMING_SNAKE_CASE__, ) else: UpperCAmelCase_ : Any = DummyScheduler(SCREAMING_SNAKE_CASE__, total_num_steps=SCREAMING_SNAKE_CASE__, warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = accelerator.prepare( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # We need to keep track of how many total steps we have iterated over UpperCAmelCase_ : Union[str, Any] = 0 # We also need to keep track of the stating epoch so files are named properly UpperCAmelCase_ : Dict = 0 UpperCAmelCase_ : int = evaluate.load('''glue''', '''mrpc''' ) UpperCAmelCase_ : Optional[Any] = num_epochs if args.partial_train_epoch is not None: UpperCAmelCase_ : List[Any] = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) UpperCAmelCase_ : Tuple = args.resume_from_checkpoint.split('''epoch_''' )[1] UpperCAmelCase_ : int = '''''' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break UpperCAmelCase_ : Union[str, Any] = int(SCREAMING_SNAKE_CASE__ ) + 1 UpperCAmelCase_ : Dict = evaluation_loop(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) accelerator.print('''resumed checkpoint performance:''', SCREAMING_SNAKE_CASE__ ) accelerator.print('''resumed checkpoint\'s scheduler\'s lr:''', lr_scheduler.get_lr()[0] ) accelerator.print('''resumed optimizers\'s lr:''', optimizer.param_groups[0]['''lr'''] ) with open(os.path.join(args.output_dir, F"""state_{starting_epoch-1}.json""" ), '''r''' ) as f: UpperCAmelCase_ : Optional[int] = json.load(SCREAMING_SNAKE_CASE__ ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model UpperCAmelCase_ : int = {} for epoch in range(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): model.train() for step, batch in enumerate(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Optional[int] = model(**SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Any = outputs.loss UpperCAmelCase_ : Tuple = loss / gradient_accumulation_steps accelerator.backward(SCREAMING_SNAKE_CASE__ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 UpperCAmelCase_ : Tuple = F"""epoch_{epoch}""" UpperCAmelCase_ : Optional[int] = os.path.join(args.output_dir, SCREAMING_SNAKE_CASE__ ) accelerator.save_state(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : int = evaluation_loop(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[Any] = accuracy UpperCAmelCase_ : Any = lr_scheduler.get_lr()[0] UpperCAmelCase_ : List[str] = optimizer.param_groups[0]['''lr'''] UpperCAmelCase_ : Tuple = epoch UpperCAmelCase_ : Dict = overall_step accelerator.print(F"""epoch {epoch}:""", SCREAMING_SNAKE_CASE__ ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir, F"""state_{epoch}.json""" ), '''w''' ) as f: json.dump(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( ) -> List[str]: UpperCAmelCase_ : Optional[int] = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''', type=SCREAMING_SNAKE_CASE__, default='''bert-base-cased''', help='''Path to pretrained model or model identifier from huggingface.co/models.''', required=SCREAMING_SNAKE_CASE__, ) parser.add_argument( '''--output_dir''', type=SCREAMING_SNAKE_CASE__, default='''.''', help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''', ) parser.add_argument( '''--resume_from_checkpoint''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''If the training should continue from a checkpoint folder.''', ) parser.add_argument( '''--partial_train_epoch''', type=SCREAMING_SNAKE_CASE__, default=SCREAMING_SNAKE_CASE__, help='''If passed, the training will stop after this number of epochs.''', ) parser.add_argument( '''--num_epochs''', type=SCREAMING_SNAKE_CASE__, default=2, help='''Number of train epochs.''', ) UpperCAmelCase_ : Optional[int] = parser.parse_args() UpperCAmelCase_ : List[Any] = {'''lr''': 2E-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": main()
644
0
snake_case_ : int = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
704
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : list[int] ) -> list[list[int]]: UpperCAmelCase_ : int = [] if len(SCREAMING_SNAKE_CASE__ ) == 1: return [nums.copy()] for _ in range(len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ : List[Any] = nums.pop(0 ) UpperCAmelCase_ : Optional[Any] = permute(SCREAMING_SNAKE_CASE__ ) for perm in permutations: perm.append(SCREAMING_SNAKE_CASE__ ) result.extend(SCREAMING_SNAKE_CASE__ ) nums.append(SCREAMING_SNAKE_CASE__ ) return result def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str] ) -> Any: def backtrack(SCREAMING_SNAKE_CASE__ : Union[str, Any] ): if start == len(SCREAMING_SNAKE_CASE__ ) - 1: output.append(nums[:] ) else: for i in range(SCREAMING_SNAKE_CASE__, len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ , UpperCAmelCase_ : Tuple = nums[i], nums[start] backtrack(start + 1 ) UpperCAmelCase_ , UpperCAmelCase_ : int = nums[i], nums[start] # backtrack UpperCAmelCase_ : Optional[int] = [] backtrack(0 ) return output if __name__ == "__main__": import doctest # use res to print the data in permute2 function snake_case_ : Tuple = permutea([1, 2, 3]) print(res) doctest.testmod()
644
0
'''simple docstring''' from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class __a (nn.Module ): def __init__( self : Any , __magic_name__ : int = 16 , __magic_name__ : int = 88 , __magic_name__ : Optional[int] = None , __magic_name__ : int = 1 , __magic_name__ : float = 0.0 , __magic_name__ : int = 32 , __magic_name__ : Optional[int] = None , __magic_name__ : bool = False , __magic_name__ : Optional[int] = None , __magic_name__ : Optional[int] = None , __magic_name__ : str = "geglu" , __magic_name__ : Optional[int] = None , ) -> List[Any]: """simple docstring""" super().__init__() UpperCAmelCase_ : List[Any] = nn.ModuleList( [ TransformeraDModel( num_attention_heads=__magic_name__ , attention_head_dim=__magic_name__ , in_channels=__magic_name__ , num_layers=__magic_name__ , dropout=__magic_name__ , norm_num_groups=__magic_name__ , cross_attention_dim=__magic_name__ , attention_bias=__magic_name__ , sample_size=__magic_name__ , num_vector_embeds=__magic_name__ , activation_fn=__magic_name__ , num_embeds_ada_norm=__magic_name__ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference UpperCAmelCase_ : List[str] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` UpperCAmelCase_ : Optional[int] = [77, 2_57] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` UpperCAmelCase_ : Tuple = [1, 0] def UpperCAmelCase__ ( self : str , __magic_name__ : Optional[int] , __magic_name__ : Any , __magic_name__ : Optional[int]=None , __magic_name__ : Optional[int]=None , __magic_name__ : List[str]=None , __magic_name__ : bool = True , ) -> Any: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = hidden_states UpperCAmelCase_ : Dict = [] UpperCAmelCase_ : Any = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens UpperCAmelCase_ : Optional[Any] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] UpperCAmelCase_ : Any = self.transformer_index_for_condition[i] UpperCAmelCase_ : str = self.transformers[transformer_index]( __magic_name__ , encoder_hidden_states=__magic_name__ , timestep=__magic_name__ , cross_attention_kwargs=__magic_name__ , return_dict=__magic_name__ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] UpperCAmelCase_ : Any = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) UpperCAmelCase_ : Any = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=__magic_name__ )
705
'''simple docstring''' class __a : def __init__( self : List[Any] , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : Optional[Any] = size UpperCAmelCase_ : Tuple = [0] * size UpperCAmelCase_ : Optional[Any] = [0] * size @staticmethod def UpperCAmelCase__ ( __magic_name__ : int ) -> int: """simple docstring""" return index | (index + 1) @staticmethod def UpperCAmelCase__ ( __magic_name__ : int ) -> int: """simple docstring""" return (index & (index + 1)) - 1 def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : int , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : int = value while index < self.size: UpperCAmelCase_ : str = self.get_prev(__magic_name__ ) + 1 if current_left_border == index: UpperCAmelCase_ : List[str] = value else: UpperCAmelCase_ : Optional[int] = max(__magic_name__ , __magic_name__ , __magic_name__ ) UpperCAmelCase_ : Tuple = self.get_next(__magic_name__ ) def UpperCAmelCase__ ( self : Any , __magic_name__ : int , __magic_name__ : int ) -> int: """simple docstring""" right -= 1 # Because of right is exclusive UpperCAmelCase_ : List[str] = 0 while left <= right: UpperCAmelCase_ : Optional[Any] = self.get_prev(__magic_name__ ) if left <= current_left: UpperCAmelCase_ : Dict = max(__magic_name__ , self.tree[right] ) UpperCAmelCase_ : Optional[Any] = current_left else: UpperCAmelCase_ : str = max(__magic_name__ , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
644
0
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> np.ndarray: # prepare kernel # the kernel size have to be odd if (ksize % 2) == 0: UpperCAmelCase_ : Any = ksize + 1 UpperCAmelCase_ : Tuple = np.zeros((ksize, ksize), dtype=np.floataa ) # each value for y in range(SCREAMING_SNAKE_CASE__ ): for x in range(SCREAMING_SNAKE_CASE__ ): # distance from center UpperCAmelCase_ : Dict = x - ksize // 2 UpperCAmelCase_ : str = y - ksize // 2 # degree to radiant UpperCAmelCase_ : List[Any] = theta / 180 * np.pi UpperCAmelCase_ : Optional[Any] = np.cos(_theta ) UpperCAmelCase_ : int = np.sin(_theta ) # get kernel x UpperCAmelCase_ : int = cos_theta * px + sin_theta * py # get kernel y UpperCAmelCase_ : Any = -sin_theta * px + cos_theta * py # fill kernel UpperCAmelCase_ : str = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image snake_case_ : Tuple = imread("../image_data/lena.jpg") # turn image in gray scale value snake_case_ : Optional[int] = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges snake_case_ : Tuple = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 1_20, 1_50]: snake_case_ : List[str] = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) snake_case_ : Optional[Any] = out / out.max() * 2_55 snake_case_ : int = out.astype(np.uinta) imshow("Original", gray) imshow("Gabor filter with 20x20 mask and 6 directions", out) waitKey(0)
706
'''simple docstring''' import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class __a : def __init__( self : List[str] , __magic_name__ : List[str] , __magic_name__ : str=13 , __magic_name__ : Union[str, Any]=7 , __magic_name__ : Union[str, Any]=True , __magic_name__ : Any=True , __magic_name__ : List[str]=False , __magic_name__ : Optional[int]=True , __magic_name__ : Dict=99 , __magic_name__ : Tuple=32 , __magic_name__ : int=5 , __magic_name__ : Dict=4 , __magic_name__ : Tuple=37 , __magic_name__ : Optional[int]="gelu" , __magic_name__ : List[str]=0.1 , __magic_name__ : Union[str, Any]=0.1 , __magic_name__ : str=5_12 , __magic_name__ : Union[str, Any]=16 , __magic_name__ : int=2 , __magic_name__ : List[Any]=0.0_2 , __magic_name__ : Tuple=3 , __magic_name__ : Union[str, Any]=4 , __magic_name__ : Optional[int]=None , ) -> str: """simple docstring""" UpperCAmelCase_ : Any = parent UpperCAmelCase_ : Union[str, Any] = batch_size UpperCAmelCase_ : List[Any] = seq_length UpperCAmelCase_ : str = is_training UpperCAmelCase_ : Any = use_input_mask UpperCAmelCase_ : List[str] = use_token_type_ids UpperCAmelCase_ : Union[str, Any] = use_labels UpperCAmelCase_ : Dict = vocab_size UpperCAmelCase_ : Optional[Any] = hidden_size UpperCAmelCase_ : Dict = num_hidden_layers UpperCAmelCase_ : List[Any] = num_attention_heads UpperCAmelCase_ : Optional[int] = intermediate_size UpperCAmelCase_ : Union[str, Any] = hidden_act UpperCAmelCase_ : str = hidden_dropout_prob UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase_ : Any = max_position_embeddings UpperCAmelCase_ : str = type_vocab_size UpperCAmelCase_ : Optional[Any] = type_sequence_label_size UpperCAmelCase_ : List[Any] = initializer_range UpperCAmelCase_ : int = num_labels UpperCAmelCase_ : Optional[int] = num_choices UpperCAmelCase_ : Tuple = scope def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : Union[str, Any] = None if self.use_input_mask: UpperCAmelCase_ : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ : str = None if self.use_token_type_ids: UpperCAmelCase_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Tuple = None UpperCAmelCase_ : List[str] = None UpperCAmelCase_ : Union[str, Any] = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase_ : int = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" return BioGptConfig( 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=__magic_name__ , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : List[str] , __magic_name__ : Tuple , __magic_name__ : str , __magic_name__ : Tuple , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = BioGptModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Dict = model(__magic_name__ , attention_mask=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = model(__magic_name__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Optional[int] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[Any] , __magic_name__ : Any , __magic_name__ : Tuple , __magic_name__ : List[str] , __magic_name__ : Optional[int] , ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptForCausalLM(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : List[Any] = model(__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase__ ( self : str , __magic_name__ : Optional[int] , __magic_name__ : Tuple , __magic_name__ : List[str] , __magic_name__ : int , __magic_name__ : str , *__magic_name__ : Any ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() # create attention mask UpperCAmelCase_ : Optional[Any] = torch.ones(input_ids.shape , dtype=torch.long , device=__magic_name__ ) UpperCAmelCase_ : Any = self.seq_length // 2 UpperCAmelCase_ : Tuple = 0 # first forward pass UpperCAmelCase_ , UpperCAmelCase_ : Dict = model(__magic_name__ , attention_mask=__magic_name__ ).to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase_ : Tuple = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids UpperCAmelCase_ : List[str] = ids_tensor((1,) , __magic_name__ ).item() + 1 UpperCAmelCase_ : Tuple = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) UpperCAmelCase_ : str = random_other_next_tokens # append to next input_ids and attn_mask UpperCAmelCase_ : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase_ : int = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=__magic_name__ )] , dim=1 , ) # get two different outputs UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] UpperCAmelCase_ : int = model(__magic_name__ , past_key_values=__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] # select random slice UpperCAmelCase_ : Optional[int] = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase_ : Union[str, Any] = output_from_no_past[:, -1, random_slice_idx].detach() UpperCAmelCase_ : Dict = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-3 ) ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Dict , __magic_name__ : Optional[Any] , __magic_name__ : List[Any] , *__magic_name__ : str ) -> int: """simple docstring""" UpperCAmelCase_ : Dict = BioGptModel(config=__magic_name__ ).to(__magic_name__ ).eval() UpperCAmelCase_ : Optional[int] = torch.ones(input_ids.shape , dtype=torch.long , device=__magic_name__ ) # first forward pass UpperCAmelCase_ : Union[str, Any] = model(__magic_name__ , attention_mask=__magic_name__ , use_cache=__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ : int = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids UpperCAmelCase_ : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase_ : Any = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and UpperCAmelCase_ : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) UpperCAmelCase_ : List[str] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ )['''last_hidden_state'''] UpperCAmelCase_ : Optional[Any] = model(__magic_name__ , attention_mask=__magic_name__ , past_key_values=__magic_name__ )[ '''last_hidden_state''' ] # select random slice UpperCAmelCase_ : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() UpperCAmelCase_ : str = output_from_no_past[:, -3:, random_slice_idx].detach() UpperCAmelCase_ : Optional[int] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__magic_name__ , __magic_name__ , atol=1E-3 ) ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : str , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] , *__magic_name__ : Any , __magic_name__ : List[Any]=False ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = BioGptForCausalLM(__magic_name__ ) model.to(__magic_name__ ) if gradient_checkpointing: model.gradient_checkpointing_enable() UpperCAmelCase_ : List[str] = model(__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Optional[int] , *__magic_name__ : List[str] ) -> str: """simple docstring""" UpperCAmelCase_ : int = BioGptModel(__magic_name__ ) UpperCAmelCase_ : Dict = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.0_0_1 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.0_1 ) def UpperCAmelCase__ ( self : int , __magic_name__ : Tuple , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Optional[Any] , *__magic_name__ : Any ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : str = self.num_labels UpperCAmelCase_ : Any = BioGptForTokenClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Any = model(__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Optional[Any] ) -> str: """simple docstring""" UpperCAmelCase_ : List[Any] = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : int = config_and_inputs UpperCAmelCase_ : Any = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __a (lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : str = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) __a : List[Any] = (BioGptForCausalLM,) if is_torch_available() else () __a : Union[str, Any] = ( { "feature-extraction": BioGptModel, "text-classification": BioGptForSequenceClassification, "text-generation": BioGptForCausalLM, "token-classification": BioGptForTokenClassification, "zero-shot": BioGptForSequenceClassification, } if is_torch_available() else {} ) __a : List[str] = False def UpperCAmelCase__ ( self : Optional[Any] ) -> Dict: """simple docstring""" UpperCAmelCase_ : List[str] = BioGptModelTester(self ) UpperCAmelCase_ : Optional[Any] = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ : str = type self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*__magic_name__ , gradient_checkpointing=__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> List[str]: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*__magic_name__ ) def UpperCAmelCase__ ( self : Dict ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*__magic_name__ ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*__magic_name__ ) @slow def UpperCAmelCase__ ( self : List[Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) model.to(__magic_name__ ) UpperCAmelCase_ : List[str] = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : Tuple = '''left''' # Define PAD Token = EOS Token = 50256 UpperCAmelCase_ : List[Any] = tokenizer.eos_token UpperCAmelCase_ : List[Any] = model.config.eos_token_id # use different length sentences to test batching UpperCAmelCase_ : Tuple = [ '''Hello, my dog is a little''', '''Today, I''', ] UpperCAmelCase_ : Optional[Any] = tokenizer(__magic_name__ , return_tensors='''pt''' , padding=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = inputs['''input_ids'''].to(__magic_name__ ) UpperCAmelCase_ : Any = model.generate( input_ids=__magic_name__ , attention_mask=inputs['''attention_mask'''].to(__magic_name__ ) , ) UpperCAmelCase_ : Union[str, Any] = tokenizer(sentences[0] , return_tensors='''pt''' ).input_ids.to(__magic_name__ ) UpperCAmelCase_ : Tuple = model.generate(input_ids=__magic_name__ ) UpperCAmelCase_ : List[str] = inputs_non_padded.shape[-1] - inputs['''attention_mask'''][-1].long().sum().cpu().item() UpperCAmelCase_ : List[Any] = tokenizer(sentences[1] , return_tensors='''pt''' ).input_ids.to(__magic_name__ ) UpperCAmelCase_ : Tuple = model.generate(input_ids=__magic_name__ , max_length=model.config.max_length - num_paddings ) UpperCAmelCase_ : int = tokenizer.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Dict = tokenizer.decode(output_non_padded[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = [ '''Hello, my dog is a little bit bigger than a little bit.''', '''Today, I have a good idea of how to use the information''', ] self.assertListEqual(__magic_name__ , __magic_name__ ) self.assertListEqual(__magic_name__ , [non_padded_sentence, padded_sentence] ) @slow def UpperCAmelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : List[Any] = BioGptModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) def UpperCAmelCase__ ( self : Tuple ) -> str: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : str = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : List[str] = 3 UpperCAmelCase_ : Tuple = input_dict['''input_ids'''] UpperCAmelCase_ : Dict = input_ids.ne(1 ).to(__magic_name__ ) UpperCAmelCase_ : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) UpperCAmelCase_ : Dict = BioGptForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : int = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() UpperCAmelCase_ : List[Any] = 3 UpperCAmelCase_ : Optional[int] = '''multi_label_classification''' UpperCAmelCase_ : int = input_dict['''input_ids'''] UpperCAmelCase_ : str = input_ids.ne(1 ).to(__magic_name__ ) UpperCAmelCase_ : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) UpperCAmelCase_ : Union[str, Any] = BioGptForSequenceClassification(__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : str = model(__magic_name__ , attention_mask=__magic_name__ , labels=__magic_name__ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class __a (unittest.TestCase ): @slow def UpperCAmelCase__ ( self : List[Any] ) -> str: """simple docstring""" UpperCAmelCase_ : str = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : List[str] = torch.tensor([[2, 48_05, 9, 6_56, 21]] ) UpperCAmelCase_ : str = model(__magic_name__ )[0] UpperCAmelCase_ : Optional[int] = 4_23_84 UpperCAmelCase_ : Tuple = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , __magic_name__ ) UpperCAmelCase_ : List[Any] = torch.tensor( [[[-9.5_2_3_6, -9.8_9_1_8, 1_0.4_5_5_7], [-1_1.0_4_6_9, -9.6_4_2_3, 8.1_0_2_2], [-8.8_6_6_4, -7.8_8_2_6, 5.5_3_2_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __magic_name__ , atol=1E-4 ) ) @slow def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Any = BioGptTokenizer.from_pretrained('''microsoft/biogpt''' ) UpperCAmelCase_ : str = BioGptForCausalLM.from_pretrained('''microsoft/biogpt''' ) model.to(__magic_name__ ) torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = tokenizer('''COVID-19 is''' , return_tensors='''pt''' ).to(__magic_name__ ) UpperCAmelCase_ : Optional[int] = model.generate( **__magic_name__ , min_length=1_00 , max_length=10_24 , num_beams=5 , early_stopping=__magic_name__ , ) UpperCAmelCase_ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=__magic_name__ ) UpperCAmelCase_ : Optional[Any] = ( '''COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the''' ''' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and''' ''' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),''' ''' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and''' ''' more than 800,000 deaths.''' ) self.assertEqual(__magic_name__ , __magic_name__ )
644
0
'''simple docstring''' import sys import turtle def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float] ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : int, ) -> None: my_pen.up() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) if depth == 0: return triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( "Correct format for using this script: " "python fractals.py <int:depth_for_fractal>" ) lowerCamelCase : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor("red") lowerCamelCase : Tuple = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
707
'''simple docstring''' import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class __a (lowerCamelCase , unittest.TestCase ): __a : List[str] = BlenderbotSmallTokenizer __a : List[Any] = False def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" super().setUp() UpperCAmelCase_ : Tuple = ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__'''] UpperCAmelCase_ : Optional[Any] = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) UpperCAmelCase_ : int = ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', ''''''] UpperCAmelCase_ : Optional[Any] = {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''} UpperCAmelCase_ : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase_ : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(__magic_name__ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(__magic_name__ ) ) def UpperCAmelCase__ ( self : List[Any] , **__magic_name__ : Dict ) -> Tuple: """simple docstring""" kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **__magic_name__ ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : List[str] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : str = '''adapt act apte''' UpperCAmelCase_ : Tuple = '''adapt act apte''' return input_text, output_text def UpperCAmelCase__ ( self : str ) -> Any: """simple docstring""" UpperCAmelCase_ : str = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) UpperCAmelCase_ : List[Any] = '''adapt act apte''' UpperCAmelCase_ : Dict = ['''adapt''', '''act''', '''ap@@''', '''te'''] UpperCAmelCase_ : Dict = tokenizer.tokenize(__magic_name__ ) self.assertListEqual(__magic_name__ , __magic_name__ ) UpperCAmelCase_ : Tuple = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] UpperCAmelCase_ : Dict = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(__magic_name__ ) , __magic_name__ ) def UpperCAmelCase__ ( self : int ) -> List[str]: """simple docstring""" UpperCAmelCase_ : List[Any] = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) assert tok('''sam''' ).input_ids == [13_84] UpperCAmelCase_ : Optional[int] = '''I am a small frog.''' UpperCAmelCase_ : List[str] = tok([src_text] , padding=__magic_name__ , truncation=__magic_name__ )['''input_ids'''] UpperCAmelCase_ : Dict = tok.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ , clean_up_tokenization_spaces=__magic_name__ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def UpperCAmelCase__ ( self : Any ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) UpperCAmelCase_ : List[Any] = '''I am a small frog .''' UpperCAmelCase_ : Any = '''.''' UpperCAmelCase_ : List[Any] = tok(__magic_name__ )['''input_ids'''] UpperCAmelCase_ : Optional[int] = tok(__magic_name__ )['''input_ids'''] assert encoded[-1] == encoded_dot[0]
644
0
'''simple docstring''' import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList snake_case_ : Optional[Any] = ["\nclass", "\ndef", "\n#", "\n@", "\nprint", "\nif"] class __a (lowerCamelCase ): def __init__( self : int , __magic_name__ : Any , __magic_name__ : Optional[Any] , __magic_name__ : int=None , __magic_name__ : List[str]=1 ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = tokenizer UpperCAmelCase_ : str = dataset UpperCAmelCase_ : str = len(__magic_name__ ) if n_tasks is None else n_tasks UpperCAmelCase_ : List[Any] = n_copies def __iter__( self : str ) -> Dict: """simple docstring""" UpperCAmelCase_ : Optional[Any] = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['''prompt'''].strip() ) UpperCAmelCase_ : Any = self.tokenizer(__magic_name__ , padding=__magic_name__ , return_tensors='''pt''' ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class __a (lowerCamelCase ): def __init__( self : int , __magic_name__ : int , __magic_name__ : Tuple , __magic_name__ : Tuple ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = start_length UpperCAmelCase_ : Dict = eof_strings UpperCAmelCase_ : List[str] = tokenizer def __call__( self : str , __magic_name__ : Tuple , __magic_name__ : Any , **__magic_name__ : Optional[int] ) -> str: """simple docstring""" UpperCAmelCase_ : Any = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) UpperCAmelCase_ : List[str] = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(__magic_name__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: UpperCAmelCase_ : str = re.split('''(%s)''' % '''|'''.join(SCREAMING_SNAKE_CASE__ ), SCREAMING_SNAKE_CASE__ ) # last string should be "" return "".join(string_list[:-2] ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : List[str], SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : Optional[Any], SCREAMING_SNAKE_CASE__ : Any, SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Tuple=20, **SCREAMING_SNAKE_CASE__ : Any ) -> List[str]: UpperCAmelCase_ : Dict = defaultdict(SCREAMING_SNAKE_CASE__ ) # dict of list of generated tokens for step, batch in tqdm(enumerate(SCREAMING_SNAKE_CASE__ ) ): with torch.no_grad(): UpperCAmelCase_ : Optional[Any] = batch['''ids'''].shape[-1] UpperCAmelCase_ : Optional[int] = accelerator.unwrap_model(SCREAMING_SNAKE_CASE__ ).generate( input_ids=batch['''ids'''][:, : batch['''input_len''']], num_return_sequences=SCREAMING_SNAKE_CASE__, **SCREAMING_SNAKE_CASE__ ) # each task is generated batch_size times UpperCAmelCase_ : Any = batch['''task_id'''].repeat(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[Any] = accelerator.pad_across_processes( SCREAMING_SNAKE_CASE__, dim=1, pad_index=tokenizer.pad_token_id ) UpperCAmelCase_ : str = accelerator.gather((generated_tokens, generated_tasks) ) UpperCAmelCase_ : Any = generated_tokens.cpu().numpy() UpperCAmelCase_ : Union[str, Any] = generated_tasks.cpu().numpy() for task, generated_tokens in zip(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): gen_token_dict[task].append(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = [[] for _ in range(SCREAMING_SNAKE_CASE__ )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: UpperCAmelCase_ : int = tokenizer.decode(SCREAMING_SNAKE_CASE__, skip_special_tokens=SCREAMING_SNAKE_CASE__, clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ ) code_gens[task].append(remove_last_block(SCREAMING_SNAKE_CASE__ ) ) return code_gens def lowerCamelCase_ ( ) -> Tuple: # Setup configuration UpperCAmelCase_ : Optional[Any] = HfArgumentParser(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[str] = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric UpperCAmelCase_ : Union[str, Any] = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing UpperCAmelCase_ : Any = '''false''' if args.num_workers is None: UpperCAmelCase_ : Optional[Any] = multiprocessing.cpu_count() # Use dataset load to feed to accelerate UpperCAmelCase_ : Optional[Any] = Accelerator() set_seed(args.seed, device_specific=SCREAMING_SNAKE_CASE__ ) # Load model and tokenizer UpperCAmelCase_ : List[str] = AutoTokenizer.from_pretrained(args.model_ckpt ) UpperCAmelCase_ : int = tokenizer.eos_token UpperCAmelCase_ : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings UpperCAmelCase_ : Any = { '''do_sample''': args.do_sample, '''temperature''': args.temperature, '''max_new_tokens''': args.max_new_tokens, '''top_p''': args.top_p, '''top_k''': args.top_k, '''stopping_criteria''': StoppingCriteriaList([EndOfFunctionCriteria(0, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )] ), } # Load evaluation dataset and metric UpperCAmelCase_ : Optional[Any] = load_dataset('''openai_humaneval''' ) UpperCAmelCase_ : List[Any] = load_metric('''code_eval''' ) UpperCAmelCase_ : Tuple = args.num_tasks if args.num_tasks is not None else len(human_eval['''test'''] ) UpperCAmelCase_ : Union[str, Any] = args.n_samples // args.batch_size UpperCAmelCase_ : Any = TokenizedDataset(SCREAMING_SNAKE_CASE__, human_eval['''test'''], n_copies=SCREAMING_SNAKE_CASE__, n_tasks=SCREAMING_SNAKE_CASE__ ) # do not confuse args.batch_size, which is actually the num_return_sequences UpperCAmelCase_ : List[str] = DataLoader(SCREAMING_SNAKE_CASE__, batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: UpperCAmelCase_ : Tuple = code_eval_metric.compute(references=[''''''], predictions=[['''''']] ) except ValueError as exception: print( '''Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`''' ''' flag to enable code evaluation.''' ) raise exception UpperCAmelCase_ : List[str] = accelerator.prepare(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[int] = complete_code( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, n_tasks=SCREAMING_SNAKE_CASE__, batch_size=args.batch_size, **SCREAMING_SNAKE_CASE__, ) if accelerator.is_main_process: UpperCAmelCase_ : Optional[Any] = [] for task in tqdm(range(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ : Any = human_eval['''test'''][task]['''test'''] UpperCAmelCase_ : List[Any] = F"""check({human_eval["test"][task]["entry_point"]})""" references.append('''\n''' + test_func + '''\n''' + entry_point ) # Evaluate completions with "code_eval" metric UpperCAmelCase_ : Union[str, Any] = code_eval_metric.compute( references=SCREAMING_SNAKE_CASE__, predictions=SCREAMING_SNAKE_CASE__, num_workers=args.num_workers ) print(F"""Results: {pass_at_k}""" ) # Save results to json file with open(args.output_file, '''w''' ) as fp: json.dump(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
708
'''simple docstring''' import unittest import torch from torch import nn from diffusers.models.activations import get_activation class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Dict ) -> Dict: """simple docstring""" UpperCAmelCase_ : Dict = get_activation('''swish''' ) self.assertIsInstance(__magic_name__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , 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 : Tuple ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = get_activation('''silu''' ) self.assertIsInstance(__magic_name__ , nn.SiLU ) self.assertEqual(act(torch.tensor(-1_00 , 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 : Tuple ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Optional[int] = get_activation('''mish''' ) self.assertIsInstance(__magic_name__ , nn.Mish ) self.assertEqual(act(torch.tensor(-2_00 , 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 : str ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = get_activation('''gelu''' ) self.assertIsInstance(__magic_name__ , nn.GELU ) self.assertEqual(act(torch.tensor(-1_00 , 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 )
644
0
'''simple docstring''' import sys snake_case_ : Optional[int] = ( "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450" ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str = N ) -> int: UpperCAmelCase_ : str = -sys.maxsize - 1 for i in range(len(SCREAMING_SNAKE_CASE__ ) - 12 ): UpperCAmelCase_ : Union[str, Any] = 1 for j in range(13 ): product *= int(n[i + j] ) if product > largest_product: UpperCAmelCase_ : List[Any] = product return largest_product if __name__ == "__main__": print(f'''{solution() = }''')
709
'''simple docstring''' from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging snake_case_ : Union[str, Any] = logging.get_logger(__name__) class __a (lowerCamelCase ): __a : Tuple = ["pixel_values"] def __init__( self : List[Any] , __magic_name__ : bool = True , __magic_name__ : int = 32 , __magic_name__ : Union[str, Any]=PILImageResampling.BILINEAR , __magic_name__ : bool = True , **__magic_name__ : List[str] , ) -> None: """simple docstring""" UpperCAmelCase_ : int = do_resize UpperCAmelCase_ : Tuple = do_rescale UpperCAmelCase_ : List[Any] = size_divisor UpperCAmelCase_ : Any = resample super().__init__(**__magic_name__ ) def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : np.ndarray , __magic_name__ : int , __magic_name__ : str , __magic_name__ : Optional[ChannelDimension] = None , **__magic_name__ : Tuple ) -> np.ndarray: """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ : List[str] = get_image_size(__magic_name__ ) # Rounds the height and width down to the closest multiple of size_divisor UpperCAmelCase_ : Dict = height // size_divisor * size_divisor UpperCAmelCase_ : Dict = width // size_divisor * size_divisor UpperCAmelCase_ : Any = resize(__magic_name__ , (new_h, new_w) , resample=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) return image def UpperCAmelCase__ ( self : int , __magic_name__ : np.ndarray , __magic_name__ : float , __magic_name__ : Optional[ChannelDimension] = None , **__magic_name__ : Optional[Any] ) -> np.ndarray: """simple docstring""" return rescale(image=__magic_name__ , scale=__magic_name__ , data_format=__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : str , __magic_name__ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[int] = None , __magic_name__ : Any=None , __magic_name__ : Optional[bool] = None , __magic_name__ : Optional[Union[TensorType, str]] = None , __magic_name__ : ChannelDimension = ChannelDimension.FIRST , **__magic_name__ : Tuple , ) -> BatchFeature: """simple docstring""" UpperCAmelCase_ : Dict = do_resize if do_resize is not None else self.do_resize UpperCAmelCase_ : str = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ : Any = size_divisor if size_divisor is not None else self.size_divisor UpperCAmelCase_ : Dict = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('''size_divisor is required for resizing''' ) UpperCAmelCase_ : Optional[int] = make_list_of_images(__magic_name__ ) if not valid_images(__magic_name__ ): raise ValueError('''Invalid image(s)''' ) # All transformations expect numpy arrays. UpperCAmelCase_ : List[str] = [to_numpy_array(__magic_name__ ) for img in images] if do_resize: UpperCAmelCase_ : str = [self.resize(__magic_name__ , size_divisor=__magic_name__ , resample=__magic_name__ ) for image in images] if do_rescale: UpperCAmelCase_ : Tuple = [self.rescale(__magic_name__ , scale=1 / 2_55 ) for image in images] UpperCAmelCase_ : Union[str, Any] = [to_channel_dimension_format(__magic_name__ , __magic_name__ ) for image in images] UpperCAmelCase_ : int = {'''pixel_values''': images} return BatchFeature(data=__magic_name__ , tensor_type=__magic_name__ )
644
0
'''simple docstring''' from ..utils import DummyObject, requires_backends class __a (metaclass=lowerCamelCase ): __a : List[str] = ["flax", "transformers"] def __init__( self : List[str] , *__magic_name__ : int , **__magic_name__ : str ) -> str: """simple docstring""" requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def UpperCAmelCase__ ( cls : Optional[int] , *__magic_name__ : Optional[int] , **__magic_name__ : Optional[int] ) -> List[str]: """simple docstring""" requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def UpperCAmelCase__ ( cls : List[str] , *__magic_name__ : List[Any] , **__magic_name__ : Union[str, Any] ) -> Optional[Any]: """simple docstring""" requires_backends(cls , ['''flax''', '''transformers'''] ) class __a (metaclass=lowerCamelCase ): __a : List[str] = ["flax", "transformers"] def __init__( self : List[Any] , *__magic_name__ : Optional[Any] , **__magic_name__ : str ) -> int: """simple docstring""" requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def UpperCAmelCase__ ( cls : Any , *__magic_name__ : str , **__magic_name__ : List[str] ) -> List[Any]: """simple docstring""" requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def UpperCAmelCase__ ( cls : Tuple , *__magic_name__ : Dict , **__magic_name__ : Optional[int] ) -> Optional[Any]: """simple docstring""" requires_backends(cls , ['''flax''', '''transformers'''] ) class __a (metaclass=lowerCamelCase ): __a : Any = ["flax", "transformers"] def __init__( self : List[str] , *__magic_name__ : List[str] , **__magic_name__ : Optional[int] ) -> Tuple: """simple docstring""" requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def UpperCAmelCase__ ( cls : Tuple , *__magic_name__ : Any , **__magic_name__ : List[str] ) -> List[str]: """simple docstring""" requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def UpperCAmelCase__ ( cls : Optional[Any] , *__magic_name__ : Optional[int] , **__magic_name__ : Any ) -> Optional[int]: """simple docstring""" requires_backends(cls , ['''flax''', '''transformers'''] ) class __a (metaclass=lowerCamelCase ): __a : Dict = ["flax", "transformers"] def __init__( self : List[str] , *__magic_name__ : List[str] , **__magic_name__ : Tuple ) -> Optional[Any]: """simple docstring""" requires_backends(self , ['''flax''', '''transformers'''] ) @classmethod def UpperCAmelCase__ ( cls : Union[str, Any] , *__magic_name__ : List[Any] , **__magic_name__ : Any ) -> str: """simple docstring""" requires_backends(cls , ['''flax''', '''transformers'''] ) @classmethod def UpperCAmelCase__ ( cls : int , *__magic_name__ : Optional[Any] , **__magic_name__ : Union[str, Any] ) -> Any: """simple docstring""" requires_backends(cls , ['''flax''', '''transformers'''] )
710
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int = 10, SCREAMING_SNAKE_CASE__ : int = 22 ) -> int: UpperCAmelCase_ : Optional[int] = range(1, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = range(1, SCREAMING_SNAKE_CASE__ ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(f'''{solution(10, 22) = }''')
644
0
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str = "The quick brown fox jumps over the lazy dog", ) -> bool: UpperCAmelCase_ : List[str] = set() # Replace all the whitespace in our sentence UpperCAmelCase_ : Union[str, Any] = input_str.replace(''' ''', '''''' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(SCREAMING_SNAKE_CASE__ ) == 26 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str = "The quick brown fox jumps over the lazy dog", ) -> bool: UpperCAmelCase_ : int = [False] * 26 for char in input_str: if char.islower(): UpperCAmelCase_ : Dict = True elif char.isupper(): UpperCAmelCase_ : List[Any] = True return all(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str = "The quick brown fox jumps over the lazy dog", ) -> bool: return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def lowerCamelCase_ ( ) -> None: from timeit import timeit UpperCAmelCase_ : Any = '''from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest''' print(timeit('''is_pangram()''', setup=SCREAMING_SNAKE_CASE__ ) ) print(timeit('''is_pangram_faster()''', setup=SCREAMING_SNAKE_CASE__ ) ) print(timeit('''is_pangram_fastest()''', setup=SCREAMING_SNAKE_CASE__ ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
711
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING import torch from ..models.auto import AutoModelForVisualQuestionAnswering, AutoProcessor from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __a (lowerCamelCase ): __a : int = "dandelin/vilt-b32-finetuned-vqa" __a : Any = ( "This is a tool that answers a question about an image. It takes an input named `image` which should be the " "image containing the information, as well as a `question` which should be the question in English. It " "returns a text that is the answer to the question." ) __a : Any = "image_qa" __a : str = AutoProcessor __a : Any = AutoModelForVisualQuestionAnswering __a : List[Any] = ["image", "text"] __a : int = ["text"] def __init__( self : Tuple , *__magic_name__ : Any , **__magic_name__ : Any ) -> Tuple: """simple docstring""" requires_backends(self , ['''vision'''] ) super().__init__(*__magic_name__ , **__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : "Image" , __magic_name__ : str ) -> Tuple: """simple docstring""" return self.pre_processor(__magic_name__ , __magic_name__ , return_tensors='''pt''' ) def UpperCAmelCase__ ( self : Any , __magic_name__ : List[str] ) -> Optional[Any]: """simple docstring""" with torch.no_grad(): return self.model(**__magic_name__ ).logits def UpperCAmelCase__ ( self : int , __magic_name__ : int ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Dict = outputs.argmax(-1 ).item() return self.model.config.idalabel[idx]
644
0
'''simple docstring''' import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging snake_case_ : Optional[Any] = logging.get_logger(__name__) snake_case_ : List[Any] = {"vocab_file": "vocab.json", "merges_file": "merges.txt"} # See all LED models at https://huggingface.co/models?filter=LED snake_case_ : Optional[Any] = { "vocab_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json", }, "merges_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt", }, "tokenizer_file": { "allenai/led-base-16384": "https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json", }, } snake_case_ : Union[str, Any] = { "allenai/led-base-16384": 1_63_84, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def lowerCamelCase_ ( ) -> List[Any]: UpperCAmelCase_ : List[str] = ( list(range(ord('''!''' ), ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ), ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ), ord('''ÿ''' ) + 1 ) ) ) UpperCAmelCase_ : List[Any] = bs[:] UpperCAmelCase_ : List[Any] = 0 for b in range(2**8 ): if b not in bs: bs.append(SCREAMING_SNAKE_CASE__ ) cs.append(2**8 + n ) n += 1 UpperCAmelCase_ : Dict = [chr(SCREAMING_SNAKE_CASE__ ) for n in cs] return dict(zip(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[int]: UpperCAmelCase_ : Optional[int] = set() UpperCAmelCase_ : Any = word[0] for char in word[1:]: pairs.add((prev_char, char) ) UpperCAmelCase_ : List[str] = char return pairs class __a (lowerCamelCase ): __a : Tuple = VOCAB_FILES_NAMES __a : int = PRETRAINED_VOCAB_FILES_MAP __a : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a : str = ["input_ids", "attention_mask"] def __init__( self : Dict , __magic_name__ : Any , __magic_name__ : int , __magic_name__ : str="replace" , __magic_name__ : Any="<s>" , __magic_name__ : int="</s>" , __magic_name__ : Tuple="</s>" , __magic_name__ : List[str]="<s>" , __magic_name__ : List[Any]="<unk>" , __magic_name__ : Tuple="<pad>" , __magic_name__ : str="<mask>" , __magic_name__ : Optional[Any]=False , **__magic_name__ : int , ) -> int: """simple docstring""" UpperCAmelCase_ : int = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else bos_token UpperCAmelCase_ : int = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else eos_token UpperCAmelCase_ : List[Any] = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else sep_token UpperCAmelCase_ : Dict = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else cls_token UpperCAmelCase_ : Optional[int] = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else unk_token UpperCAmelCase_ : Dict = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase_ : List[str] = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else mask_token super().__init__( errors=__magic_name__ , bos_token=__magic_name__ , eos_token=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , cls_token=__magic_name__ , pad_token=__magic_name__ , mask_token=__magic_name__ , add_prefix_space=__magic_name__ , **__magic_name__ , ) with open(__magic_name__ , encoding='''utf-8''' ) as vocab_handle: UpperCAmelCase_ : Optional[Any] = json.load(__magic_name__ ) UpperCAmelCase_ : int = {v: k for k, v in self.encoder.items()} UpperCAmelCase_ : int = errors # how to handle errors in decoding UpperCAmelCase_ : Tuple = bytes_to_unicode() UpperCAmelCase_ : Optional[Any] = {v: k for k, v in self.byte_encoder.items()} with open(__magic_name__ , encoding='''utf-8''' ) as merges_handle: UpperCAmelCase_ : Any = merges_handle.read().split('''\n''' )[1:-1] UpperCAmelCase_ : str = [tuple(merge.split() ) for merge in bpe_merges] UpperCAmelCase_ : int = dict(zip(__magic_name__ , range(len(__magic_name__ ) ) ) ) UpperCAmelCase_ : List[Any] = {} UpperCAmelCase_ : Tuple = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions UpperCAmelCase_ : Dict = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def UpperCAmelCase__ ( self : List[Any] ) -> Tuple: """simple docstring""" return len(self.encoder ) def UpperCAmelCase__ ( self : List[Any] ) -> Dict: """simple docstring""" return dict(self.encoder , **self.added_tokens_encoder ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : List[str] ) -> Tuple: """simple docstring""" if token in self.cache: return self.cache[token] UpperCAmelCase_ : List[str] = tuple(__magic_name__ ) UpperCAmelCase_ : Optional[Any] = get_pairs(__magic_name__ ) if not pairs: return token while True: UpperCAmelCase_ : str = min(__magic_name__ , key=lambda __magic_name__ : self.bpe_ranks.get(__magic_name__ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break UpperCAmelCase_ : Union[str, Any] = bigram UpperCAmelCase_ : List[str] = [] UpperCAmelCase_ : List[str] = 0 while i < len(__magic_name__ ): try: UpperCAmelCase_ : Tuple = word.index(__magic_name__ , __magic_name__ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) UpperCAmelCase_ : List[str] = j if word[i] == first and i < len(__magic_name__ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 UpperCAmelCase_ : Tuple = tuple(__magic_name__ ) UpperCAmelCase_ : Any = new_word if len(__magic_name__ ) == 1: break else: UpperCAmelCase_ : Union[str, Any] = get_pairs(__magic_name__ ) UpperCAmelCase_ : List[Any] = ''' '''.join(__magic_name__ ) UpperCAmelCase_ : Tuple = word return word def UpperCAmelCase__ ( self : int , __magic_name__ : List[str] ) -> Any: """simple docstring""" UpperCAmelCase_ : List[Any] = [] for token in re.findall(self.pat , __magic_name__ ): UpperCAmelCase_ : Union[str, Any] = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(__magic_name__ ).split(''' ''' ) ) return bpe_tokens def UpperCAmelCase__ ( self : Any , __magic_name__ : Optional[int] ) -> List[str]: """simple docstring""" return self.encoder.get(__magic_name__ , self.encoder.get(self.unk_token ) ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : int ) -> Any: """simple docstring""" return self.decoder.get(__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : Union[str, Any] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Any = ''''''.join(__magic_name__ ) UpperCAmelCase_ : str = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : str , __magic_name__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(__magic_name__ ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return UpperCAmelCase_ : Union[str, Any] = os.path.join( __magic_name__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) UpperCAmelCase_ : Optional[int] = os.path.join( __magic_name__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(__magic_name__ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=__magic_name__ , ensure_ascii=__magic_name__ ) + '''\n''' ) UpperCAmelCase_ : Tuple = 0 with open(__magic_name__ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda __magic_name__ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.""" ''' Please check that the tokenizer is not corrupted!''' ) UpperCAmelCase_ : int = token_index writer.write(''' '''.join(__magic_name__ ) + '''\n''' ) index += 1 return vocab_file, merge_file def UpperCAmelCase__ ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : 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] UpperCAmelCase_ : Any = [self.cls_token_id] UpperCAmelCase_ : int = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCAmelCase__ ( self : Any , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None , __magic_name__ : bool = False ) -> List[int]: """simple docstring""" if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) if token_ids_a is None: return [1] + ([0] * len(__magic_name__ )) + [1] return [1] + ([0] * len(__magic_name__ )) + [1, 1] + ([0] * len(__magic_name__ )) + [1] def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" UpperCAmelCase_ : List[Any] = [self.sep_token_id] UpperCAmelCase_ : 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] def UpperCAmelCase__ ( self : str , __magic_name__ : Union[str, Any] , __magic_name__ : str=False , **__magic_name__ : Any ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(__magic_name__ ) > 0 and not text[0].isspace()): UpperCAmelCase_ : Tuple = ''' ''' + text return (text, kwargs) def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : Union[Dict[str, EncodedInput], BatchEncoding] , __magic_name__ : Optional[int] = None , __magic_name__ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , __magic_name__ : Optional[int] = None , __magic_name__ : Optional[bool] = None , ) -> dict: """simple docstring""" UpperCAmelCase_ : Any = super()._pad( encoded_inputs=__magic_name__ , max_length=__magic_name__ , padding_strategy=__magic_name__ , pad_to_multiple_of=__magic_name__ , return_attention_mask=__magic_name__ , ) # Load from model defaults if return_attention_mask is None: UpperCAmelCase_ : int = '''attention_mask''' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: UpperCAmelCase_ : int = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. UpperCAmelCase_ : List[str] = len(encoded_inputs['''global_attention_mask'''] ) != len(__magic_name__ ) if needs_to_be_padded: UpperCAmelCase_ : Union[str, Any] = len(__magic_name__ ) - len(encoded_inputs['''global_attention_mask'''] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` UpperCAmelCase_ : Union[str, Any] = ( encoded_inputs['''global_attention_mask'''] + [-1] * difference ) elif self.padding_side == "left": UpperCAmelCase_ : Any = [-1] * difference + encoded_inputs[ '''global_attention_mask''' ] else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return encoded_inputs
712
'''simple docstring''' from collections.abc import Iterable from typing import Any class __a : def __init__( self : Optional[Any] , __magic_name__ : int | None = None ) -> Tuple: """simple docstring""" UpperCAmelCase_ : List[str] = value UpperCAmelCase_ : Node | None = None # Added in order to delete a node easier UpperCAmelCase_ : Node | None = None UpperCAmelCase_ : Node | None = None def __repr__( self : List[str] ) -> str: """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({F"""{self.value}""": (self.left, self.right)} , indent=1 ) class __a : def __init__( self : int , __magic_name__ : Node | None = None ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : str = root def __str__( self : Any ) -> str: """simple docstring""" return str(self.root ) def UpperCAmelCase__ ( self : Any , __magic_name__ : Node , __magic_name__ : Node | None ) -> None: """simple docstring""" if new_children is not None: # reset its kids UpperCAmelCase_ : Dict = node.parent if node.parent is not None: # reset its parent if self.is_right(__magic_name__ ): # If it is the right children UpperCAmelCase_ : Optional[Any] = new_children else: UpperCAmelCase_ : Optional[int] = new_children else: UpperCAmelCase_ : List[str] = new_children def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Node ) -> bool: """simple docstring""" if node.parent and node.parent.right: return node == node.parent.right return False def UpperCAmelCase__ ( self : Union[str, Any] ) -> bool: """simple docstring""" return self.root is None def UpperCAmelCase__ ( self : Any , __magic_name__ : str ) -> None: """simple docstring""" UpperCAmelCase_ : Tuple = Node(__magic_name__ ) # create a new Node if self.empty(): # if Tree is empty UpperCAmelCase_ : List[Any] = new_node # set its root else: # Tree is not empty UpperCAmelCase_ : str = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: UpperCAmelCase_ : Union[str, Any] = new_node # We insert the new node in a leaf break else: UpperCAmelCase_ : List[Any] = parent_node.left else: if parent_node.right is None: UpperCAmelCase_ : List[Any] = new_node break else: UpperCAmelCase_ : Union[str, Any] = parent_node.right UpperCAmelCase_ : Union[str, Any] = parent_node def UpperCAmelCase__ ( self : Optional[Any] , *__magic_name__ : List[str] ) -> None: """simple docstring""" for value in values: self.__insert(__magic_name__ ) def UpperCAmelCase__ ( self : Dict , __magic_name__ : int ) -> Node | None: """simple docstring""" if self.empty(): raise IndexError('''Warning: Tree is empty! please use another.''' ) else: UpperCAmelCase_ : str = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: UpperCAmelCase_ : List[str] = node.left if value < node.value else node.right return node def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Node | None = None ) -> Node | None: """simple docstring""" if node is None: if self.root is None: return None UpperCAmelCase_ : Dict = self.root if not self.empty(): while node.right is not None: UpperCAmelCase_ : Any = node.right return node def UpperCAmelCase__ ( self : Dict , __magic_name__ : Node | None = None ) -> Node | None: """simple docstring""" if node is None: UpperCAmelCase_ : Optional[int] = self.root if self.root is None: return None if not self.empty(): UpperCAmelCase_ : Union[str, Any] = self.root while node.left is not None: UpperCAmelCase_ : Dict = node.left return node def UpperCAmelCase__ ( self : Tuple , __magic_name__ : int ) -> None: """simple docstring""" UpperCAmelCase_ : List[str] = self.search(__magic_name__ ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(__magic_name__ , __magic_name__ ) elif node.left is None: # Has only right children self.__reassign_nodes(__magic_name__ , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(__magic_name__ , node.left ) else: UpperCAmelCase_ : List[str] = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore UpperCAmelCase_ : Optional[int] = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Node | None ) -> Iterable: """simple docstring""" if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : List[Any]=None ) -> Any: """simple docstring""" if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : list , __magic_name__ : Node | None ) -> None: """simple docstring""" if node: self.inorder(__magic_name__ , node.left ) arr.append(node.value ) self.inorder(__magic_name__ , node.right ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : int , __magic_name__ : Node ) -> int: """simple docstring""" UpperCAmelCase_ : list[int] = [] self.inorder(__magic_name__ , __magic_name__ ) # append all values to list using inorder traversal return arr[k - 1] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Node | None ) -> list[Node]: UpperCAmelCase_ : Any = [] if curr_node is not None: UpperCAmelCase_ : Any = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def lowerCamelCase_ ( ) -> None: UpperCAmelCase_ : str = (8, 3, 6, 1, 10, 14, 13, 4, 7) UpperCAmelCase_ : Tuple = BinarySearchTree() for i in testlist: t.insert(SCREAMING_SNAKE_CASE__ ) # Prints all the elements of the list in order traversal print(SCREAMING_SNAKE_CASE__ ) if t.search(6 ) is not None: print('''The value 6 exists''' ) else: print('''The value 6 doesn\'t exist''' ) if t.search(-1 ) is not None: print('''The value -1 exists''' ) else: print('''The value -1 doesn\'t exist''' ) if not t.empty(): print('''Max Value: ''', t.get_max().value ) # type: ignore print('''Min Value: ''', t.get_min().value ) # type: ignore for i in testlist: t.remove(SCREAMING_SNAKE_CASE__ ) print(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
644
0
import argparse from torch import nn # transformers_old should correspond to branch `save_old_prophetnet_model_structure` here # original prophetnet_checkpoints are saved under `patrickvonplaten/..._old` respectively from transformers_old.modeling_prophetnet import ( ProphetNetForConditionalGeneration as ProphetNetForConditionalGenerationOld, ) from transformers_old.modeling_xlm_prophetnet import ( XLMProphetNetForConditionalGeneration as XLMProphetNetForConditionalGenerationOld, ) from transformers import ProphetNetForConditionalGeneration, XLMProphetNetForConditionalGeneration, logging snake_case_ : Optional[Any] = logging.get_logger(__name__) logging.set_verbosity_info() def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : str, SCREAMING_SNAKE_CASE__ : str ) -> Tuple: if "xprophetnet" in prophetnet_checkpoint_path: UpperCAmelCase_ : str = XLMProphetNetForConditionalGenerationOld.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[str] = XLMProphetNetForConditionalGeneration.from_pretrained( SCREAMING_SNAKE_CASE__, output_loading_info=SCREAMING_SNAKE_CASE__ ) else: UpperCAmelCase_ : Tuple = ProphetNetForConditionalGenerationOld.from_pretrained(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Optional[int] = ProphetNetForConditionalGeneration.from_pretrained( SCREAMING_SNAKE_CASE__, output_loading_info=SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Any = ['''key_proj''', '''value_proj''', '''query_proj'''] UpperCAmelCase_ : Dict = { '''self_attn''': '''ngram_self_attn''', '''cross_attn''': '''encoder_attn''', '''cross_attn_layer_norm''': '''encoder_attn_layer_norm''', '''feed_forward_layer_norm''': '''final_layer_norm''', '''feed_forward''': '''''', '''intermediate''': '''fc1''', '''output''': '''fc2''', '''key_proj''': '''k_proj''', '''query_proj''': '''q_proj''', '''value_proj''': '''v_proj''', '''word_embeddings''': '''embed_tokens''', '''embeddings_layer_norm''': '''emb_layer_norm''', '''relative_pos_embeddings''': '''relative_linear''', '''ngram_embeddings''': '''ngram_input_embed''', '''position_embeddings''': '''embed_positions''', } for key in loading_info["missing_keys"]: UpperCAmelCase_ : Union[str, Any] = key.split('''.''' ) if attributes[0] == "lm_head": UpperCAmelCase_ : Tuple = prophet UpperCAmelCase_ : Optional[int] = prophet_old else: UpperCAmelCase_ : Optional[int] = prophet.prophetnet UpperCAmelCase_ : Optional[Any] = prophet_old.model UpperCAmelCase_ : Any = False for attribute in attributes: if attribute in mapping: UpperCAmelCase_ : Union[str, Any] = mapping[attribute] if not hasattr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) and len(SCREAMING_SNAKE_CASE__ ) > 0: UpperCAmelCase_ : str = attribute elif hasattr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Dict = attribute if attribute == "weight": assert old_model.weight.shape == model.weight.shape, "Shapes have to match!" UpperCAmelCase_ : Union[str, Any] = old_model.weight logger.info(F"""{attribute} is initialized.""" ) UpperCAmelCase_ : Optional[int] = True break elif attribute == "bias": assert old_model.bias.shape == model.bias.shape, "Shapes have to match!" UpperCAmelCase_ : int = old_model.bias logger.info(F"""{attribute} is initialized""" ) UpperCAmelCase_ : Optional[int] = True break elif attribute in special_keys and hasattr(SCREAMING_SNAKE_CASE__, '''in_proj_weight''' ): UpperCAmelCase_ : Union[str, Any] = old_model.in_proj_weight.shape[0] // 3 UpperCAmelCase_ : int = getattr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) param.weight.shape == old_model.in_proj_weight[:embed_dim, :].shape, "Shapes have to match" param.bias.shape == old_model.in_proj_bias[:embed_dim].shape, "Shapes have to match" if attribute == "query_proj": UpperCAmelCase_ : List[Any] = nn.Parameter(old_model.in_proj_weight[:embed_dim, :] ) UpperCAmelCase_ : Optional[int] = nn.Parameter(old_model.in_proj_bias[:embed_dim] ) elif attribute == "key_proj": UpperCAmelCase_ : str = nn.Parameter(old_model.in_proj_weight[embed_dim : 2 * embed_dim, :] ) UpperCAmelCase_ : List[Any] = nn.Parameter(old_model.in_proj_bias[embed_dim : 2 * embed_dim] ) elif attribute == "value_proj": UpperCAmelCase_ : Any = nn.Parameter(old_model.in_proj_weight[2 * embed_dim :, :] ) UpperCAmelCase_ : str = nn.Parameter(old_model.in_proj_bias[2 * embed_dim :] ) UpperCAmelCase_ : Union[str, Any] = True break elif attribute == "position_embeddings": assert ( model.position_embeddings.weight.shape[-1] == old_model.embed_positions.weight.shape[-1] ), "Hidden size has to match" assert model.position_embeddings.weight.shape[0] == 512, "We want 512 position_embeddings." UpperCAmelCase_ : List[str] = nn.Parameter(old_model.embed_positions.weight[:512, :] ) UpperCAmelCase_ : Optional[int] = True break if attribute.isdigit(): UpperCAmelCase_ : Any = model[int(SCREAMING_SNAKE_CASE__ )] UpperCAmelCase_ : Optional[Any] = old_model[int(SCREAMING_SNAKE_CASE__ )] else: UpperCAmelCase_ : Tuple = getattr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) if old_attribute == "": UpperCAmelCase_ : Dict = old_model else: if not hasattr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ): raise ValueError(F"""{old_model} does not have {old_attribute}""" ) UpperCAmelCase_ : Union[str, Any] = getattr(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) if not is_key_init: raise ValueError(F"""{key} was not correctly initialized!""" ) print(F"""Saving model to {pytorch_dump_folder_path}""" ) prophet.save_pretrained(SCREAMING_SNAKE_CASE__ ) if __name__ == "__main__": snake_case_ : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( "--prophetnet_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." ) snake_case_ : Union[str, Any] = parser.parse_args() convert_prophetnet_checkpoint_to_pytorch(args.prophetnet_checkpoint_path, args.pytorch_dump_folder_path)
713
'''simple docstring''' import sys import turtle def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float] ) -> tuple[float, float]: return (pa[0] + pa[0]) / 2, (pa[1] + pa[1]) / 2 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : tuple[float, float], SCREAMING_SNAKE_CASE__ : int, ) -> None: my_pen.up() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.down() my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) my_pen.goto(vertexa[0], vertexa[1] ) if depth == 0: return triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) triangle(SCREAMING_SNAKE_CASE__, get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), get_mid(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ), depth - 1 ) if __name__ == "__main__": if len(sys.argv) != 2: raise ValueError( "Correct format for using this script: " "python fractals.py <int:depth_for_fractal>" ) snake_case_ : Any = turtle.Turtle() my_pen.ht() my_pen.speed(5) my_pen.pencolor("red") snake_case_ : Tuple = [(-1_75, -1_25), (0, 1_75), (1_75, -1_25)] # vertices of triangle triangle(vertices[0], vertices[1], vertices[2], int(sys.argv[1]))
644
0
import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = '''ylacombe/bark-small''' UpperCAmelCase_ : Any = tempfile.mkdtemp() UpperCAmelCase_ : Dict = '''en_speaker_1''' UpperCAmelCase_ : Dict = '''This is a test string''' UpperCAmelCase_ : List[Any] = '''speaker_embeddings_path.json''' UpperCAmelCase_ : Union[str, Any] = '''speaker_embeddings''' def UpperCAmelCase__ ( self : int , **__magic_name__ : List[Any] ) -> Any: """simple docstring""" return AutoTokenizer.from_pretrained(self.checkpoint , **__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def UpperCAmelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : str = self.get_tokenizer() UpperCAmelCase_ : Tuple = BarkProcessor(tokenizer=__magic_name__ ) processor.save_pretrained(self.tmpdirname ) UpperCAmelCase_ : str = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def UpperCAmelCase__ ( self : Dict ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) UpperCAmelCase_ : Dict = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) UpperCAmelCase_ : Tuple = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='''(BOS)''' , eos_token='''(EOS)''' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" UpperCAmelCase_ : str = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) UpperCAmelCase_ : Union[str, Any] = 35 UpperCAmelCase_ : Optional[Any] = 2 UpperCAmelCase_ : Tuple = 8 UpperCAmelCase_ : str = { '''semantic_prompt''': np.ones(__magic_name__ ), '''coarse_prompt''': np.ones((nb_codebooks_coarse, seq_len) ), '''fine_prompt''': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset UpperCAmelCase_ : Optional[int] = processor(text=self.input_string , voice_preset=__magic_name__ ) UpperCAmelCase_ : Tuple = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__magic_name__ , np.array([] ) ).tolist() ) # test loading voice preset from npz file UpperCAmelCase_ : List[str] = os.path.join(self.tmpdirname , '''file.npz''' ) np.savez(__magic_name__ , **__magic_name__ ) UpperCAmelCase_ : Tuple = processor(text=self.input_string , voice_preset=__magic_name__ ) UpperCAmelCase_ : List[str] = inputs['''history_prompt'''] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(__magic_name__ , np.array([] ) ).tolist() ) # test loading voice preset from the hub UpperCAmelCase_ : int = processor(text=self.input_string , voice_preset=self.voice_preset ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Any = self.get_tokenizer() UpperCAmelCase_ : str = BarkProcessor(tokenizer=__magic_name__ ) UpperCAmelCase_ : Dict = processor(text=self.input_string ) UpperCAmelCase_ : Optional[int] = tokenizer( self.input_string , padding='''max_length''' , max_length=2_56 , add_special_tokens=__magic_name__ , return_attention_mask=__magic_name__ , return_token_type_ids=__magic_name__ , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
714
'''simple docstring''' import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device snake_case_ : List[str] = False class __a (unittest.TestCase ): pass @nightly @require_torch_gpu class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : int ) -> str: """simple docstring""" # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self : List[str] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : List[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCAmelCase_ : Optional[int] = torch.manual_seed(0 ) UpperCAmelCase_ : Union[str, Any] = pipe.dual_guided( prompt='''first prompt''' , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(__magic_name__ ) UpperCAmelCase_ : Optional[int] = VersatileDiffusionPipeline.from_pretrained(__magic_name__ , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Any = generator.manual_seed(0 ) UpperCAmelCase_ : Dict = pipe.dual_guided( prompt='''first prompt''' , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='''numpy''' , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : str = VersatileDiffusionPipeline.from_pretrained('''shi-labs/versatile-diffusion''' , torch_dtype=torch.floataa ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Union[str, Any] = '''cyberpunk 2077''' UpperCAmelCase_ : Union[str, Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''' ) UpperCAmelCase_ : Tuple = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = pipe.dual_guided( prompt=__magic_name__ , image=__magic_name__ , text_to_image_strength=0.7_5 , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' , ).images UpperCAmelCase_ : List[str] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Union[str, Any] = np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 UpperCAmelCase_ : Tuple = '''A painting of a squirrel eating a burger ''' UpperCAmelCase_ : Optional[int] = torch.manual_seed(0 ) UpperCAmelCase_ : List[Any] = pipe.text_to_image( prompt=__magic_name__ , generator=__magic_name__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='''numpy''' ).images UpperCAmelCase_ : Tuple = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : Any = np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 UpperCAmelCase_ : Tuple = pipe.image_variation(__magic_name__ , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Optional[Any] = image[0, 2_53:2_56, 2_53:2_56, -1] assert image.shape == (1, 5_12, 5_12, 3) UpperCAmelCase_ : List[str] = np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
644
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case_ : Dict = { "configuration_nllb_moe": [ "NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP", "NllbMoeConfig", ] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Dict = [ "NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST", "NllbMoeForConditionalGeneration", "NllbMoeModel", "NllbMoePreTrainedModel", "NllbMoeTop2Router", "NllbMoeSparseMLP", ] if TYPE_CHECKING: from .configuration_nllb_moe import ( NLLB_MOE_PRETRAINED_CONFIG_ARCHIVE_MAP, NllbMoeConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_nllb_moe import ( NLLB_MOE_PRETRAINED_MODEL_ARCHIVE_LIST, NllbMoeForConditionalGeneration, NllbMoeModel, NllbMoePreTrainedModel, NllbMoeSparseMLP, NllbMoeTopaRouter, ) else: import sys snake_case_ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
715
'''simple docstring''' snake_case_ : int = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
644
0
'''simple docstring''' from __future__ import annotations def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : float, SCREAMING_SNAKE_CASE__ : float, SCREAMING_SNAKE_CASE__ : float, ) -> tuple: if (electron_conc, hole_conc, intrinsic_conc).count(0 ) != 1: raise ValueError('''You cannot supply more or less than 2 values''' ) elif electron_conc < 0: raise ValueError('''Electron concentration cannot be negative in a semiconductor''' ) elif hole_conc < 0: raise ValueError('''Hole concentration cannot be negative in a semiconductor''' ) elif intrinsic_conc < 0: raise ValueError( '''Intrinsic concentration cannot be negative in a semiconductor''' ) elif electron_conc == 0: return ( "electron_conc", intrinsic_conc**2 / hole_conc, ) elif hole_conc == 0: return ( "hole_conc", intrinsic_conc**2 / electron_conc, ) elif intrinsic_conc == 0: return ( "intrinsic_conc", (electron_conc * hole_conc) ** 0.5, ) else: return (-1, -1) if __name__ == "__main__": import doctest doctest.testmod()
716
'''simple docstring''' import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __a (unittest.TestCase ): @property def UpperCAmelCase__ ( self : Dict ) -> str: """simple docstring""" torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def UpperCAmelCase__ ( self : Dict ) -> Tuple: """simple docstring""" UpperCAmelCase_ : List[Any] = self.dummy_uncond_unet UpperCAmelCase_ : Dict = KarrasVeScheduler() UpperCAmelCase_ : Union[str, Any] = KarrasVePipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Dict = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[int] = pipe(num_inference_steps=2 , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Tuple = torch.manual_seed(0 ) UpperCAmelCase_ : str = pipe(num_inference_steps=2 , generator=__magic_name__ , output_type='''numpy''' , return_dict=__magic_name__ )[0] UpperCAmelCase_ : Union[str, Any] = image[0, -3:, -3:, -1] UpperCAmelCase_ : Optional[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase_ : Dict = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : List[str] = '''google/ncsnpp-celebahq-256''' UpperCAmelCase_ : List[str] = UNetaDModel.from_pretrained(__magic_name__ ) UpperCAmelCase_ : List[Any] = KarrasVeScheduler() UpperCAmelCase_ : Any = KarrasVePipeline(unet=__magic_name__ , scheduler=__magic_name__ ) pipe.to(__magic_name__ ) pipe.set_progress_bar_config(disable=__magic_name__ ) UpperCAmelCase_ : Dict = torch.manual_seed(0 ) UpperCAmelCase_ : Optional[Any] = pipe(num_inference_steps=20 , generator=__magic_name__ , output_type='''numpy''' ).images UpperCAmelCase_ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) UpperCAmelCase_ : Optional[Any] = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
644
0
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int = 50 ) -> int: '''simple docstring''' UpperCAmelCase_ : Tuple = [1] * (length + 1) for row_length in range(3, length + 1 ): for block_length in range(3, row_length + 1 ): for block_start in range(row_length - block_length ): ways_number[row_length] += ways_number[ row_length - block_start - block_length - 1 ] ways_number[row_length] += 1 return ways_number[length] if __name__ == "__main__": print(f'''{solution() = }''')
717
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class __a (lowerCamelCase ): __a : List[Any] = "openai/whisper-base" __a : Optional[Any] = ( "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the " "transcribed text." ) __a : Any = "transcriber" __a : str = WhisperProcessor __a : List[Any] = WhisperForConditionalGeneration __a : int = ["audio"] __a : Optional[Any] = ["text"] def UpperCAmelCase__ ( self : Dict , __magic_name__ : List[str] ) -> Optional[int]: """simple docstring""" return self.pre_processor(__magic_name__ , return_tensors='''pt''' ).input_features def UpperCAmelCase__ ( self : Dict , __magic_name__ : Dict ) -> Tuple: """simple docstring""" return self.model.generate(inputs=__magic_name__ ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Dict ) -> str: """simple docstring""" return self.pre_processor.batch_decode(__magic_name__ , skip_special_tokens=__magic_name__ )[0]
644
0
'''simple docstring''' import unittest from transformers import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING, is_vision_available, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class __a : @staticmethod def UpperCAmelCase__ ( *__magic_name__ : Optional[Any] , **__magic_name__ : Tuple ) -> int: """simple docstring""" pass @is_pipeline_test @require_vision @require_torch class __a (unittest.TestCase ): __a : Union[str, Any] = MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING def UpperCAmelCase__ ( self : Optional[Any] , __magic_name__ : Union[str, Any] , __magic_name__ : Tuple , __magic_name__ : str ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Dict = pipeline( '''zero-shot-object-detection''' , model='''hf-internal-testing/tiny-random-owlvit-object-detection''' ) UpperCAmelCase_ : int = [ { '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], } ] return object_detector, examples def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : str = object_detector(examples[0] , threshold=0.0 ) UpperCAmelCase_ : int = len(__magic_name__ ) self.assertGreater(__magic_name__ , 0 ) self.assertEqual( __magic_name__ , [ { '''score''': ANY(__magic_name__ ), '''label''': ANY(__magic_name__ ), '''box''': {'''xmin''': ANY(__magic_name__ ), '''ymin''': ANY(__magic_name__ ), '''xmax''': ANY(__magic_name__ ), '''ymax''': ANY(__magic_name__ )}, } for i in range(__magic_name__ ) ] , ) @require_tf @unittest.skip('''Zero Shot Object Detection not implemented in TF''' ) def UpperCAmelCase__ ( self : str ) -> Optional[int]: """simple docstring""" pass @require_torch def UpperCAmelCase__ ( self : str ) -> Tuple: """simple docstring""" UpperCAmelCase_ : Tuple = pipeline( '''zero-shot-object-detection''' , model='''hf-internal-testing/tiny-random-owlvit-object-detection''' ) UpperCAmelCase_ : List[Any] = object_detector( '''./tests/fixtures/tests_samples/COCO/000000039769.png''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , threshold=0.6_4 , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ {'''score''': 0.7_2_3_5, '''label''': '''cat''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.7_2_1_8, '''label''': '''remote''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.7_1_8_4, '''label''': '''couch''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.6_7_4_8, '''label''': '''remote''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.6_6_5_6, '''label''': '''cat''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.6_6_1_4, '''label''': '''couch''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.6_4_5_6, '''label''': '''remote''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}}, {'''score''': 0.6_4_2, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 2_74, '''xmax''': 93, '''ymax''': 2_97}}, {'''score''': 0.6_4_1_9, '''label''': '''cat''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}}, ] , ) UpperCAmelCase_ : int = object_detector( [ { '''image''': '''./tests/fixtures/tests_samples/COCO/000000039769.png''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], } ] , threshold=0.6_4 , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ [ {'''score''': 0.7_2_3_5, '''label''': '''cat''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.7_2_1_8, '''label''': '''remote''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.7_1_8_4, '''label''': '''couch''', '''box''': {'''xmin''': 2_04, '''ymin''': 1_67, '''xmax''': 2_32, '''ymax''': 1_90}}, {'''score''': 0.6_7_4_8, '''label''': '''remote''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.6_6_5_6, '''label''': '''cat''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.6_6_1_4, '''label''': '''couch''', '''box''': {'''xmin''': 5_71, '''ymin''': 83, '''xmax''': 5_98, '''ymax''': 1_03}}, {'''score''': 0.6_4_5_6, '''label''': '''remote''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}}, {'''score''': 0.6_4_2, '''label''': '''remote''', '''box''': {'''xmin''': 67, '''ymin''': 2_74, '''xmax''': 93, '''ymax''': 2_97}}, {'''score''': 0.6_4_1_9, '''label''': '''cat''', '''box''': {'''xmin''': 4_94, '''ymin''': 1_05, '''xmax''': 5_21, '''ymax''': 1_27}}, ] ] , ) @require_torch @slow def UpperCAmelCase__ ( self : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = pipeline('''zero-shot-object-detection''' ) UpperCAmelCase_ : Any = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ {'''score''': 0.2_8_6_8, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}}, {'''score''': 0.2_7_7, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}}, {'''score''': 0.2_5_3_7, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}}, {'''score''': 0.1_4_7_4, '''label''': '''remote''', '''box''': {'''xmin''': 3_35, '''ymin''': 74, '''xmax''': 3_71, '''ymax''': 1_87}}, {'''score''': 0.1_2_0_8, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_42, '''ymax''': 4_76}}, ] , ) UpperCAmelCase_ : Any = object_detector( [ { '''image''': '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], }, { '''image''': '''http://images.cocodataset.org/val2017/000000039769.jpg''', '''candidate_labels''': ['''cat''', '''remote''', '''couch'''], }, ] , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ [ {'''score''': 0.2_8_6_8, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}}, {'''score''': 0.2_7_7, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}}, {'''score''': 0.2_5_3_7, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}}, {'''score''': 0.1_4_7_4, '''label''': '''remote''', '''box''': {'''xmin''': 3_35, '''ymin''': 74, '''xmax''': 3_71, '''ymax''': 1_87}}, {'''score''': 0.1_2_0_8, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_42, '''ymax''': 4_76}}, ], [ {'''score''': 0.2_8_6_8, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}}, {'''score''': 0.2_7_7, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}}, {'''score''': 0.2_5_3_7, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}}, {'''score''': 0.1_4_7_4, '''label''': '''remote''', '''box''': {'''xmin''': 3_35, '''ymin''': 74, '''xmax''': 3_71, '''ymax''': 1_87}}, {'''score''': 0.1_2_0_8, '''label''': '''couch''', '''box''': {'''xmin''': 4, '''ymin''': 0, '''xmax''': 6_42, '''ymax''': 4_76}}, ], ] , ) @require_tf @unittest.skip('''Zero Shot Object Detection not implemented in TF''' ) def UpperCAmelCase__ ( self : Any ) -> Dict: """simple docstring""" pass @require_torch @slow def UpperCAmelCase__ ( self : Any ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : str = 0.2 UpperCAmelCase_ : Union[str, Any] = pipeline('''zero-shot-object-detection''' ) UpperCAmelCase_ : Optional[int] = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , threshold=__magic_name__ , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ {'''score''': 0.2_8_6_8, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}}, {'''score''': 0.2_7_7, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}}, {'''score''': 0.2_5_3_7, '''label''': '''cat''', '''box''': {'''xmin''': 1, '''ymin''': 55, '''xmax''': 3_15, '''ymax''': 4_72}}, ] , ) @require_torch @slow def UpperCAmelCase__ ( self : Any ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Tuple = 2 UpperCAmelCase_ : Any = pipeline('''zero-shot-object-detection''' ) UpperCAmelCase_ : List[Any] = object_detector( '''http://images.cocodataset.org/val2017/000000039769.jpg''' , candidate_labels=['''cat''', '''remote''', '''couch'''] , top_k=__magic_name__ , ) self.assertEqual( nested_simplify(__magic_name__ , decimals=4 ) , [ {'''score''': 0.2_8_6_8, '''label''': '''cat''', '''box''': {'''xmin''': 3_24, '''ymin''': 20, '''xmax''': 6_40, '''ymax''': 3_73}}, {'''score''': 0.2_7_7, '''label''': '''remote''', '''box''': {'''xmin''': 40, '''ymin''': 72, '''xmax''': 1_77, '''ymax''': 1_15}}, ] , )
718
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> int: return abs(SCREAMING_SNAKE_CASE__ ) if a == 0 else greatest_common_divisor(b % a, SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int, SCREAMING_SNAKE_CASE__ : int ) -> int: while y: # --> when y=0 then loop will terminate and return x as final GCD. UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = y, x % y return abs(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( ) -> Optional[int]: try: UpperCAmelCase_ : Optional[Any] = input('''Enter two integers separated by comma (,): ''' ).split(''',''' ) UpperCAmelCase_ : Optional[int] = int(nums[0] ) UpperCAmelCase_ : List[Any] = int(nums[1] ) print( F"""greatest_common_divisor({num_a}, {num_a}) = """ F"""{greatest_common_divisor(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )}""" ) print(F"""By iterative gcd({num_a}, {num_a}) = {gcd_by_iterative(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )}""" ) except (IndexError, UnboundLocalError, ValueError): print('''Wrong input''' ) if __name__ == "__main__": main()
644
0
'''simple docstring''' import numpy # List of input, output pairs snake_case_ : Dict = ( ((5, 2, 3), 15), ((6, 5, 9), 25), ((11, 12, 13), 41), ((1, 1, 1), 8), ((11, 12, 13), 41), ) snake_case_ : Optional[int] = (((5_15, 22, 13), 5_55), ((61, 35, 49), 1_50)) snake_case_ : Union[str, Any] = [2, 4, 1, 5] snake_case_ : Optional[Any] = len(train_data) snake_case_ : Tuple = 0.009 def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Dict, SCREAMING_SNAKE_CASE__ : str="train" ) -> Optional[int]: return calculate_hypothesis_value(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) - output( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple ) -> List[Any]: UpperCAmelCase_ : Any = 0 for i in range(len(SCREAMING_SNAKE_CASE__ ) - 1 ): hyp_val += data_input_tuple[i] * parameter_vector[i + 1] hyp_val += parameter_vector[0] return hyp_val def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : int ) -> Tuple: if data_set == "train": return train_data[example_no][1] elif data_set == "test": return test_data[example_no][1] return None def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Union[str, Any], SCREAMING_SNAKE_CASE__ : str ) -> Union[str, Any]: if data_set == "train": return _hypothesis_value(train_data[example_no][0] ) elif data_set == "test": return _hypothesis_value(test_data[example_no][0] ) return None def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : Tuple, SCREAMING_SNAKE_CASE__ : Dict=m ) -> Optional[int]: UpperCAmelCase_ : Dict = 0 for i in range(SCREAMING_SNAKE_CASE__ ): if index == -1: summation_value += _error(SCREAMING_SNAKE_CASE__ ) else: summation_value += _error(SCREAMING_SNAKE_CASE__ ) * train_data[i][0][index] return summation_value def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int ) -> Any: UpperCAmelCase_ : List[Any] = summation_of_cost_derivative(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) / m return cost_derivative_value def lowerCamelCase_ ( ) -> List[str]: global parameter_vector # Tune these values to set a tolerance value for predicted output UpperCAmelCase_ : Optional[Any] = 0.00_00_02 UpperCAmelCase_ : Optional[int] = 0 UpperCAmelCase_ : Tuple = 0 while True: j += 1 UpperCAmelCase_ : List[Any] = [0, 0, 0, 0] for i in range(0, len(SCREAMING_SNAKE_CASE__ ) ): UpperCAmelCase_ : int = get_cost_derivative(i - 1 ) UpperCAmelCase_ : List[Any] = ( parameter_vector[i] - LEARNING_RATE * cost_derivative ) if numpy.allclose( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, atol=SCREAMING_SNAKE_CASE__, rtol=SCREAMING_SNAKE_CASE__, ): break UpperCAmelCase_ : Any = temp_parameter_vector print(('''Number of iterations:''', j) ) def lowerCamelCase_ ( ) -> Optional[Any]: for i in range(len(SCREAMING_SNAKE_CASE__ ) ): print(('''Actual output value:''', output(SCREAMING_SNAKE_CASE__, '''test''' )) ) print(('''Hypothesis output:''', calculate_hypothesis_value(SCREAMING_SNAKE_CASE__, '''test''' )) ) if __name__ == "__main__": run_gradient_descent() print("\nTesting gradient descent for a linear hypothesis function.\n") test_gradient_descent()
719
'''simple docstring''' import unittest from transformers import LiltConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, ) from transformers.models.lilt.modeling_lilt import LILT_PRETRAINED_MODEL_ARCHIVE_LIST class __a : def __init__( self : int , __magic_name__ : Optional[Any] , __magic_name__ : Any=13 , __magic_name__ : Any=7 , __magic_name__ : Union[str, Any]=True , __magic_name__ : Union[str, Any]=True , __magic_name__ : str=True , __magic_name__ : Optional[int]=True , __magic_name__ : List[Any]=99 , __magic_name__ : int=24 , __magic_name__ : Optional[int]=2 , __magic_name__ : Tuple=6 , __magic_name__ : Union[str, Any]=37 , __magic_name__ : Optional[Any]="gelu" , __magic_name__ : Any=0.1 , __magic_name__ : str=0.1 , __magic_name__ : Tuple=5_12 , __magic_name__ : Union[str, Any]=16 , __magic_name__ : Tuple=2 , __magic_name__ : Tuple=0.0_2 , __magic_name__ : Optional[Any]=3 , __magic_name__ : Optional[int]=None , __magic_name__ : Any=10_00 , ) -> str: """simple docstring""" UpperCAmelCase_ : Tuple = parent UpperCAmelCase_ : Optional[int] = batch_size UpperCAmelCase_ : List[str] = seq_length UpperCAmelCase_ : Dict = is_training UpperCAmelCase_ : List[str] = use_input_mask UpperCAmelCase_ : Any = use_token_type_ids UpperCAmelCase_ : Any = use_labels UpperCAmelCase_ : Any = vocab_size UpperCAmelCase_ : Dict = hidden_size UpperCAmelCase_ : Tuple = num_hidden_layers UpperCAmelCase_ : Tuple = num_attention_heads UpperCAmelCase_ : int = intermediate_size UpperCAmelCase_ : Union[str, Any] = hidden_act UpperCAmelCase_ : Optional[int] = hidden_dropout_prob UpperCAmelCase_ : Optional[Any] = attention_probs_dropout_prob UpperCAmelCase_ : Union[str, Any] = max_position_embeddings UpperCAmelCase_ : int = type_vocab_size UpperCAmelCase_ : List[Any] = type_sequence_label_size UpperCAmelCase_ : int = initializer_range UpperCAmelCase_ : Dict = num_labels UpperCAmelCase_ : List[str] = scope UpperCAmelCase_ : List[str] = range_bbox def UpperCAmelCase__ ( self : Optional[int] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ : List[str] = ids_tensor([self.batch_size, self.seq_length, 4] , self.range_bbox ) # Ensure that bbox is legal for i in range(bbox.shape[0] ): for j in range(bbox.shape[1] ): if bbox[i, j, 3] < bbox[i, j, 1]: UpperCAmelCase_ : List[str] = bbox[i, j, 3] UpperCAmelCase_ : Dict = bbox[i, j, 1] UpperCAmelCase_ : Optional[Any] = t if bbox[i, j, 2] < bbox[i, j, 0]: UpperCAmelCase_ : List[str] = bbox[i, j, 2] UpperCAmelCase_ : Tuple = bbox[i, j, 0] UpperCAmelCase_ : Union[str, Any] = t UpperCAmelCase_ : int = None if self.use_input_mask: UpperCAmelCase_ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) UpperCAmelCase_ : Optional[int] = None if self.use_token_type_ids: UpperCAmelCase_ : str = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ : Dict = None UpperCAmelCase_ : Tuple = None if self.use_labels: UpperCAmelCase_ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ : int = self.get_config() return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels def UpperCAmelCase__ ( self : Any ) -> List[Any]: """simple docstring""" return LiltConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , ) def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : str , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : int , __magic_name__ : Optional[Any] , __magic_name__ : int , ) -> Optional[int]: """simple docstring""" UpperCAmelCase_ : Any = LiltModel(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Optional[Any] = model(__magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : List[Any] = model(__magic_name__ , bbox=__magic_name__ , token_type_ids=__magic_name__ ) UpperCAmelCase_ : Optional[int] = model(__magic_name__ , bbox=__magic_name__ ) 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 : int , __magic_name__ : Optional[Any] , __magic_name__ : List[str] , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : str , __magic_name__ : Optional[int] , __magic_name__ : List[Any] , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : Any = self.num_labels UpperCAmelCase_ : List[Any] = LiltForTokenClassification(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : List[Any] = model( __magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , labels=__magic_name__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase__ ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : Dict , __magic_name__ : Any , __magic_name__ : Optional[int] , __magic_name__ : int , __magic_name__ : Tuple , __magic_name__ : Any , ) -> Optional[Any]: """simple docstring""" UpperCAmelCase_ : str = LiltForQuestionAnswering(config=__magic_name__ ) model.to(__magic_name__ ) model.eval() UpperCAmelCase_ : Optional[Any] = model( __magic_name__ , bbox=__magic_name__ , attention_mask=__magic_name__ , token_type_ids=__magic_name__ , start_positions=__magic_name__ , end_positions=__magic_name__ , ) 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 : List[Any] ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Tuple = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) : Optional[int] = config_and_inputs UpperCAmelCase_ : Tuple = { '''input_ids''': input_ids, '''bbox''': bbox, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask, } return config, inputs_dict @require_torch class __a (lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ): __a : Tuple = ( ( LiltModel, LiltForSequenceClassification, LiltForTokenClassification, LiltForQuestionAnswering, ) if is_torch_available() else () ) __a : Any = ( { "feature-extraction": LiltModel, "question-answering": LiltForQuestionAnswering, "text-classification": LiltForSequenceClassification, "token-classification": LiltForTokenClassification, "zero-shot": LiltForSequenceClassification, } if is_torch_available() else {} ) __a : Union[str, Any] = False __a : int = False def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Dict , __magic_name__ : List[Any] , __magic_name__ : Optional[int] , __magic_name__ : Optional[Any] , __magic_name__ : int ) -> str: """simple docstring""" return True def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : List[Any] = LiltModelTester(self ) UpperCAmelCase_ : List[Any] = ConfigTester(self , config_class=__magic_name__ , hidden_size=37 ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> str: """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self : str ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> str: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ : Tuple = type self.model_tester.create_and_check_model(*__magic_name__ ) def UpperCAmelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" UpperCAmelCase_ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__magic_name__ ) def UpperCAmelCase__ ( self : str ) -> List[Any]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__magic_name__ ) @slow def UpperCAmelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" for model_name in LILT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ : Optional[int] = LiltModel.from_pretrained(__magic_name__ ) self.assertIsNotNone(__magic_name__ ) @require_torch @slow class __a (unittest.TestCase ): def UpperCAmelCase__ ( self : Tuple ) -> Tuple: """simple docstring""" UpperCAmelCase_ : str = LiltModel.from_pretrained('''SCUT-DLVCLab/lilt-roberta-en-base''' ).to(__magic_name__ ) UpperCAmelCase_ : Any = torch.tensor([[1, 2]] , device=__magic_name__ ) UpperCAmelCase_ : int = torch.tensor([[[1, 2, 3, 4], [5, 6, 7, 8]]] , device=__magic_name__ ) # forward pass with torch.no_grad(): UpperCAmelCase_ : Optional[int] = model(input_ids=__magic_name__ , bbox=__magic_name__ ) UpperCAmelCase_ : int = torch.Size([1, 2, 7_68] ) UpperCAmelCase_ : List[str] = torch.tensor( [[-0.0_6_5_3, 0.0_9_5_0, -0.0_0_6_1], [-0.0_5_4_5, 0.0_9_2_6, -0.0_3_2_4]] , device=__magic_name__ , ) self.assertTrue(outputs.last_hidden_state.shape , __magic_name__ ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :, :3] , __magic_name__ , atol=1E-3 ) )
644
0
from __future__ import annotations import numpy as np from numpy import floataa from numpy.typing import NDArray def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : NDArray[floataa], SCREAMING_SNAKE_CASE__ : NDArray[floataa], SCREAMING_SNAKE_CASE__ : list[int], SCREAMING_SNAKE_CASE__ : int, ) -> list[float]: UpperCAmelCase_ : Any = coefficient_matrix.shape UpperCAmelCase_ : Dict = constant_matrix.shape if rowsa != colsa: UpperCAmelCase_ : Tuple = F"""Coefficient matrix dimensions must be nxn but received {rowsa}x{colsa}""" raise ValueError(SCREAMING_SNAKE_CASE__ ) if colsa != 1: UpperCAmelCase_ : Union[str, Any] = F"""Constant matrix must be nx1 but received {rowsa}x{colsa}""" raise ValueError(SCREAMING_SNAKE_CASE__ ) if rowsa != rowsa: UpperCAmelCase_ : int = ( '''Coefficient and constant matrices dimensions must be nxn and nx1 but ''' F"""received {rowsa}x{colsa} and {rowsa}x{colsa}""" ) raise ValueError(SCREAMING_SNAKE_CASE__ ) if len(SCREAMING_SNAKE_CASE__ ) != rowsa: UpperCAmelCase_ : List[Any] = ( '''Number of initial values must be equal to number of rows in coefficient ''' F"""matrix but received {len(SCREAMING_SNAKE_CASE__ )} and {rowsa}""" ) raise ValueError(SCREAMING_SNAKE_CASE__ ) if iterations <= 0: raise ValueError('''Iterations must be at least 1''' ) UpperCAmelCase_ : NDArray[floataa] = np.concatenate( (coefficient_matrix, constant_matrix), axis=1 ) UpperCAmelCase_ : Optional[int] = table.shape strictly_diagonally_dominant(SCREAMING_SNAKE_CASE__ ) # Iterates the whole matrix for given number of times for _ in range(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Tuple = [] for row in range(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : List[str] = 0 for col in range(SCREAMING_SNAKE_CASE__ ): if col == row: UpperCAmelCase_ : Union[str, Any] = table[row][col] elif col == cols - 1: UpperCAmelCase_ : str = table[row][col] else: temp += (-1) * table[row][col] * init_val[col] UpperCAmelCase_ : List[Any] = (temp + val) / denom new_val.append(SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : Dict = new_val return [float(SCREAMING_SNAKE_CASE__ ) for i in new_val] def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : NDArray[floataa] ) -> bool: UpperCAmelCase_ : Tuple = table.shape UpperCAmelCase_ : Tuple = True for i in range(0, SCREAMING_SNAKE_CASE__ ): UpperCAmelCase_ : Tuple = 0 for j in range(0, cols - 1 ): if i == j: continue else: total += table[i][j] if table[i][i] <= total: raise ValueError('''Coefficient matrix is not strictly diagonally dominant''' ) return is_diagonally_dominant # Test Cases if __name__ == "__main__": import doctest doctest.testmod()
720
'''simple docstring''' import io import os import unicodedata from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging snake_case_ : str = logging.get_logger(__name__) snake_case_ : int = "▁" snake_case_ : str = {"vocab_file": "vocab.txt", "sentencepiece_model_ckpt": "sentencepiece.bpe.model"} snake_case_ : int = { "sentencepiece_model_file": "sentencepiece.bpe.model", "vocab_file": "vocab.txt", } snake_case_ : Optional[Any] = { "vocab_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/vocab.txt", }, "sentencepiece_model_file": { "ernie-m-base": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", "ernie-m-large": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/sentencepiece.bpe.model", }, } snake_case_ : Dict = { "ernie-m-base": 5_14, "ernie-m-large": 5_14, } snake_case_ : Any = { "ernie-m-base": {"do_lower_case": False}, "ernie-m-large": {"do_lower_case": False}, } class __a (lowerCamelCase ): __a : List[str] = ["input_ids"] __a : Union[str, Any] = VOCAB_FILES_NAMES __a : Tuple = PRETRAINED_INIT_CONFIGURATION __a : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __a : Optional[int] = PRETRAINED_VOCAB_FILES_MAP __a : Union[str, Any] = RESOURCE_FILES_NAMES def __init__( self : Union[str, Any] , __magic_name__ : Dict , __magic_name__ : int=None , __magic_name__ : str=False , __magic_name__ : int="utf8" , __magic_name__ : Optional[int]="[UNK]" , __magic_name__ : Dict="[SEP]" , __magic_name__ : List[Any]="[PAD]" , __magic_name__ : str="[CLS]" , __magic_name__ : Optional[int]="[MASK]" , __magic_name__ : Optional[Dict[str, Any]] = None , **__magic_name__ : Union[str, Any] , ) -> None: """simple docstring""" # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. UpperCAmelCase_ : List[Any] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__magic_name__ , unk_token=__magic_name__ , sep_token=__magic_name__ , pad_token=__magic_name__ , cls_token=__magic_name__ , mask_token=__magic_name__ , vocab_file=__magic_name__ , encoding=__magic_name__ , sp_model_kwargs=self.sp_model_kwargs , **__magic_name__ , ) UpperCAmelCase_ : Optional[Any] = do_lower_case UpperCAmelCase_ : List[str] = sentencepiece_model_ckpt UpperCAmelCase_ : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__magic_name__ ) # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning if vocab_file is not None: UpperCAmelCase_ : List[Any] = self.load_vocab(filepath=__magic_name__ ) else: UpperCAmelCase_ : str = {self.sp_model.id_to_piece(__magic_name__ ): id for id in range(self.sp_model.get_piece_size() )} UpperCAmelCase_ : int = {v: k for k, v in self.vocab.items()} def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Any ) -> Any: """simple docstring""" if text is None: return None UpperCAmelCase_ : str = self.tokenize(__magic_name__ ) UpperCAmelCase_ , UpperCAmelCase_ : str = '''''', [] for i, ch in enumerate(__magic_name__ ): if ch in self.SP_CHAR_MAPPING: UpperCAmelCase_ : Optional[int] = self.SP_CHAR_MAPPING.get(__magic_name__ ) else: UpperCAmelCase_ : Union[str, Any] = unicodedata.normalize('''NFKC''' , __magic_name__ ) if self.is_whitespace(__magic_name__ ): continue normalized_text += ch char_mapping.extend([i] * len(__magic_name__ ) ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Union[str, Any] = normalized_text, [], 0 if self.do_lower_case: UpperCAmelCase_ : Optional[int] = text.lower() for token in split_tokens: if token[:1] == "▁": UpperCAmelCase_ : Tuple = token[1:] UpperCAmelCase_ : int = text[offset:].index(__magic_name__ ) + offset UpperCAmelCase_ : Optional[int] = start + len(__magic_name__ ) token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1) ) UpperCAmelCase_ : int = end return token_mapping @property def UpperCAmelCase__ ( self : Any ) -> Any: """simple docstring""" return len(self.vocab ) def UpperCAmelCase__ ( self : List[Any] ) -> int: """simple docstring""" return dict(self.vocab , **self.added_tokens_encoder ) def __getstate__( self : str ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[Any] = self.__dict__.copy() UpperCAmelCase_ : Optional[Any] = None return state def __setstate__( self : str , __magic_name__ : Any ) -> Dict: """simple docstring""" UpperCAmelCase_ : Dict = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): UpperCAmelCase_ : int = {} UpperCAmelCase_ : List[Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.sentencepiece_model_ckpt ) def UpperCAmelCase__ ( self : Optional[int] , __magic_name__ : Any ) -> List[str]: """simple docstring""" return "".join((self.SP_CHAR_MAPPING.get(__magic_name__ , __magic_name__ ) for c in text) ) def UpperCAmelCase__ ( self : List[str] , __magic_name__ : Tuple , __magic_name__ : Any=False , __magic_name__ : List[str]=64 , __magic_name__ : List[str]=0.1 ) -> List[str]: """simple docstring""" if self.sp_model_kwargs.get('''enable_sampling''' ) is True: UpperCAmelCase_ : Dict = True if self.sp_model_kwargs.get('''alpha''' ) is not None: UpperCAmelCase_ : Union[str, Any] = self.sp_model_kwargs.get('''alpha''' ) if self.sp_model_kwargs.get('''nbest_size''' ) is not None: UpperCAmelCase_ : Any = self.sp_model_kwargs.get('''nbest_size''' ) if not enable_sampling: UpperCAmelCase_ : Dict = self.sp_model.EncodeAsPieces(__magic_name__ ) else: UpperCAmelCase_ : Dict = self.sp_model.SampleEncodeAsPieces(__magic_name__ , __magic_name__ , __magic_name__ ) UpperCAmelCase_ : List[Any] = [] for pi, piece in enumerate(__magic_name__ ): if piece == SPIECE_UNDERLINE: if not pieces[pi + 1].startswith(__magic_name__ ) and pi != 0: new_pieces.append(__magic_name__ ) continue else: continue UpperCAmelCase_ : List[str] = 0 for i, chunk in enumerate(__magic_name__ ): if chunk == SPIECE_UNDERLINE: continue if self.is_ch_char(__magic_name__ ) or self.is_punct(__magic_name__ ): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) new_pieces.append(__magic_name__ ) UpperCAmelCase_ : List[Any] = i + 1 elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) UpperCAmelCase_ : List[str] = i elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit(): if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE: new_pieces.append(piece[lst_i:i] ) UpperCAmelCase_ : str = i if len(__magic_name__ ) > lst_i: new_pieces.append(piece[lst_i:] ) return new_pieces def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Optional[int] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : Optional[Any] = ''''''.join(__magic_name__ ).replace(__magic_name__ , ''' ''' ).strip() return out_string def UpperCAmelCase__ ( self : List[Any] , __magic_name__ : Union[str, Any] ) -> List[str]: """simple docstring""" UpperCAmelCase_ : str = self.convert_ids_to_tokens(__magic_name__ ) UpperCAmelCase_ : Optional[Any] = ''''''.join(__magic_name__ ).replace(__magic_name__ , ''' ''' ).strip() return out_string def UpperCAmelCase__ ( self : str , __magic_name__ : Optional[Any] ) -> List[Any]: """simple docstring""" return self.vocab.get(__magic_name__ , self.vocab.get(self.unk_token ) ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return self.reverse_vocab.get(__magic_name__ , self.unk_token ) def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Any , __magic_name__ : Union[str, Any]=None ) -> Any: """simple docstring""" if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] UpperCAmelCase_ : Union[str, Any] = [self.cls_token_id] UpperCAmelCase_ : List[Any] = [self.sep_token_id] return _cls + token_ids_a + _sep + _sep + token_ids_a + _sep def UpperCAmelCase__ ( self : Any , __magic_name__ : Optional[Any] , __magic_name__ : List[str]=None ) -> int: """simple docstring""" if offset_mapping_a is None: return [(0, 0)] + offset_mapping_a + [(0, 0)] return [(0, 0)] + offset_mapping_a + [(0, 0), (0, 0)] + offset_mapping_a + [(0, 0)] def UpperCAmelCase__ ( self : Dict , __magic_name__ : Optional[Any] , __magic_name__ : List[str]=None , __magic_name__ : Optional[Any]=False ) -> Optional[int]: """simple docstring""" if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__magic_name__ )) + [1, 1] + ([0] * len(__magic_name__ )) + [1] return [1] + ([0] * len(__magic_name__ )) + [1] def UpperCAmelCase__ ( self : List[str] , __magic_name__ : List[int] , __magic_name__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method if token_ids_a is None: # [CLS] X [SEP] return (len(__magic_name__ ) + 2) * [0] # [CLS] A [SEP] [SEP] B [SEP] return [0] * (len(__magic_name__ ) + 1) + [1] * (len(__magic_name__ ) + 3) def UpperCAmelCase__ ( self : Dict , __magic_name__ : str ) -> Tuple: """simple docstring""" if "\u4e00" <= char <= "\u9fff": return True return False def UpperCAmelCase__ ( self : int , __magic_name__ : Optional[int] ) -> str: """simple docstring""" if ("a" <= char <= "z") or ("A" <= char <= "Z"): return True return False def UpperCAmelCase__ ( self : int , __magic_name__ : Optional[Any] ) -> Dict: """simple docstring""" if char in ",;:.?!~,;:。?!《》【】": return True return False def UpperCAmelCase__ ( self : Tuple , __magic_name__ : Any ) -> Union[str, Any]: """simple docstring""" if char == " " or char == "\t" or char == "\n" or char == "\r": return True if len(__magic_name__ ) == 1: UpperCAmelCase_ : Optional[Any] = unicodedata.category(__magic_name__ ) if cat == "Zs": return True return False def UpperCAmelCase__ ( self : Union[str, Any] , __magic_name__ : Tuple ) -> Any: """simple docstring""" UpperCAmelCase_ : Optional[Any] = {} with io.open(__magic_name__ , '''r''' , encoding='''utf-8''' ) as f: for index, line in enumerate(__magic_name__ ): UpperCAmelCase_ : List[Any] = line.rstrip('''\n''' ) UpperCAmelCase_ : Dict = int(__magic_name__ ) return token_to_idx def UpperCAmelCase__ ( self : Dict , __magic_name__ : str , __magic_name__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" UpperCAmelCase_ : Union[str, Any] = 0 if os.path.isdir(__magic_name__ ): UpperCAmelCase_ : Any = os.path.join( __magic_name__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) else: UpperCAmelCase_ : List[str] = (filename_prefix + '''-''' if filename_prefix else '''''') + save_directory with open(__magic_name__ , '''w''' , encoding='''utf-8''' ) as writer: for token, token_index in sorted(self.vocab.items() , key=lambda __magic_name__ : kv[1] ): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ''' Please check that the vocabulary is not corrupted!''' ) UpperCAmelCase_ : Dict = token_index writer.write(token + '''\n''' ) index += 1 UpperCAmelCase_ : Union[str, Any] = os.path.join(__magic_name__ , '''sentencepiece.bpe.model''' ) with open(__magic_name__ , '''wb''' ) as fi: UpperCAmelCase_ : Optional[int] = self.sp_model.serialized_model_proto() fi.write(__magic_name__ ) return (vocab_file,)
644
0
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int = 10, SCREAMING_SNAKE_CASE__ : int = 22 ) -> int: UpperCAmelCase_ : Optional[int] = range(1, SCREAMING_SNAKE_CASE__ ) UpperCAmelCase_ : List[Any] = range(1, SCREAMING_SNAKE_CASE__ ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(f'''{solution(10, 22) = }''')
721
'''simple docstring''' def lowerCamelCase_ ( SCREAMING_SNAKE_CASE__ : int ) -> str: if number > 0: raise ValueError('''input must be a negative integer''' ) UpperCAmelCase_ : Union[str, Any] = len(bin(SCREAMING_SNAKE_CASE__ )[3:] ) UpperCAmelCase_ : Union[str, Any] = bin(abs(SCREAMING_SNAKE_CASE__ ) - (1 << binary_number_length) )[3:] UpperCAmelCase_ : Optional[Any] = ( ( '''1''' + '''0''' * (binary_number_length - len(SCREAMING_SNAKE_CASE__ )) + twos_complement_number ) if number < 0 else '''0''' ) return "0b" + twos_complement_number if __name__ == "__main__": import doctest doctest.testmod()
644
0
"""simple docstring""" import logging import torch from accelerate import Accelerator from arguments import EvaluationArguments from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set_seed class UpperCAmelCase_ ( _a): def __init__( self , a , a , a=1_0_2_4 , a=1_0_2_4 , a=3.6 ) -> Any: lowercase__ : List[Any] = tokenizer lowercase__ : Dict = tokenizer.bos_token_id lowercase__ : Optional[Any] = dataset lowercase__ : str = seq_length lowercase__ : int = seq_length * chars_per_token * num_of_sequences def __iter__( self ) -> List[str]: lowercase__ : List[Any] = iter(self.dataset ) lowercase__ : Tuple = True while more_examples: lowercase__ , lowercase__ : Optional[Any] = [], 0 while True: if buffer_len >= self.input_characters: break try: buffer.append(next(a )['content'] ) buffer_len += len(buffer[-1] ) except StopIteration: lowercase__ : List[Any] = False break lowercase__ : Optional[int] = tokenizer(a , truncation=a )['input_ids'] lowercase__ : Any = [] for tokenized_input in tokenized_inputs: all_token_ids.extend(tokenized_input + [self.concat_token_id] ) for i in range(0 , len(a ) , self.seq_length ): lowercase__ : Optional[int] = all_token_ids[i : i + self.seq_length] if len(a ) == self.seq_length: yield torch.tensor(a ) def a_ ( _lowerCAmelCase : Optional[Any] ): '''simple docstring''' lowercase__ : int = {'streaming': True} lowercase__ : List[str] = load_dataset(args.dataset_name , split='train' , **_lowerCAmelCase ) lowercase__ : Any = ConstantLengthDataset(_lowerCAmelCase , _lowerCAmelCase , seq_length=args.seq_length ) lowercase__ : Union[str, Any] = DataLoader(_lowerCAmelCase , batch_size=args.batch_size ) return eval_dataloader def a_ ( _lowerCAmelCase : Union[str, Any] ): '''simple docstring''' model.eval() lowercase__ : List[Any] = [] for step, batch in enumerate(_lowerCAmelCase ): with torch.no_grad(): lowercase__ : Any = model(_lowerCAmelCase , labels=_lowerCAmelCase ) lowercase__ : List[str] = outputs.loss.repeat(args.batch_size ) losses.append(accelerator.gather(_lowerCAmelCase ) ) if args.max_eval_steps > 0 and step >= args.max_eval_steps: break lowercase__ : int = torch.mean(torch.cat(_lowerCAmelCase ) ) try: lowercase__ : Optional[Any] = torch.exp(_lowerCAmelCase ) except OverflowError: lowercase__ : Tuple = float('inf' ) return loss.item(), perplexity.item() # Setup Accelerator _UpperCamelCase : Optional[int] = Accelerator() # Parse configuration _UpperCamelCase : int = HfArgumentParser(EvaluationArguments) _UpperCamelCase : Dict = parser.parse_args() set_seed(args.seed) # Logging _UpperCamelCase : List[str] = logging.getLogger(__name__) logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO ) # Load model and tokenizer _UpperCamelCase : Dict = AutoModelForCausalLM.from_pretrained(args.model_ckpt) _UpperCamelCase : Tuple = AutoTokenizer.from_pretrained(args.model_ckpt) # Load dataset and dataloader _UpperCamelCase : Union[str, Any] = create_dataloader(args) # Prepare everything with our `accelerator`. _UpperCamelCase , _UpperCamelCase : int = accelerator.prepare(model, eval_dataloader) # Evaluate and save the last checkpoint logger.info("Evaluating and saving model after training") _UpperCamelCase , _UpperCamelCase : Optional[int] = evaluate(args) logger.info(f'''loss/eval: {eval_loss}, perplexity: {perplexity}''')
645
"""simple docstring""" import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def a_ ( _lowerCAmelCase : dict ): '''simple docstring''' return (data["data"], data["target"]) def a_ ( _lowerCAmelCase : np.ndarray , _lowerCAmelCase : np.ndarray , _lowerCAmelCase : np.ndarray ): '''simple docstring''' lowercase__ : Any = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(_lowerCAmelCase , _lowerCAmelCase ) # Predict target for test data lowercase__ : str = xgb.predict(_lowerCAmelCase ) lowercase__ : Union[str, Any] = predictions.reshape(len(_lowerCAmelCase ) , 1 ) return predictions def a_ ( ): '''simple docstring''' lowercase__ : Optional[Any] = fetch_california_housing() lowercase__ , lowercase__ : str = data_handling(_lowerCAmelCase ) lowercase__ , lowercase__ , lowercase__ , lowercase__ : str = train_test_split( _lowerCAmelCase , _lowerCAmelCase , test_size=0.2_5 , random_state=1 ) lowercase__ : Any = xgboost(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # Error printing print(f"""Mean Absolute Error : {mean_absolute_error(_lowerCAmelCase , _lowerCAmelCase )}""" ) print(f"""Mean Square Error : {mean_squared_error(_lowerCAmelCase , _lowerCAmelCase )}""" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
645
1
"""simple docstring""" import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", level=logging.INFO, ) _UpperCamelCase : str = logging.getLogger(__name__) def a_ ( _lowerCAmelCase : str ): '''simple docstring''' lowercase__ : Any = git.Repo(search_parent_directories=_lowerCAmelCase ) lowercase__ : Any = { 'repo_id': str(_lowerCAmelCase ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), } with open(os.path.join(_lowerCAmelCase , 'git_log.json' ) , 'w' ) as f: json.dump(_lowerCAmelCase , _lowerCAmelCase , indent=4 ) def a_ ( _lowerCAmelCase : List[Any] ): '''simple docstring''' if params.n_gpu <= 0: lowercase__ : Dict = 0 lowercase__ : List[Any] = -1 lowercase__ : List[str] = True lowercase__ : Union[str, Any] = False return assert torch.cuda.is_available() logger.info('Initializing GPUs' ) if params.n_gpu > 1: assert params.local_rank != -1 lowercase__ : Optional[int] = int(os.environ['WORLD_SIZE'] ) lowercase__ : Union[str, Any] = int(os.environ['N_GPU_NODE'] ) lowercase__ : List[Any] = int(os.environ['RANK'] ) # number of nodes / node ID lowercase__ : int = params.world_size // params.n_gpu_per_node lowercase__ : List[Any] = params.global_rank // params.n_gpu_per_node lowercase__ : List[str] = 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 lowercase__ : List[str] = 1 lowercase__ : Tuple = 0 lowercase__ : int = 0 lowercase__ : List[Any] = 0 lowercase__ : int = 1 lowercase__ : List[Any] = 1 lowercase__ : 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 lowercase__ : Tuple = params.node_id == 0 and params.local_rank == 0 lowercase__ : Optional[int] = params.n_nodes > 1 # summary lowercase__ : Union[str, Any] = f"""--- Global rank: {params.global_rank} - """ logger.info(PREFIX + 'Number of nodes: %i' % params.n_nodes ) logger.info(PREFIX + 'Node ID : %i' % params.node_id ) logger.info(PREFIX + 'Local rank : %i' % params.local_rank ) logger.info(PREFIX + 'World size : %i' % params.world_size ) logger.info(PREFIX + 'GPUs per node : %i' % params.n_gpu_per_node ) logger.info(PREFIX + 'Master : %s' % str(params.is_master ) ) logger.info(PREFIX + 'Multi-node : %s' % str(params.multi_node ) ) logger.info(PREFIX + 'Multi-GPU : %s' % str(params.multi_gpu ) ) logger.info(PREFIX + 'Hostname : %s' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('Initializing PyTorch distributed' ) torch.distributed.init_process_group( init_method='env://' , backend='nccl' , ) def a_ ( _lowerCAmelCase : List[Any] ): '''simple docstring''' np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
645
"""simple docstring""" import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEModel, ) from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class UpperCAmelCase_ : def __init__( self , a , a=1_3 , a=1_0 , a=3 , a=2 , a=2 , a=2 , a=True , a=True , a=3_2 , a=5 , a=4 , a=3_7 , a="gelu" , a=0.1 , a=0.1 , a=1_0 , a=0.02 , a=0.9 , a=None , ) -> Optional[Any]: lowercase__ : str = parent lowercase__ : int = batch_size lowercase__ : Union[str, Any] = image_size lowercase__ : Optional[Any] = num_channels lowercase__ : Dict = patch_size lowercase__ : Tuple = tubelet_size lowercase__ : Optional[int] = num_frames lowercase__ : Optional[int] = is_training lowercase__ : int = use_labels lowercase__ : Optional[int] = hidden_size lowercase__ : Union[str, Any] = num_hidden_layers lowercase__ : Optional[int] = num_attention_heads lowercase__ : Any = intermediate_size lowercase__ : str = hidden_act lowercase__ : List[Any] = hidden_dropout_prob lowercase__ : str = attention_probs_dropout_prob lowercase__ : Union[str, Any] = type_sequence_label_size lowercase__ : List[Any] = initializer_range lowercase__ : str = mask_ratio lowercase__ : Optional[Any] = scope # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame lowercase__ : Optional[Any] = (image_size // patch_size) ** 2 lowercase__ : str = (num_frames // tubelet_size) * self.num_patches_per_frame # use this variable to define bool_masked_pos lowercase__ : str = int(mask_ratio * self.seq_length ) def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : int = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowercase__ : int = None if self.use_labels: lowercase__ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ : Dict = self.get_config() return config, pixel_values, labels def _UpperCAmelCase ( self ) -> Tuple: return VideoMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , tubelet_size=self.tubelet_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 , is_decoder=a , initializer_range=self.initializer_range , ) def _UpperCAmelCase ( self , a , a , a ) -> Optional[int]: lowercase__ : Dict = VideoMAEModel(config=a ) model.to(a ) model.eval() lowercase__ : Tuple = model(a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCAmelCase ( self , a , a , a ) -> Union[str, Any]: lowercase__ : str = VideoMAEForPreTraining(a ) model.to(a ) model.eval() # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch lowercase__ : Any = torch.ones((self.num_masks,) ) lowercase__ : str = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0 ) )] ) lowercase__ : Optional[int] = mask.expand(self.batch_size , -1 ).bool() lowercase__ : str = model(a , a ) # model only returns predictions for masked patches lowercase__ : str = mask.sum().item() lowercase__ : int = 3 * self.tubelet_size * self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_masked_patches, decoder_num_labels) ) def _UpperCAmelCase ( self ) -> str: lowercase__ : Dict = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ : Union[str, Any] = config_and_inputs lowercase__ : List[str] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _a , _a , unittest.TestCase): lowerCamelCase__ : Tuple = ( (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else () ) lowerCamelCase__ : Optional[int] = ( {"feature-extraction": VideoMAEModel, "video-classification": VideoMAEForVideoClassification} if is_torch_available() else {} ) lowerCamelCase__ : Any = False lowerCamelCase__ : Any = False lowerCamelCase__ : Union[str, Any] = False lowerCamelCase__ : str = False def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : Optional[Any] = VideoMAEModelTester(self ) lowercase__ : Optional[Any] = ConfigTester(self , config_class=a , has_text_modality=a , hidden_size=3_7 ) def _UpperCAmelCase ( self , a , a , a=False ) -> Optional[int]: lowercase__ : Union[str, Any] = copy.deepcopy(a ) if model_class == VideoMAEForPreTraining: # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch lowercase__ : Optional[Any] = torch.ones((self.model_tester.num_masks,) ) lowercase__ : Any = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0 ) )] ) lowercase__ : Any = mask.expand(self.model_tester.batch_size , -1 ).bool() lowercase__ : Union[str, Any] = bool_masked_pos.to(a ) if return_labels: if model_class in [ *get_values(a ), ]: lowercase__ : Dict = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=a ) return inputs_dict def _UpperCAmelCase ( self ) -> Tuple: self.config_tester.run_common_tests() @unittest.skip(reason='VideoMAE does not use inputs_embeds' ) def _UpperCAmelCase ( self ) -> Dict: pass def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ , lowercase__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : int = model_class(a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase__ : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a , nn.Linear ) ) def _UpperCAmelCase ( self ) -> Optional[int]: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : List[str] = model_class(a ) lowercase__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : Optional[Any] = [*signature.parameters.keys()] lowercase__ : int = ['pixel_values'] self.assertListEqual(arg_names[:1] , a ) def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*a ) @slow def _UpperCAmelCase ( self ) -> str: for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase__ : List[Any] = VideoMAEModel.from_pretrained(a ) self.assertIsNotNone(a ) def _UpperCAmelCase ( self ) -> Optional[Any]: if not self.has_attentions: pass else: lowercase__ , lowercase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : str = True for model_class in self.all_model_classes: lowercase__ : Union[str, Any] = self.model_tester.seq_length - self.model_tester.num_masks lowercase__ : Any = ( num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length ) lowercase__ : Optional[Any] = True lowercase__ : int = False lowercase__ : Any = True lowercase__ : List[str] = model_class(a ) model.to(a ) model.eval() with torch.no_grad(): lowercase__ : Optional[int] = model(**self._prepare_for_class(a , a ) ) lowercase__ : Dict = outputs.attentions self.assertEqual(len(a ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowercase__ : str = True lowercase__ : List[str] = model_class(a ) model.to(a ) model.eval() with torch.no_grad(): lowercase__ : List[Any] = model(**self._prepare_for_class(a , a ) ) lowercase__ : Optional[Any] = outputs.attentions self.assertEqual(len(a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) lowercase__ : List[str] = len(a ) # Check attention is always last and order is fine lowercase__ : Optional[int] = True lowercase__ : List[str] = True lowercase__ : int = model_class(a ) model.to(a ) model.eval() with torch.no_grad(): lowercase__ : List[str] = model(**self._prepare_for_class(a , a ) ) self.assertEqual(out_len + 1 , len(a ) ) lowercase__ : int = outputs.attentions self.assertEqual(len(a ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def _UpperCAmelCase ( self ) -> Optional[int]: def check_hidden_states_output(a , a , a ): lowercase__ : Optional[int] = model_class(a ) model.to(a ) model.eval() with torch.no_grad(): lowercase__ : Optional[Any] = model(**self._prepare_for_class(a , a ) ) lowercase__ : Optional[int] = outputs.hidden_states lowercase__ : List[Any] = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(a ) , a ) lowercase__ : Optional[Any] = self.model_tester.seq_length - self.model_tester.num_masks lowercase__ : Union[str, Any] = num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowercase__ , lowercase__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Tuple = True check_hidden_states_output(a , a , a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : Union[str, Any] = True check_hidden_states_output(a , a , a ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def _UpperCAmelCase ( self ) -> List[Any]: pass def a_ ( ): '''simple docstring''' lowercase__ : int = hf_hub_download( repo_id='hf-internal-testing/spaghetti-video' , filename='eating_spaghetti.npy' , repo_type='dataset' ) lowercase__ : str = np.load(_lowerCAmelCase ) return list(_lowerCAmelCase ) @require_torch @require_vision class UpperCAmelCase_ ( unittest.TestCase): @cached_property def _UpperCAmelCase ( self ) -> Optional[Any]: # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def _UpperCAmelCase ( self ) -> int: lowercase__ : Dict = VideoMAEForVideoClassification.from_pretrained('MCG-NJU/videomae-base-finetuned-kinetics' ).to( a ) lowercase__ : str = self.default_image_processor lowercase__ : List[str] = prepare_video() lowercase__ : int = image_processor(a , return_tensors='pt' ).to(a ) # forward pass with torch.no_grad(): lowercase__ : Union[str, Any] = model(**a ) # verify the logits lowercase__ : str = torch.Size((1, 4_0_0) ) self.assertEqual(outputs.logits.shape , a ) lowercase__ : List[Any] = torch.tensor([0.3_669, -0.0_688, -0.2_421] ).to(a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a , atol=1e-4 ) ) @slow def _UpperCAmelCase ( self ) -> List[str]: lowercase__ : Optional[int] = VideoMAEForPreTraining.from_pretrained('MCG-NJU/videomae-base-short' ).to(a ) lowercase__ : Optional[Any] = self.default_image_processor lowercase__ : List[str] = prepare_video() lowercase__ : str = image_processor(a , return_tensors='pt' ).to(a ) # add boolean mask, indicating which patches to mask lowercase__ : Union[str, Any] = hf_hub_download(repo_id='hf-internal-testing/bool-masked-pos' , filename='bool_masked_pos.pt' ) lowercase__ : str = torch.load(a ) # forward pass with torch.no_grad(): lowercase__ : List[Any] = model(**a ) # verify the logits lowercase__ : Dict = torch.Size([1, 1_4_0_8, 1_5_3_6] ) lowercase__ : List[str] = torch.tensor( [[0.7_994, 0.9_612, 0.8_508], [0.7_401, 0.8_958, 0.8_302], [0.5_862, 0.7_468, 0.7_325]] , device=a ) self.assertEqual(outputs.logits.shape , a ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , a , atol=1e-4 ) ) # verify the loss (`config.norm_pix_loss` = `True`) lowercase__ : List[Any] = torch.tensor([0.5_142] , device=a ) self.assertTrue(torch.allclose(outputs.loss , a , atol=1e-4 ) ) # verify the loss (`config.norm_pix_loss` = `False`) lowercase__ : Tuple = VideoMAEForPreTraining.from_pretrained('MCG-NJU/videomae-base-short' , norm_pix_loss=a ).to( a ) with torch.no_grad(): lowercase__ : Any = model(**a ) lowercase__ : List[Any] = torch.tensor(torch.tensor([0.6_469] ) , device=a ) self.assertTrue(torch.allclose(outputs.loss , a , atol=1e-4 ) )
645
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available _UpperCamelCase : Optional[int] = { "configuration_rag": ["RagConfig"], "retrieval_rag": ["RagRetriever"], "tokenization_rag": ["RagTokenizer"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : List[Any] = [ "RagModel", "RagPreTrainedModel", "RagSequenceForGeneration", "RagTokenForGeneration", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : str = [ "TFRagModel", "TFRagPreTrainedModel", "TFRagSequenceForGeneration", "TFRagTokenForGeneration", ] if TYPE_CHECKING: from .configuration_rag import RagConfig from .retrieval_rag import RagRetriever from .tokenization_rag import RagTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_rag import RagModel, RagPreTrainedModel, RagSequenceForGeneration, RagTokenForGeneration try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_rag import ( TFRagModel, TFRagPreTrainedModel, TFRagSequenceForGeneration, TFRagTokenForGeneration, ) else: import sys _UpperCamelCase : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
645
"""simple docstring""" import argparse import fairseq import torch from transformers import UniSpeechSatConfig, UniSpeechSatForCTC, UniSpeechSatForPreTraining, logging logging.set_verbosity_info() _UpperCamelCase : Dict = logging.get_logger(__name__) _UpperCamelCase : List[Any] = { "post_extract_proj": "feature_projection.projection", "encoder.pos_conv.0": "encoder.pos_conv_embed.conv", "self_attn.k_proj": "encoder.layers.*.attention.k_proj", "self_attn.v_proj": "encoder.layers.*.attention.v_proj", "self_attn.q_proj": "encoder.layers.*.attention.q_proj", "self_attn.out_proj": "encoder.layers.*.attention.out_proj", "self_attn_layer_norm": "encoder.layers.*.layer_norm", "fc1": "encoder.layers.*.feed_forward.intermediate_dense", "fc2": "encoder.layers.*.feed_forward.output_dense", "final_layer_norm": "encoder.layers.*.final_layer_norm", "encoder.layer_norm": "encoder.layer_norm", "encoder.layer_norm_for_extract": "layer_norm_for_extract", "w2v_model.layer_norm": "feature_projection.layer_norm", "quantizer.weight_proj": "quantizer.weight_proj", "quantizer.vars": "quantizer.codevectors", "project_q": "project_q", "final_proj": "project_hid", "w2v_encoder.proj": "lm_head", "label_embs_concat": "label_embeddings_concat", "mask_emb": "masked_spec_embed", "spk_proj": "speaker_proj", } _UpperCamelCase : List[str] = [ "lm_head", "quantizer.weight_proj", "quantizer.codevectors", "project_q", "project_hid", "label_embeddings_concat", "speaker_proj", "layer_norm_for_extract", ] def a_ ( _lowerCAmelCase : Any , _lowerCAmelCase : int , _lowerCAmelCase : Any , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Tuple ): '''simple docstring''' for attribute in key.split('.' ): lowercase__ : Dict = getattr(_lowerCAmelCase , _lowerCAmelCase ) if weight_type is not None: lowercase__ : Optional[int] = getattr(_lowerCAmelCase , _lowerCAmelCase ).shape else: lowercase__ : Optional[int] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": lowercase__ : Optional[Any] = value elif weight_type == "weight_g": lowercase__ : Dict = value elif weight_type == "weight_v": lowercase__ : List[str] = value elif weight_type == "bias": lowercase__ : Optional[Any] = value else: lowercase__ : List[str] = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def a_ ( _lowerCAmelCase : Any , _lowerCAmelCase : Optional[Any] ): '''simple docstring''' lowercase__ : Tuple = [] lowercase__ : List[str] = fairseq_model.state_dict() lowercase__ : Union[str, Any] = hf_model.unispeech_sat.feature_extractor for name, value in fairseq_dict.items(): lowercase__ : Optional[int] = False if "conv_layers" in name: load_conv_layer( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , hf_model.config.feat_extract_norm == 'group' , ) lowercase__ : Optional[Any] = True else: for key, mapped_key in MAPPING.items(): lowercase__ : List[Any] = 'unispeech_sat.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]: if "layer_norm_for_extract" in name and (".".join(name.split('.' )[:-1] ) != key): # special case since naming is very similar continue lowercase__ : int = True if "*" in mapped_key: lowercase__ : Optional[int] = name.split(_lowerCAmelCase )[0].split('.' )[-2] lowercase__ : List[str] = mapped_key.replace('*' , _lowerCAmelCase ) if "weight_g" in name: lowercase__ : List[Any] = 'weight_g' elif "weight_v" in name: lowercase__ : int = 'weight_v' elif "bias" in name: lowercase__ : Dict = 'bias' elif "weight" in name: # TODO: don't match quantizer.weight_proj lowercase__ : Union[str, Any] = 'weight' else: lowercase__ : int = None set_recursively(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) continue if not is_used: unused_weights.append(_lowerCAmelCase ) logger.warning(f"""Unused weights: {unused_weights}""" ) def a_ ( _lowerCAmelCase : List[Any] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : int , _lowerCAmelCase : Dict ): '''simple docstring''' lowercase__ : int = full_name.split('conv_layers.' )[-1] lowercase__ : int = name.split('.' ) lowercase__ : int = int(items[0] ) lowercase__ : Dict = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) lowercase__ : Union[str, Any] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) lowercase__ : Optional[int] = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.bias.data.shape} was found.""" ) lowercase__ : List[Any] = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) lowercase__ : int = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(_lowerCAmelCase ) @torch.no_grad() def a_ ( _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : List[Any]=None , _lowerCAmelCase : str=None , _lowerCAmelCase : Tuple=True ): '''simple docstring''' if config_path is not None: lowercase__ : Any = UniSpeechSatConfig.from_pretrained(_lowerCAmelCase ) else: lowercase__ : Any = UniSpeechSatConfig() lowercase__ : Union[str, Any] = '' if is_finetuned: lowercase__ : Optional[Any] = UniSpeechSatForCTC(_lowerCAmelCase ) else: lowercase__ : List[Any] = UniSpeechSatForPreTraining(_lowerCAmelCase ) lowercase__ , lowercase__ , lowercase__ : int = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} ) lowercase__ : Union[str, Any] = model[0].eval() recursively_load_weights(_lowerCAmelCase , _lowerCAmelCase ) hf_wavavec.save_pretrained(_lowerCAmelCase ) if __name__ == "__main__": _UpperCamelCase : Tuple = argparse.ArgumentParser() parser.add_argument("--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model.") parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to fairseq checkpoint") parser.add_argument("--dict_path", default=None, type=str, help="Path to dict of fine-tuned model") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--not_finetuned", action="store_true", help="Whether the model to convert is a fine-tuned model or not" ) _UpperCamelCase : str = parser.parse_args() convert_unispeech_sat_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
645
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _UpperCamelCase : str = { "configuration_gpt_neo": ["GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoConfig", "GPTNeoOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : Tuple = [ "GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoForCausalLM", "GPTNeoForQuestionAnswering", "GPTNeoForSequenceClassification", "GPTNeoForTokenClassification", "GPTNeoModel", "GPTNeoPreTrainedModel", "load_tf_weights_in_gpt_neo", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : Dict = [ "FlaxGPTNeoForCausalLM", "FlaxGPTNeoModel", "FlaxGPTNeoPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys _UpperCamelCase : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
645
"""simple docstring""" import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class UpperCAmelCase_ : def __init__( self , a , a=1_3 , a=3_2 , a=2 , a=3 , a=1_6 , a=[1, 2, 1] , a=[2, 2, 4] , a=2 , a=2.0 , a=True , a=0.0 , a=0.0 , a=0.1 , a="gelu" , a=False , a=True , a=0.02 , a=1e-5 , a=True , a=None , a=True , a=1_0 , a=8 , a=["stage1", "stage2", "stage3"] , a=[1, 2, 3] , ) -> int: lowercase__ : int = parent lowercase__ : Union[str, Any] = batch_size lowercase__ : Dict = image_size lowercase__ : str = patch_size lowercase__ : Optional[Any] = num_channels lowercase__ : List[str] = embed_dim lowercase__ : Any = depths lowercase__ : Dict = num_heads lowercase__ : List[str] = window_size lowercase__ : int = mlp_ratio lowercase__ : Tuple = qkv_bias lowercase__ : Union[str, Any] = hidden_dropout_prob lowercase__ : str = attention_probs_dropout_prob lowercase__ : Tuple = drop_path_rate lowercase__ : List[str] = hidden_act lowercase__ : Optional[Any] = use_absolute_embeddings lowercase__ : Optional[Any] = patch_norm lowercase__ : Any = layer_norm_eps lowercase__ : List[Any] = initializer_range lowercase__ : List[str] = is_training lowercase__ : int = scope lowercase__ : Optional[int] = use_labels lowercase__ : List[Any] = type_sequence_label_size lowercase__ : List[str] = encoder_stride lowercase__ : Optional[Any] = out_features lowercase__ : Dict = out_indices def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ : Optional[Any] = None if self.use_labels: lowercase__ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ : Tuple = self.get_config() return config, pixel_values, labels def _UpperCAmelCase ( self ) -> Union[str, Any]: return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _UpperCAmelCase ( self , a , a , a ) -> Dict: lowercase__ : Tuple = MaskFormerSwinModel(config=a ) model.to(a ) model.eval() lowercase__ : str = model(a ) lowercase__ : str = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) lowercase__ : Dict = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _UpperCAmelCase ( self , a , a , a ) -> Optional[int]: lowercase__ : List[Any] = MaskFormerSwinBackbone(config=a ) model.to(a ) model.eval() lowercase__ : int = model(a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(a ): lowercase__ : Dict = ['stem'] lowercase__ : List[str] = MaskFormerSwinBackbone(config=a ) def _UpperCAmelCase ( self ) -> str: lowercase__ : int = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ : Tuple = config_and_inputs lowercase__ : Union[str, Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _a , _a , unittest.TestCase): lowerCamelCase__ : Optional[int] = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) lowerCamelCase__ : List[str] = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} lowerCamelCase__ : str = False lowerCamelCase__ : Dict = False lowerCamelCase__ : Any = False lowerCamelCase__ : Dict = False lowerCamelCase__ : int = False def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : str = MaskFormerSwinModelTester(self ) lowercase__ : Tuple = ConfigTester(self , config_class=a , embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( '`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with' ' `nn.DataParallel`' ) ) def _UpperCAmelCase ( self ) -> Optional[int]: pass def _UpperCAmelCase ( self ) -> Tuple: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _UpperCAmelCase ( self ) -> str: return def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*a ) @unittest.skip('Swin does not use inputs_embeds' ) def _UpperCAmelCase ( self ) -> Tuple: pass @unittest.skip('Swin does not support feedforward chunking' ) def _UpperCAmelCase ( self ) -> Tuple: pass def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ , lowercase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : List[str] = model_class(a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase__ : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a , nn.Linear ) ) def _UpperCAmelCase ( self ) -> str: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Any = model_class(a ) lowercase__ : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : Optional[Any] = [*signature.parameters.keys()] lowercase__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a ) @unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions' ) def _UpperCAmelCase ( self ) -> List[Any]: pass @unittest.skip(reason='MaskFormerSwin is only used as an internal backbone' ) def _UpperCAmelCase ( self ) -> int: pass def _UpperCAmelCase ( self , a , a , a , a ) -> Tuple: lowercase__ : Dict = model_class(a ) model.to(a ) model.eval() with torch.no_grad(): lowercase__ : str = model(**self._prepare_for_class(a , a ) ) lowercase__ : List[Any] = outputs.hidden_states lowercase__ : str = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(a ) , a ) # Swin has a different seq_length lowercase__ : Dict = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ : Tuple = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ , lowercase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: lowercase__ : List[str] = True self.check_hidden_states_output(a , a , a , a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : List[str] = True self.check_hidden_states_output(a , a , a , a ) def _UpperCAmelCase ( self ) -> Optional[int]: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Union[str, Any] = 3 lowercase__ : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) lowercase__ : Tuple = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ : Optional[int] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) lowercase__ : List[str] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: lowercase__ : List[str] = True self.check_hidden_states_output(a , a , a , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : int = True self.check_hidden_states_output(a , a , a , (padded_height, padded_width) ) @unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints' ) def _UpperCAmelCase ( self ) -> Optional[int]: pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def _UpperCAmelCase ( self ) -> Any: pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def _UpperCAmelCase ( self ) -> Any: pass def _UpperCAmelCase ( self ) -> Any: lowercase__ , lowercase__ : str = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(a ): lowercase__ : Union[str, Any] = 0 return t def check_equivalence(a , a , a , a={} ): with torch.no_grad(): lowercase__ : Optional[Any] = model(**a , return_dict=a , **a ) lowercase__ : Optional[int] = model(**a , return_dict=a , **a ).to_tuple() def recursive_check(a , a ): if isinstance(a , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a , a ): recursive_check(a , a ) elif isinstance(a , a ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(a , a ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(a ) , set_nan_tensor_to_zero(a ) , atol=1e-5 ) , msg=( 'Tuple and dict output are not equal. Difference:' f""" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:""" f""" {torch.isnan(a ).any()} and `inf`: {torch.isinf(a )}. Dict has""" f""" `nan`: {torch.isnan(a ).any()} and `inf`: {torch.isinf(a )}.""" ) , ) recursive_check(a , a ) for model_class in self.all_model_classes: lowercase__ : Any = model_class(a ) model.to(a ) model.eval() lowercase__ : Tuple = self._prepare_for_class(a , a ) lowercase__ : Optional[Any] = self._prepare_for_class(a , a ) check_equivalence(a , a , a ) lowercase__ : Any = self._prepare_for_class(a , a , return_labels=a ) lowercase__ : List[Any] = self._prepare_for_class(a , a , return_labels=a ) check_equivalence(a , a , a ) lowercase__ : Any = self._prepare_for_class(a , a ) lowercase__ : int = self._prepare_for_class(a , a ) check_equivalence(a , a , a , {'output_hidden_states': True} ) lowercase__ : Dict = self._prepare_for_class(a , a , return_labels=a ) lowercase__ : Optional[int] = self._prepare_for_class(a , a , return_labels=a ) check_equivalence(a , a , a , {'output_hidden_states': True} ) @require_torch class UpperCAmelCase_ ( unittest.TestCase , _a): lowerCamelCase__ : Dict = (MaskFormerSwinBackbone,) if is_torch_available() else () lowerCamelCase__ : Optional[int] = MaskFormerSwinConfig def _UpperCAmelCase ( self ) -> Dict: lowercase__ : Optional[int] = MaskFormerSwinModelTester(self ) def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : int = inputs_dict['pixel_values'].shape[0] for backbone_class in self.all_model_classes: lowercase__ : Optional[Any] = backbone_class(a ) backbone.to(a ) backbone.eval() lowercase__ : Union[str, Any] = backbone(**a ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , a ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True lowercase__ : List[str] = backbone(**a , output_hidden_states=a ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) lowercase__ , lowercase__ , lowercase__ : int = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: lowercase__ : List[Any] = backbone(**a , output_attentions=a ) self.assertIsNotNone(outputs.attentions )
645
1
"""simple docstring""" import os import shutil import tempfile import unittest import numpy as np from transformers import AutoTokenizer, BarkProcessor from transformers.testing_utils import require_torch, slow @require_torch class UpperCAmelCase_ ( unittest.TestCase): def _UpperCAmelCase ( self ) -> List[str]: lowercase__ : Optional[Any] = 'ylacombe/bark-small' lowercase__ : Optional[int] = tempfile.mkdtemp() lowercase__ : int = 'en_speaker_1' lowercase__ : Union[str, Any] = 'This is a test string' lowercase__ : Any = 'speaker_embeddings_path.json' lowercase__ : str = 'speaker_embeddings' def _UpperCAmelCase ( self , **a ) -> List[Any]: return AutoTokenizer.from_pretrained(self.checkpoint , **a ) def _UpperCAmelCase ( self ) -> Optional[Any]: shutil.rmtree(self.tmpdirname ) def _UpperCAmelCase ( self ) -> str: lowercase__ : List[str] = self.get_tokenizer() lowercase__ : Dict = BarkProcessor(tokenizer=a ) processor.save_pretrained(self.tmpdirname ) lowercase__ : List[Any] = BarkProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) @slow def _UpperCAmelCase ( self ) -> Dict: lowercase__ : str = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) processor.save_pretrained( self.tmpdirname , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , speaker_embeddings_directory=self.speaker_embeddings_directory , ) lowercase__ : Dict = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) lowercase__ : int = BarkProcessor.from_pretrained( self.tmpdirname , self.speaker_embeddings_dict_path , bos_token='(BOS)' , eos_token='(EOS)' , ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) def _UpperCAmelCase ( self ) -> Any: lowercase__ : List[Any] = BarkProcessor.from_pretrained( pretrained_processor_name_or_path=self.checkpoint , speaker_embeddings_dict_path=self.speaker_embeddings_dict_path , ) lowercase__ : List[Any] = 3_5 lowercase__ : Tuple = 2 lowercase__ : Dict = 8 lowercase__ : Dict = { 'semantic_prompt': np.ones(a ), 'coarse_prompt': np.ones((nb_codebooks_coarse, seq_len) ), 'fine_prompt': np.ones((nb_codebooks_total, seq_len) ), } # test providing already loaded voice_preset lowercase__ : int = processor(text=self.input_string , voice_preset=a ) lowercase__ : Any = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a , np.array([] ) ).tolist() ) # test loading voice preset from npz file lowercase__ : Dict = os.path.join(self.tmpdirname , 'file.npz' ) np.savez(a , **a ) lowercase__ : Any = processor(text=self.input_string , voice_preset=a ) lowercase__ : Optional[Any] = inputs['history_prompt'] for key in voice_preset: self.assertListEqual(voice_preset[key].tolist() , processed_voice_preset.get(a , np.array([] ) ).tolist() ) # test loading voice preset from the hub lowercase__ : Tuple = processor(text=self.input_string , voice_preset=self.voice_preset ) def _UpperCAmelCase ( self ) -> int: lowercase__ : int = self.get_tokenizer() lowercase__ : Union[str, Any] = BarkProcessor(tokenizer=a ) lowercase__ : Any = processor(text=self.input_string ) lowercase__ : Union[str, Any] = tokenizer( self.input_string , padding='max_length' , max_length=2_5_6 , add_special_tokens=a , return_attention_mask=a , return_token_type_ids=a , ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key].squeeze().tolist() )
645
"""simple docstring""" import math def a_ ( _lowerCAmelCase : int = 100 ): '''simple docstring''' lowercase__ : Union[str, Any] = sum(i * i for i in range(1 , n + 1 ) ) lowercase__ : str = int(math.pow(sum(range(1 , n + 1 ) ) , 2 ) ) return square_of_sum - sum_of_squares if __name__ == "__main__": print(f'''{solution() = }''')
645
1
"""simple docstring""" import logging import random import ray from transformers import RagConfig, RagRetriever, RagTokenizer from transformers.models.rag.retrieval_rag import CustomHFIndex _UpperCamelCase : Optional[Any] = logging.getLogger(__name__) class UpperCAmelCase_ : def __init__( self ) -> List[str]: lowercase__ : List[Any] = False def _UpperCAmelCase ( self , a , a , a , a ) -> List[str]: if not self.initialized: lowercase__ : str = RagRetriever( a , question_encoder_tokenizer=a , generator_tokenizer=a , index=a , init_retrieval=a , ) lowercase__ : int = True def _UpperCAmelCase ( self ) -> Optional[Any]: self.retriever.index.init_index() def _UpperCAmelCase ( self , a , a ) -> List[str]: lowercase__ , lowercase__ : Union[str, Any] = self.retriever._main_retrieve(a , a ) return doc_ids, retrieved_doc_embeds class UpperCAmelCase_ ( _a): def __init__( self , a , a , a , a , a=None ) -> Dict: 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 , ) lowercase__ : int = 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 ) -> Union[str, Any]: 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 , a , a ) -> Optional[int]: if len(self.retrieval_workers ) > 0: # Select a random retrieval actor. lowercase__ : List[str] = self.retrieval_workers[random.randint(0 , len(self.retrieval_workers ) - 1 )] lowercase__ , lowercase__ : int = ray.get(random_worker.retrieve.remote(a , a ) ) else: lowercase__ , lowercase__ : List[str] = self._main_retrieve(a , a ) return retrieved_doc_embeds, doc_ids, self.index.get_doc_dicts(a ) @classmethod def _UpperCAmelCase ( cls , a , a=None , **a ) -> Optional[int]: return super(a , cls ).get_tokenizers(a , a , **a ) @classmethod def _UpperCAmelCase ( cls , a , a , a=None , **a ) -> int: lowercase__ : List[str] = kwargs.pop('config' , a ) or RagConfig.from_pretrained(a , **a ) lowercase__ : Any = RagTokenizer.from_pretrained(a , config=a ) lowercase__ : List[str] = rag_tokenizer.question_encoder lowercase__ : str = rag_tokenizer.generator if indexed_dataset is not None: lowercase__ : Tuple = 'custom' lowercase__ : List[Any] = CustomHFIndex(config.retrieval_vector_size , a ) else: lowercase__ : List[Any] = cls._build_index(a ) return cls( a , question_encoder_tokenizer=a , generator_tokenizer=a , retrieval_workers=a , index=a , )
645
"""simple docstring""" import gc import unittest from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline from diffusers.utils import is_flax_available, load_image, slow from diffusers.utils.testing_utils import require_flax if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard @slow @require_flax class UpperCAmelCase_ ( unittest.TestCase): def _UpperCAmelCase ( self ) -> List[Any]: # clean up the VRAM after each test super().tearDown() gc.collect() def _UpperCAmelCase ( self ) -> Tuple: lowercase__ , lowercase__ : str = FlaxControlNetModel.from_pretrained( 'lllyasviel/sd-controlnet-canny' , from_pt=a , dtype=jnp.bfloataa ) lowercase__ , lowercase__ : List[str] = FlaxStableDiffusionControlNetPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , controlnet=a , from_pt=a , dtype=jnp.bfloataa ) lowercase__ : List[Any] = controlnet_params lowercase__ : int = 'bird' lowercase__ : List[Any] = jax.device_count() lowercase__ : Dict = pipe.prepare_text_inputs([prompts] * num_samples ) lowercase__ : Union[str, Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png' ) lowercase__ : Optional[int] = pipe.prepare_image_inputs([canny_image] * num_samples ) lowercase__ : List[Any] = jax.random.PRNGKey(0 ) lowercase__ : Tuple = jax.random.split(a , jax.device_count() ) lowercase__ : str = replicate(a ) lowercase__ : List[str] = shard(a ) lowercase__ : Dict = shard(a ) lowercase__ : List[Any] = pipe( prompt_ids=a , image=a , params=a , prng_seed=a , num_inference_steps=5_0 , jit=a , ).images assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3) lowercase__ : Any = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) lowercase__ : Tuple = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] lowercase__ : int = jnp.asarray(jax.device_get(image_slice.flatten() ) ) lowercase__ : Optional[Any] = jnp.array( [0.167_969, 0.116_699, 0.081_543, 0.154_297, 0.132_812, 0.108_887, 0.169_922, 0.169_922, 0.205_078] ) print(f"""output_slice: {output_slice}""" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2 def _UpperCAmelCase ( self ) -> List[str]: lowercase__ , lowercase__ : int = FlaxControlNetModel.from_pretrained( 'lllyasviel/sd-controlnet-openpose' , from_pt=a , dtype=jnp.bfloataa ) lowercase__ , lowercase__ : Optional[Any] = FlaxStableDiffusionControlNetPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , controlnet=a , from_pt=a , dtype=jnp.bfloataa ) lowercase__ : Optional[Any] = controlnet_params lowercase__ : List[Any] = 'Chef in the kitchen' lowercase__ : List[str] = jax.device_count() lowercase__ : Dict = pipe.prepare_text_inputs([prompts] * num_samples ) lowercase__ : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png' ) lowercase__ : Optional[int] = pipe.prepare_image_inputs([pose_image] * num_samples ) lowercase__ : List[str] = jax.random.PRNGKey(0 ) lowercase__ : str = jax.random.split(a , jax.device_count() ) lowercase__ : Optional[Any] = replicate(a ) lowercase__ : Optional[Any] = shard(a ) lowercase__ : List[Any] = shard(a ) lowercase__ : List[Any] = pipe( prompt_ids=a , image=a , params=a , prng_seed=a , num_inference_steps=5_0 , jit=a , ).images assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3) lowercase__ : Union[str, Any] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] ) lowercase__ : List[str] = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] lowercase__ : Optional[int] = jnp.asarray(jax.device_get(image_slice.flatten() ) ) lowercase__ : str = jnp.array( [[0.271_484, 0.261_719, 0.275_391, 0.277_344, 0.279_297, 0.291_016, 0.294_922, 0.302_734, 0.302_734]] ) print(f"""output_slice: {output_slice}""" ) assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
645
1
"""simple docstring""" from ..utils import DummyObject, requires_backends class UpperCAmelCase_ ( metaclass=_a): lowerCamelCase__ : Optional[int] = ["speech"] def __init__( self , *a , **a ) -> Dict: requires_backends(self , ['speech'] ) class UpperCAmelCase_ ( metaclass=_a): lowerCamelCase__ : Any = ["speech"] def __init__( self , *a , **a ) -> int: requires_backends(self , ['speech'] )
645
"""simple docstring""" from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
645
1
"""simple docstring""" from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record _UpperCamelCase : Any = "\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n" _UpperCamelCase : Any = "\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n" _UpperCamelCase : Any = "\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for 'record': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'prediction_text': the predicted answer text\n - for 'multirc': list of question-answer dictionaries with the following keys:\n - 'idx': index of the question-answer pair as specified by the dataset\n - 'prediction': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for 'record': list of question-answers dictionaries with the following keys:\n - 'idx': index of the question as specified by the dataset\n - 'answers': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for 'record':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1': F1 score\n - for 'multirc':\n - 'exact_match': Exact match between answer and gold answer\n - 'f1_m': Per-question macro-F1 score\n - 'f1_a': Average F1 score over all answers\n - for 'axb':\n 'matthews_correlation': Matthew Correlation\n - for 'cb':\n - 'accuracy': Accuracy\n - 'f1': F1 score\n - for all others:\n - 'accuracy': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'copa') # any of [\"copa\", \"rte\", \"wic\", \"wsc\", \"wsc.fixed\", \"boolq\", \"axg\"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'cb')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'record')\n >>> predictions = [{'idx': {'passage': 0, 'query': 0}, 'prediction_text': 'answer'}]\n >>> references = [{'idx': {'passage': 0, 'query': 0}, 'answers': ['answer', 'another_answer']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'multirc')\n >>> predictions = [{'idx': {'answer': 0, 'paragraph': 0, 'question': 0}, 'prediction': 0}, {'idx': {'answer': 1, 'paragraph': 2, 'question': 3}, 'prediction': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'exact_match': 1.0, 'f1_m': 1.0, 'f1_a': 1.0}\n\n >>> super_glue_metric = datasets.load_metric('super_glue', 'axb')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'matthews_correlation': 1.0}\n" def a_ ( _lowerCAmelCase : Dict , _lowerCAmelCase : Optional[Any] ): '''simple docstring''' return float((preds == labels).mean() ) def a_ ( _lowerCAmelCase : Dict , _lowerCAmelCase : str , _lowerCAmelCase : Union[str, Any]="binary" ): '''simple docstring''' lowercase__ : Any = simple_accuracy(_lowerCAmelCase , _lowerCAmelCase ) lowercase__ : str = float(fa_score(y_true=_lowerCAmelCase , y_pred=_lowerCAmelCase , average=_lowerCAmelCase ) ) return { "accuracy": acc, "f1": fa, } def a_ ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Dict ): '''simple docstring''' lowercase__ : List[Any] = {} for id_pred, label in zip(_lowerCAmelCase , _lowerCAmelCase ): lowercase__ : str = f"""{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}""" lowercase__ : Optional[Any] = id_pred['prediction'] if question_id in question_map: question_map[question_id].append((pred, label) ) else: lowercase__ : Optional[Any] = [(pred, label)] lowercase__ , lowercase__ : List[Any] = [], [] for question, preds_labels in question_map.items(): lowercase__ , lowercase__ : Dict = zip(*_lowerCAmelCase ) lowercase__ : Optional[Any] = fa_score(y_true=_lowerCAmelCase , y_pred=_lowerCAmelCase , average='macro' ) fas.append(_lowerCAmelCase ) lowercase__ : Any = int(sum(pred == label for pred, label in preds_labels ) == len(_lowerCAmelCase ) ) ems.append(_lowerCAmelCase ) lowercase__ : Union[str, Any] = float(sum(_lowerCAmelCase ) / len(_lowerCAmelCase ) ) lowercase__ : Dict = sum(_lowerCAmelCase ) / len(_lowerCAmelCase ) lowercase__ : Tuple = float(fa_score(y_true=_lowerCAmelCase , y_pred=[id_pred['prediction'] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION) class UpperCAmelCase_ ( datasets.Metric): def _UpperCAmelCase ( self ) -> Union[str, Any]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( 'You should supply a configuration name selected in ' '["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format='numpy' if not self.config_name == 'record' and not self.config_name == 'multirc' else None , ) def _UpperCAmelCase ( self ) -> Dict: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value('int64' ), "query": datasets.Value('int64' ), }, "prediction_text": datasets.Value('string' ), }, "references": { "idx": { "passage": datasets.Value('int64' ), "query": datasets.Value('int64' ), }, "answers": datasets.Sequence(datasets.Value('string' ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value('int64' ), "paragraph": datasets.Value('int64' ), "question": datasets.Value('int64' ), }, "prediction": datasets.Value('int64' ), }, "references": datasets.Value('int64' ), } else: return { "predictions": datasets.Value('int64' ), "references": datasets.Value('int64' ), } def _UpperCAmelCase ( self , a , a ) -> Union[str, Any]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(a , a )} elif self.config_name == "cb": return acc_and_fa(a , a , fa_avg='macro' ) elif self.config_name == "record": lowercase__ : str = [ { 'qas': [ {'id': ref['idx']['query'], 'answers': [{'text': ans} for ans in ref['answers']]} for ref in references ] } ] lowercase__ : str = {pred['idx']['query']: pred['prediction_text'] for pred in predictions} return evaluate_record(a , a )[0] elif self.config_name == "multirc": return evaluate_multirc(a , a ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(a , a )} else: raise KeyError( 'You should supply a configuration name selected in ' '["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]' )
645
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class UpperCAmelCase_ ( unittest.TestCase): @slow def _UpperCAmelCase ( self ) -> str: lowercase__ : Optional[Any] = AutoImageProcessor.from_pretrained('microsoft/dit-base-finetuned-rvlcdip' ) lowercase__ : Union[str, Any] = AutoModelForImageClassification.from_pretrained('microsoft/dit-base-finetuned-rvlcdip' ) model.to(a ) from datasets import load_dataset lowercase__ : str = load_dataset('nielsr/rvlcdip-demo' ) lowercase__ : Tuple = dataset['train'][0]['image'].convert('RGB' ) lowercase__ : int = image_processor(a , return_tensors='pt' ).to(a ) # forward pass with torch.no_grad(): lowercase__ : List[str] = model(**a ) lowercase__ : List[Any] = outputs.logits lowercase__ : Union[str, Any] = torch.Size((1, 1_6) ) self.assertEqual(logits.shape , a ) lowercase__ : Tuple = torch.tensor( [-0.4_158, -0.4_092, -0.4_347] , device=a , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , a , atol=1e-4 ) )
645
1
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _UpperCamelCase : str = logging.get_logger(__name__) _UpperCamelCase : List[Any] = { "caidas/swin2sr-classicalsr-x2-64": ( "https://huggingface.co/caidas/swin2sr-classicalsr-x2-64/resolve/main/config.json" ), } class UpperCAmelCase_ ( _a): lowerCamelCase__ : Dict = "swin2sr" lowerCamelCase__ : Any = { "hidden_size": "embed_dim", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self , a=6_4 , a=1 , a=3 , a=1_8_0 , a=[6, 6, 6, 6, 6, 6] , a=[6, 6, 6, 6, 6, 6] , a=8 , a=2.0 , a=True , a=0.0 , a=0.0 , a=0.1 , a="gelu" , a=False , a=0.02 , a=1e-5 , a=2 , a=1.0 , a="1conv" , a="pixelshuffle" , **a , ) -> Optional[Any]: super().__init__(**a ) lowercase__ : str = image_size lowercase__ : Tuple = patch_size lowercase__ : List[Any] = num_channels lowercase__ : Tuple = embed_dim lowercase__ : int = depths lowercase__ : int = len(a ) lowercase__ : Dict = num_heads lowercase__ : List[str] = window_size lowercase__ : Dict = mlp_ratio lowercase__ : List[Any] = qkv_bias lowercase__ : Dict = hidden_dropout_prob lowercase__ : str = attention_probs_dropout_prob lowercase__ : Optional[int] = drop_path_rate lowercase__ : int = hidden_act lowercase__ : Any = use_absolute_embeddings lowercase__ : Optional[Any] = layer_norm_eps lowercase__ : str = initializer_range lowercase__ : List[Any] = upscale lowercase__ : List[Any] = img_range lowercase__ : str = resi_connection lowercase__ : Any = upsampler
645
"""simple docstring""" import hashlib import unittest from transformers import MODEL_FOR_DEPTH_ESTIMATION_MAPPING, is_torch_available, is_vision_available from transformers.pipelines import DepthEstimationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_timm, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image else: class UpperCAmelCase_ : @staticmethod def _UpperCAmelCase ( *a , **a ) -> int: pass def a_ ( _lowerCAmelCase : Image ): '''simple docstring''' lowercase__ : List[str] = hashlib.mda(image.tobytes() ) return m.hexdigest() @is_pipeline_test @require_vision @require_timm @require_torch class UpperCAmelCase_ ( unittest.TestCase): lowerCamelCase__ : Union[str, Any] = MODEL_FOR_DEPTH_ESTIMATION_MAPPING def _UpperCAmelCase ( self , a , a , a ) -> Dict: lowercase__ : Union[str, Any] = DepthEstimationPipeline(model=a , image_processor=a ) return depth_estimator, [ "./tests/fixtures/tests_samples/COCO/000000039769.png", "./tests/fixtures/tests_samples/COCO/000000039769.png", ] def _UpperCAmelCase ( self , a , a ) -> Optional[int]: lowercase__ : Tuple = depth_estimator('./tests/fixtures/tests_samples/COCO/000000039769.png' ) self.assertEqual({'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )} , a ) import datasets lowercase__ : Tuple = datasets.load_dataset('hf-internal-testing/fixtures_image_utils' , 'image' , split='test' ) lowercase__ : List[Any] = depth_estimator( [ Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ), 'http://images.cocodataset.org/val2017/000000039769.jpg', # RGBA dataset[0]['file'], # LA dataset[1]['file'], # L dataset[2]['file'], ] ) self.assertEqual( [ {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, {'predicted_depth': ANY(torch.Tensor ), 'depth': ANY(Image.Image )}, ] , a , ) @require_tf @unittest.skip('Depth estimation is not implemented in TF' ) def _UpperCAmelCase ( self ) -> Optional[int]: pass @slow @require_torch def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : Tuple = 'Intel/dpt-large' lowercase__ : Optional[int] = pipeline('depth-estimation' , model=a ) lowercase__ : List[Any] = depth_estimator('http://images.cocodataset.org/val2017/000000039769.jpg' ) lowercase__ : Optional[Any] = hashimage(outputs['depth'] ) # This seems flaky. # self.assertEqual(outputs["depth"], "1a39394e282e9f3b0741a90b9f108977") self.assertEqual(nested_simplify(outputs['predicted_depth'].max().item() ) , 29.304 ) self.assertEqual(nested_simplify(outputs['predicted_depth'].min().item() ) , 2.662 ) @require_torch def _UpperCAmelCase ( self ) -> Optional[int]: # This is highly irregular to have no small tests. self.skipTest('There is not hf-internal-testing tiny model for either GLPN nor DPT' )
645
1
"""simple docstring""" from __future__ import annotations def a_ ( _lowerCAmelCase : list ): '''simple docstring''' if len(_lowerCAmelCase ) == 0: return [] lowercase__ , lowercase__ : List[str] = min(_lowerCAmelCase ), max(_lowerCAmelCase ) lowercase__ : Any = int(max_value - min_value ) + 1 lowercase__ : list[list] = [[] for _ in range(_lowerCAmelCase )] for i in my_list: buckets[int(i - min_value )].append(_lowerCAmelCase ) return [v for bucket in buckets for v in sorted(_lowerCAmelCase )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
645
"""simple docstring""" import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class UpperCAmelCase_ ( _a): def __init__( self ) -> Any: lowercase__ : Tuple = [] def _UpperCAmelCase ( self , a , a , a , **a ) -> Any: self.events.append('on_init_end' ) def _UpperCAmelCase ( self , a , a , a , **a ) -> Optional[int]: self.events.append('on_train_begin' ) def _UpperCAmelCase ( self , a , a , a , **a ) -> List[str]: self.events.append('on_train_end' ) def _UpperCAmelCase ( self , a , a , a , **a ) -> int: self.events.append('on_epoch_begin' ) def _UpperCAmelCase ( self , a , a , a , **a ) -> Optional[Any]: self.events.append('on_epoch_end' ) def _UpperCAmelCase ( self , a , a , a , **a ) -> int: self.events.append('on_step_begin' ) def _UpperCAmelCase ( self , a , a , a , **a ) -> str: self.events.append('on_step_end' ) def _UpperCAmelCase ( self , a , a , a , **a ) -> int: self.events.append('on_evaluate' ) def _UpperCAmelCase ( self , a , a , a , **a ) -> Tuple: self.events.append('on_predict' ) def _UpperCAmelCase ( self , a , a , a , **a ) -> Union[str, Any]: self.events.append('on_save' ) def _UpperCAmelCase ( self , a , a , a , **a ) -> List[str]: self.events.append('on_log' ) def _UpperCAmelCase ( self , a , a , a , **a ) -> Any: self.events.append('on_prediction_step' ) @require_torch class UpperCAmelCase_ ( unittest.TestCase): def _UpperCAmelCase ( self ) -> str: lowercase__ : str = tempfile.mkdtemp() def _UpperCAmelCase ( self ) -> Dict: shutil.rmtree(self.output_dir ) def _UpperCAmelCase ( self , a=0 , a=0 , a=6_4 , a=6_4 , a=None , a=False , **a ) -> int: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. lowercase__ : str = RegressionDataset(length=a ) lowercase__ : Any = RegressionDataset(length=a ) lowercase__ : Optional[Any] = RegressionModelConfig(a=a , b=a ) lowercase__ : Union[str, Any] = RegressionPreTrainedModel(a ) lowercase__ : Tuple = TrainingArguments(self.output_dir , disable_tqdm=a , report_to=[] , **a ) return Trainer( a , a , train_dataset=a , eval_dataset=a , callbacks=a , ) def _UpperCAmelCase ( self , a , a ) -> Union[str, Any]: self.assertEqual(len(a ) , len(a ) ) # Order doesn't matter lowercase__ : Optional[int] = sorted(a , key=lambda a : cb.__name__ if isinstance(a , a ) else cb.__class__.__name__ ) lowercase__ : Tuple = sorted(a , key=lambda a : cb.__name__ if isinstance(a , a ) else cb.__class__.__name__ ) for cba, cba in zip(a , a ): if isinstance(a , a ) and isinstance(a , a ): self.assertEqual(a , a ) elif isinstance(a , a ) and not isinstance(a , a ): self.assertEqual(a , cba.__class__ ) elif not isinstance(a , a ) and isinstance(a , a ): self.assertEqual(cba.__class__ , a ) else: self.assertEqual(a , a ) def _UpperCAmelCase ( self , a ) -> Optional[Any]: lowercase__ : Dict = ['on_init_end', 'on_train_begin'] lowercase__ : List[Any] = 0 lowercase__ : Optional[int] = len(trainer.get_eval_dataloader() ) lowercase__ : Tuple = ['on_prediction_step'] * len(trainer.get_eval_dataloader() ) + ['on_log', 'on_evaluate'] for _ in range(trainer.state.num_train_epochs ): expected_events.append('on_epoch_begin' ) for _ in range(a ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('on_log' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('on_save' ) expected_events.append('on_epoch_end' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def _UpperCAmelCase ( self ) -> Union[str, Any]: lowercase__ : int = self.get_trainer() lowercase__ : str = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , a ) # Callbacks passed at init are added to the default callbacks lowercase__ : str = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(a ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback lowercase__ : List[Any] = self.get_trainer(disable_tqdm=a ) lowercase__ : Optional[Any] = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , a ) def _UpperCAmelCase ( self ) -> Any: lowercase__ : int = DEFAULT_CALLBACKS.copy() + [ProgressCallback] lowercase__ : List[str] = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(a ) expected_callbacks.remove(a ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a ) lowercase__ : Optional[Any] = self.get_trainer() lowercase__ : List[Any] = trainer.pop_callback(a ) self.assertEqual(cb.__class__ , a ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a ) trainer.add_callback(a ) expected_callbacks.insert(0 , a ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a ) # We can also add, pop, or remove by instance lowercase__ : int = self.get_trainer() lowercase__ : List[str] = trainer.callback_handler.callbacks[0] trainer.remove_callback(a ) expected_callbacks.remove(a ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a ) lowercase__ : Tuple = self.get_trainer() lowercase__ : Dict = trainer.callback_handler.callbacks[0] lowercase__ : Union[str, Any] = trainer.pop_callback(a ) self.assertEqual(a , a ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a ) trainer.add_callback(a ) expected_callbacks.insert(0 , a ) self.check_callbacks_equality(trainer.callback_handler.callbacks , a ) def _UpperCAmelCase ( self ) -> Tuple: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='ignore' , category=a ) lowercase__ : Optional[Any] = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() lowercase__ : Any = trainer.callback_handler.callbacks[-2].events self.assertEqual(a , self.get_expected_events(a ) ) # Independent log/save/eval lowercase__ : List[str] = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() lowercase__ : int = trainer.callback_handler.callbacks[-2].events self.assertEqual(a , self.get_expected_events(a ) ) lowercase__ : Union[str, Any] = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() lowercase__ : Union[str, Any] = trainer.callback_handler.callbacks[-2].events self.assertEqual(a , self.get_expected_events(a ) ) lowercase__ : List[str] = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='steps' ) trainer.train() lowercase__ : Optional[int] = trainer.callback_handler.callbacks[-2].events self.assertEqual(a , self.get_expected_events(a ) ) lowercase__ : int = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='epoch' ) trainer.train() lowercase__ : str = trainer.callback_handler.callbacks[-2].events self.assertEqual(a , self.get_expected_events(a ) ) # A bit of everything lowercase__ : Any = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=1_0 , eval_steps=5 , evaluation_strategy='steps' , ) trainer.train() lowercase__ : Any = trainer.callback_handler.callbacks[-2].events self.assertEqual(a , self.get_expected_events(a ) ) # warning should be emitted for duplicated callbacks with patch('transformers.trainer_callback.logger.warning' ) as warn_mock: lowercase__ : str = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(a ) in warn_mock.call_args[0][0]
645
1
"""simple docstring""" from __future__ import annotations import typing from collections.abc import Iterable import numpy as np _UpperCamelCase : Any = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 _UpperCamelCase : str = typing.Union[np.floataa, int, float] # noqa: UP007 def a_ ( _lowerCAmelCase : Vector , _lowerCAmelCase : Vector ): '''simple docstring''' return np.sqrt(np.sum((np.asarray(_lowerCAmelCase ) - np.asarray(_lowerCAmelCase )) ** 2 ) ) def a_ ( _lowerCAmelCase : Vector , _lowerCAmelCase : Vector ): '''simple docstring''' return sum((va - va) ** 2 for va, va in zip(_lowerCAmelCase , _lowerCAmelCase ) ) ** (1 / 2) if __name__ == "__main__": def a_ ( ): '''simple docstring''' from timeit import timeit print('Without Numpy' ) print( timeit( 'euclidean_distance_no_np([1, 2, 3], [4, 5, 6])' , number=1_0000 , globals=globals() , ) ) print('With Numpy' ) print( timeit( 'euclidean_distance([1, 2, 3], [4, 5, 6])' , number=1_0000 , globals=globals() , ) ) benchmark()
645
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available _UpperCamelCase : str = { "configuration_gpt_neo": ["GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoConfig", "GPTNeoOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : Tuple = [ "GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoForCausalLM", "GPTNeoForQuestionAnswering", "GPTNeoForSequenceClassification", "GPTNeoForTokenClassification", "GPTNeoModel", "GPTNeoPreTrainedModel", "load_tf_weights_in_gpt_neo", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase : Dict = [ "FlaxGPTNeoForCausalLM", "FlaxGPTNeoModel", "FlaxGPTNeoPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys _UpperCamelCase : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
645
1
"""simple docstring""" import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class UpperCAmelCase_ : def __init__( self , a , a=1_3 , a=3_2 , a=2 , a=3 , a=1_6 , a=[1, 2, 1] , a=[2, 2, 4] , a=2 , a=2.0 , a=True , a=0.0 , a=0.0 , a=0.1 , a="gelu" , a=False , a=True , a=0.02 , a=1e-5 , a=True , a=None , a=True , a=1_0 , a=8 , a=["stage1", "stage2", "stage3"] , a=[1, 2, 3] , ) -> int: lowercase__ : int = parent lowercase__ : Union[str, Any] = batch_size lowercase__ : Dict = image_size lowercase__ : str = patch_size lowercase__ : Optional[Any] = num_channels lowercase__ : List[str] = embed_dim lowercase__ : Any = depths lowercase__ : Dict = num_heads lowercase__ : List[str] = window_size lowercase__ : int = mlp_ratio lowercase__ : Tuple = qkv_bias lowercase__ : Union[str, Any] = hidden_dropout_prob lowercase__ : str = attention_probs_dropout_prob lowercase__ : Tuple = drop_path_rate lowercase__ : List[str] = hidden_act lowercase__ : Optional[Any] = use_absolute_embeddings lowercase__ : Optional[Any] = patch_norm lowercase__ : Any = layer_norm_eps lowercase__ : List[Any] = initializer_range lowercase__ : List[str] = is_training lowercase__ : int = scope lowercase__ : Optional[int] = use_labels lowercase__ : List[Any] = type_sequence_label_size lowercase__ : List[str] = encoder_stride lowercase__ : Optional[Any] = out_features lowercase__ : Dict = out_indices def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ : Optional[Any] = None if self.use_labels: lowercase__ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ : Tuple = self.get_config() return config, pixel_values, labels def _UpperCAmelCase ( self ) -> Union[str, Any]: return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def _UpperCAmelCase ( self , a , a , a ) -> Dict: lowercase__ : Tuple = MaskFormerSwinModel(config=a ) model.to(a ) model.eval() lowercase__ : str = model(a ) lowercase__ : str = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) lowercase__ : Dict = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def _UpperCAmelCase ( self , a , a , a ) -> Optional[int]: lowercase__ : List[Any] = MaskFormerSwinBackbone(config=a ) model.to(a ) model.eval() lowercase__ : int = model(a ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [1_3, 1_6, 1_6, 1_6] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [1_6, 3_2, 6_4] ) # verify ValueError with self.parent.assertRaises(a ): lowercase__ : Dict = ['stem'] lowercase__ : List[str] = MaskFormerSwinBackbone(config=a ) def _UpperCAmelCase ( self ) -> str: lowercase__ : int = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ : Tuple = config_and_inputs lowercase__ : Union[str, Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _a , _a , unittest.TestCase): lowerCamelCase__ : Optional[int] = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) lowerCamelCase__ : List[str] = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} lowerCamelCase__ : str = False lowerCamelCase__ : Dict = False lowerCamelCase__ : Any = False lowerCamelCase__ : Dict = False lowerCamelCase__ : int = False def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : str = MaskFormerSwinModelTester(self ) lowercase__ : Tuple = ConfigTester(self , config_class=a , embed_dim=3_7 ) @require_torch_multi_gpu @unittest.skip( reason=( '`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with' ' `nn.DataParallel`' ) ) def _UpperCAmelCase ( self ) -> Optional[int]: pass def _UpperCAmelCase ( self ) -> Tuple: self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _UpperCAmelCase ( self ) -> str: return def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def _UpperCAmelCase ( self ) -> List[Any]: lowercase__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*a ) @unittest.skip('Swin does not use inputs_embeds' ) def _UpperCAmelCase ( self ) -> Tuple: pass @unittest.skip('Swin does not support feedforward chunking' ) def _UpperCAmelCase ( self ) -> Tuple: pass def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ , lowercase__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : List[str] = model_class(a ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase__ : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a , nn.Linear ) ) def _UpperCAmelCase ( self ) -> str: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Any = model_class(a ) lowercase__ : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : Optional[Any] = [*signature.parameters.keys()] lowercase__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a ) @unittest.skip(reason='MaskFormerSwin is only used as backbone and doesn\'t support output_attentions' ) def _UpperCAmelCase ( self ) -> List[Any]: pass @unittest.skip(reason='MaskFormerSwin is only used as an internal backbone' ) def _UpperCAmelCase ( self ) -> int: pass def _UpperCAmelCase ( self , a , a , a , a ) -> Tuple: lowercase__ : Dict = model_class(a ) model.to(a ) model.eval() with torch.no_grad(): lowercase__ : str = model(**self._prepare_for_class(a , a ) ) lowercase__ : List[Any] = outputs.hidden_states lowercase__ : str = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(a ) , a ) # Swin has a different seq_length lowercase__ : Dict = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ : Tuple = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ , lowercase__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: lowercase__ : List[str] = True self.check_hidden_states_output(a , a , a , a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : List[str] = True self.check_hidden_states_output(a , a , a , a ) def _UpperCAmelCase ( self ) -> Optional[int]: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : Union[str, Any] = 3 lowercase__ : str = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) lowercase__ : Tuple = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ : Optional[int] = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) lowercase__ : List[str] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: lowercase__ : List[str] = True self.check_hidden_states_output(a , a , a , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : int = True self.check_hidden_states_output(a , a , a , (padded_height, padded_width) ) @unittest.skip(reason='MaskFormerSwin doesn\'t have pretrained checkpoints' ) def _UpperCAmelCase ( self ) -> Optional[int]: pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def _UpperCAmelCase ( self ) -> Any: pass @unittest.skip(reason='This will be fixed once MaskFormerSwin is replaced by native Swin' ) def _UpperCAmelCase ( self ) -> Any: pass def _UpperCAmelCase ( self ) -> Any: lowercase__ , lowercase__ : str = self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(a ): lowercase__ : Union[str, Any] = 0 return t def check_equivalence(a , a , a , a={} ): with torch.no_grad(): lowercase__ : Optional[Any] = model(**a , return_dict=a , **a ) lowercase__ : Optional[int] = model(**a , return_dict=a , **a ).to_tuple() def recursive_check(a , a ): if isinstance(a , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(a , a ): recursive_check(a , a ) elif isinstance(a , a ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(a , a ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(a ) , set_nan_tensor_to_zero(a ) , atol=1e-5 ) , msg=( 'Tuple and dict output are not equal. Difference:' f""" {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:""" f""" {torch.isnan(a ).any()} and `inf`: {torch.isinf(a )}. Dict has""" f""" `nan`: {torch.isnan(a ).any()} and `inf`: {torch.isinf(a )}.""" ) , ) recursive_check(a , a ) for model_class in self.all_model_classes: lowercase__ : Any = model_class(a ) model.to(a ) model.eval() lowercase__ : Tuple = self._prepare_for_class(a , a ) lowercase__ : Optional[Any] = self._prepare_for_class(a , a ) check_equivalence(a , a , a ) lowercase__ : Any = self._prepare_for_class(a , a , return_labels=a ) lowercase__ : List[Any] = self._prepare_for_class(a , a , return_labels=a ) check_equivalence(a , a , a ) lowercase__ : Any = self._prepare_for_class(a , a ) lowercase__ : int = self._prepare_for_class(a , a ) check_equivalence(a , a , a , {'output_hidden_states': True} ) lowercase__ : Dict = self._prepare_for_class(a , a , return_labels=a ) lowercase__ : Optional[int] = self._prepare_for_class(a , a , return_labels=a ) check_equivalence(a , a , a , {'output_hidden_states': True} ) @require_torch class UpperCAmelCase_ ( unittest.TestCase , _a): lowerCamelCase__ : Dict = (MaskFormerSwinBackbone,) if is_torch_available() else () lowerCamelCase__ : Optional[int] = MaskFormerSwinConfig def _UpperCAmelCase ( self ) -> Dict: lowercase__ : Optional[int] = MaskFormerSwinModelTester(self ) def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ , lowercase__ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : int = inputs_dict['pixel_values'].shape[0] for backbone_class in self.all_model_classes: lowercase__ : Optional[Any] = backbone_class(a ) backbone.to(a ) backbone.eval() lowercase__ : Union[str, Any] = backbone(**a ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , a ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True lowercase__ : List[str] = backbone(**a , output_hidden_states=a ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) lowercase__ , lowercase__ , lowercase__ : int = hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: lowercase__ : List[Any] = backbone(**a , output_attentions=a ) self.assertIsNotNone(outputs.attentions )
645
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class UpperCAmelCase_ ( unittest.TestCase): def _UpperCAmelCase ( self , a ) -> str: for model_result in results.values(): for batch_size, sequence_length in zip(model_result['bs'] , model_result['ss'] ): lowercase__ : str = model_result['result'][batch_size][sequence_length] self.assertIsNotNone(a ) def _UpperCAmelCase ( self ) -> int: lowercase__ : Dict = 'sshleifer/tiny-gpt2' lowercase__ : int = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=a , inference=a , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=a , multi_process=a , ) lowercase__ : str = TensorFlowBenchmark(a ) lowercase__ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> int: lowercase__ : List[str] = 'sgugger/tiny-distilbert-classification' lowercase__ : int = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=a , inference=a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a , only_pretrain_model=a , ) lowercase__ : Optional[Any] = TensorFlowBenchmark(a ) lowercase__ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> Union[str, Any]: lowercase__ : Optional[int] = 'sshleifer/tiny-gpt2' lowercase__ : Union[str, Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=a , inference=a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a , ) lowercase__ : Optional[Any] = TensorFlowBenchmark(a ) lowercase__ : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ : Any = 'sshleifer/tiny-gpt2' lowercase__ : List[Any] = AutoConfig.from_pretrained(a ) lowercase__ : Any = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=a , inference=a , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=a , multi_process=a , ) lowercase__ : Tuple = TensorFlowBenchmark(a , [config] ) lowercase__ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> int: lowercase__ : Optional[Any] = 'sshleifer/tiny-gpt2' lowercase__ : List[str] = AutoConfig.from_pretrained(a ) lowercase__ : Any = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=a , inference=a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a , ) lowercase__ : List[str] = TensorFlowBenchmark(a , [config] ) lowercase__ : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> Tuple: lowercase__ : Optional[Any] = 'sshleifer/tiny-gpt2' lowercase__ : Any = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=a , inference=a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a , ) lowercase__ : Optional[Any] = TensorFlowBenchmark(a ) lowercase__ : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _UpperCAmelCase ( self ) -> str: lowercase__ : Optional[Any] = 'sshleifer/tiny-gpt2' lowercase__ : Optional[int] = AutoConfig.from_pretrained(a ) lowercase__ : str = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=a , inference=a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a , ) lowercase__ : str = TensorFlowBenchmark(a , [config] ) lowercase__ : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def _UpperCAmelCase ( self ) -> Optional[Any]: lowercase__ : List[str] = 'patrickvonplaten/t5-tiny-random' lowercase__ : Any = AutoConfig.from_pretrained(a ) lowercase__ : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=a , inference=a , sequence_lengths=[8] , batch_sizes=[1] , multi_process=a , ) lowercase__ : int = TensorFlowBenchmark(a , configs=[config] ) lowercase__ : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices('GPU' ) ) == 0 , 'Cannot do xla on CPU.' ) def _UpperCAmelCase ( self ) -> Any: lowercase__ : Any = 'sshleifer/tiny-gpt2' lowercase__ : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=a , inference=a , sequence_lengths=[8] , batch_sizes=[1] , use_xla=a , multi_process=a , ) lowercase__ : Any = TensorFlowBenchmark(a ) lowercase__ : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def _UpperCAmelCase ( self ) -> List[str]: lowercase__ : Any = 'sshleifer/tiny-gpt2' with tempfile.TemporaryDirectory() as tmp_dir: lowercase__ : List[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=a , save_to_csv=a , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(a , 'inf_time.csv' ) , inference_memory_csv_file=os.path.join(a , 'inf_mem.csv' ) , env_info_csv_file=os.path.join(a , 'env.csv' ) , multi_process=a , ) lowercase__ : Union[str, Any] = TensorFlowBenchmark(a ) benchmark.run() self.assertTrue(Path(os.path.join(a , 'inf_time.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(a , 'inf_mem.csv' ) ).exists() ) self.assertTrue(Path(os.path.join(a , 'env.csv' ) ).exists() ) def _UpperCAmelCase ( self ) -> Dict: lowercase__ : Tuple = 'sshleifer/tiny-gpt2' def _check_summary_is_not_empty(a ): self.assertTrue(hasattr(a , 'sequential' ) ) self.assertTrue(hasattr(a , 'cumulative' ) ) self.assertTrue(hasattr(a , 'current' ) ) self.assertTrue(hasattr(a , 'total' ) ) with tempfile.TemporaryDirectory() as tmp_dir: lowercase__ : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=a , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(a , 'log.txt' ) , log_print=a , trace_memory_line_by_line=a , eager_mode=a , multi_process=a , ) lowercase__ : Optional[int] = TensorFlowBenchmark(a ) lowercase__ : Optional[Any] = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(a , 'log.txt' ) ).exists() )
645
1